Files
onboard/app/Services/MetricCalculators/AverageBedDaysCalculator.php
2026-04-24 16:46:10 +09:00

48 lines
1.4 KiB
PHP

<?php
// app/Services/MetricCalculators/AverageBedDaysCalculator.php
namespace App\Services\MetricCalculators;
use App\Contracts\MetricCalculatorInterface;
use App\Services\Base\BaseMetricService;
use Illuminate\Support\Facades\DB;
class AverageBedDaysCalculator extends BaseMetricService implements MetricCalculatorInterface
{
public function getMetricId(): int
{
return 18;
}
public function calculate(array $departmentIds, string $startDate, string $endDate): array
{
if (empty($departmentIds)) {
return [];
}
$results = DB::table('reports as r')
->join('metrika_results as mr', 'r.report_id', '=', 'mr.rf_report_id')
->whereIn('r.rf_department_id', $departmentIds)
->where('mr.rf_metrika_item_id', 18)
->where('r.period_start', '>=', $startDate)
->where('r.period_end', '<', $endDate)
->select(
'r.rf_department_id',
DB::raw('AVG(CAST(mr.value AS DECIMAL)) as avg_value')
)
->groupBy('r.rf_department_id')
->get()
->keyBy('rf_department_id');
$averages = [];
foreach ($departmentIds as $deptId) {
$averages[$deptId] = isset($results[$deptId])
? round((float) $results[$deptId]->avg_value, 1)
: 0;
}
return $averages;
}
}