transactions->run(function () use ($exportId, $actorUserId): int { $export = $this->exports->findById($exportId, lock: true) ?? throw new BillingExportNotFound($exportId); $export->ensureDraft(); $snapshot = $this->snapshots->load($export->period(), $export->jobIds()); foreach ($export->jobIds() as $jobId) { $job = $snapshot->jobs[$jobId] ?? throw new JobNotBillable($jobId, NotBillableReason::WrongStatus); $reason = $snapshot->reasonNotBillable($job); if ($reason !== null) { throw new JobNotBillable($jobId, $reason); } } $linesByJob = []; foreach ($export->jobs() as $draftJob) { $job = $snapshot->jobs[$draftJob->jobId]; $billedHours = $this->hours->markBilled($job->id, $exportId); $billedExpenseIds = array_flip($this->expenses->markBilled($job->id, $exportId)); $billedExpenses = array_values(array_filter( $snapshot->expensesOf($job->id), fn (BillableExpense $expense): bool => isset($billedExpenseIds[$expense->id]), )); $linesByJob[$job->id] = $snapshot->linesOf($job, $draftJob, $billedHours, $billedExpenses); if ($job->mode !== BillingMode::MonthlyFee) { $this->jobs->markInvoiced($job->id, $actorUserId); } } $export->finalize($linesByJob, $this->exports->nextNumber(), $actorUserId, $this->clock->now()); $this->exports->save($export); return count($export->invoices()); }); } }