hours->between($period) as $entry) { $quarters[$entry->jobId] = ($quarters[$entry->jobId] ?? 0) + $entry->quarters; } $expenseCosts = $this->expenses->costsByJob($period); $revenue = $this->revenue->byJob($period); $hourlyCost = $this->catalog->internalHourlyCostCents(); $jobIds = array_values(array_unique([...array_keys($quarters), ...array_keys($expenseCosts), ...array_keys($revenue)])); $jobs = $this->jobs->infoOf($jobIds); $rows = []; foreach ($jobs as $job) { if ($job->isInternal && ! $includeInternal) { continue; } $billed = $revenue[$job->id] ?? null; $rows[] = new JobProfit($job, Profit::of( $quarters[$job->id] ?? 0, $billed->billedQuarters ?? 0, $billed->workCents ?? 0, $billed->expenseCents ?? 0, $expenseCosts[$job->id] ?? 0, $hourlyCost, )); } usort($rows, fn (JobProfit $a, JobProfit $b): int => strcmp($a->job->number, $b->job->number)); $total = array_reduce($rows, fn (Profit $sum, JobProfit $row): Profit => $sum->plus($row->profit), Profit::of(0, 0, 0, 0, 0, $hourlyCost)); return new ProfitabilityReport($rows, $this->byServiceUnit($rows, $hourlyCost), $total, $hourlyCost); } /** * @param list $rows * @return list */ private function byServiceUnit(array $rows, ?int $hourlyCost): array { $names = $this->catalog->serviceUnits(); $profits = []; $jobCounts = []; foreach ($rows as $row) { $unitIds = $row->job->serviceUnitIds === [] ? [0] : $row->job->serviceUnitIds; foreach ($row->profit->split(count($unitIds)) as $index => $share) { $unitId = $unitIds[$index]; $profits[$unitId] = ($profits[$unitId] ?? Profit::of(0, 0, 0, 0, 0, $hourlyCost))->plus($share); $jobCounts[$unitId] = ($jobCounts[$unitId] ?? 0) + 1; } } $result = []; foreach ([...array_keys($names), 0] as $unitId) { if (isset($profits[$unitId])) { $result[] = new ServiceUnitProfit($unitId, $names[$unitId] ?? '', $jobCounts[$unitId], $profits[$unitId]); } } return $result; } }