Add the billing material with drafts, combined invoices and billed marks

Management builds the monthly billing material (laskuaineisto) as a
draft: done jobs are added as invoices of their own, combined when the
customer, billing unit and reference allow it, and their billable hours
are set per work type. Creating the material checks the jobs again,
marks the approved hours and billable expenses billed, forms invoice
lines with price and VAT snapshots and moves the jobs to "Lasku luotu".
Fixed price jobs bill their quoted amount once. Billed hours keep their
approval and billed expenses can no longer change. The Fennoa export
and monthly fee lines come later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 13:08:24 +02:00
co-authored by Claude Opus 5.5
parent 6de5d9bef1
commit 97bd23bed5
98 changed files with 4887 additions and 22 deletions
@@ -0,0 +1,183 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Services;
use App\Modules\Billing\Application\Contracts\BillingJobs;
use App\Modules\Billing\Application\DTOs\AvailableJob;
use App\Modules\Billing\Application\DTOs\BillableJob;
use App\Modules\Billing\Application\DTOs\ExportView;
use App\Modules\Billing\Application\DTOs\HoursRow;
use App\Modules\Billing\Application\DTOs\InvoiceJobView;
use App\Modules\Billing\Application\DTOs\InvoiceView;
use App\Modules\Billing\Application\DTOs\MergeTarget;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Entities\BillingInvoice;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
/**
* Builds a billing material's page: a draft is previewed with the hours
* and expenses the jobs have now, and a created material shows its lines.
*/
final class ExportViews
{
public function __construct(
private BillingExportRepository $exports,
private BillingJobs $jobs,
private BillingSnapshot $snapshots,
private UserAccountQueries $users,
) {}
public function of(int $exportId): ?ExportView
{
$export = $this->exports->findById($exportId);
if ($export === null) {
return null;
}
$done = $export->isDraft() ? $this->jobs->done() : [];
$snapshot = $this->snapshots->load($export->jobIds(), $done);
$onDraft = array_flip($export->jobIds());
$invoices = [];
foreach ($export->invoices() as $invoice) {
$invoices[] = $this->invoiceView($export, $invoice, $snapshot);
}
$available = [];
foreach ($done as $job) {
if (! isset($onDraft[$job->id])) {
$hours = $snapshot->hoursOf($job->id);
$available[] = new AvailableJob(
$job,
$hours->approvedQuarters(),
$hours->unapprovedQuarters,
count($snapshot->expensesOf($job->id)),
$snapshot->reasonNotBillable($job),
$job->mode === BillingMode::Hours ? $snapshot->missingRateNames($job) : [],
);
}
}
$names = $this->users->namesByIds(array_values(array_filter([$export->createdBy(), $export->finalizedBy()])));
return new ExportView(
(int) $export->id(),
$export->status(),
$export->createdAt(),
$names[$export->createdBy()] ?? '',
$export->finalizedAt(),
$export->finalizedBy() === null ? null : ($names[$export->finalizedBy()] ?? ''),
$invoices,
InvoiceTotals::sum(array_map(fn (InvoiceView $invoice): InvoiceTotals => $invoice->totals, $invoices)),
$available,
);
}
private function invoiceView(BillingExport $export, BillingInvoice $invoice, BillingSnapshot $snapshot): InvoiceView
{
$jobViews = [];
$lines = [];
$mergeTargets = [];
foreach ($invoice->jobs() as $draftJob) {
$job = $snapshot->jobs[$draftJob->jobId] ?? null;
$view = $export->isDraft()
? $this->draftJobView($draftJob, $job, $snapshot)
: $this->createdJobView($draftJob, $job, $invoice->lines());
$jobViews[] = $view;
array_push($lines, ...$view->lines);
if ($export->isDraft()) {
$mergeTargets[$draftJob->jobId] = $this->mergeTargets($export, $invoice, $draftJob, $snapshot);
}
}
$first = $snapshot->jobs[$invoice->key()] ?? null;
return new InvoiceView(
$invoice->key(),
$first->customerName ?? '',
$first?->billingUnitName,
$invoice->reference(),
$jobViews,
InvoiceTotals::of($lines),
$mergeTargets,
);
}
private function draftJobView(DraftJob $draftJob, ?BillableJob $job, BillingSnapshot $snapshot): InvoiceJobView
{
if ($job === null) {
return new InvoiceJobView($draftJob->jobId, '', '', null, [], [], 0, null);
}
$hours = $snapshot->hoursOf($job->id);
$lines = $snapshot->rules->lines($job, $draftJob, $hours->approvedByWorkType, $snapshot->expensesOf($job->id), $snapshot->isFixedPriceBilled($job->id), $snapshot->rates, $snapshot->vatBasisPoints);
$rows = [];
foreach ($snapshot->rules->sortedByName($hours->approvedByWorkType, $snapshot->rates) as $workTypeId => $approved) {
$rate = $snapshot->rates[$workTypeId] ?? null;
$billable = $draftJob->billableOf($workTypeId, $approved);
$line = $rate?->rateCents === null ? null : InvoiceLine::hours($job->id, $workTypeId, $rate->name, $approved, $billable, $rate->rateCents, $snapshot->vatBasisPoints);
$rows[] = new HoursRow($workTypeId, $rate->name ?? '', $approved, $billable, isset($draftJob->billableQuarters[$workTypeId]), $rate?->rateCents, $line->netCents ?? 0);
}
return new InvoiceJobView(
$job->id,
$job->number,
$job->name,
$job->mode,
$rows,
$lines,
$hours->unapprovedQuarters,
$snapshot->reasonNotBillable($job),
$job->mode === BillingMode::Hours ? $snapshot->missingRateNames($job) : [],
);
}
/**
* @param list<InvoiceLine> $invoiceLines
*/
private function createdJobView(DraftJob $draftJob, ?BillableJob $job, array $invoiceLines): InvoiceJobView
{
return new InvoiceJobView(
$draftJob->jobId,
$job->number ?? '',
$job->name ?? '',
$job?->mode,
[],
array_values(array_filter($invoiceLines, fn (InvoiceLine $line): bool => $line->jobId === $draftJob->jobId)),
0,
null,
);
}
/**
* @return list<MergeTarget>
*/
private function mergeTargets(BillingExport $export, BillingInvoice $current, DraftJob $job, BillingSnapshot $snapshot): array
{
$targets = [];
foreach ($export->invoices() as $invoice) {
if ($invoice === $current || $invoice->refusalFor($job) !== null) {
continue;
}
$labels = array_map(fn (DraftJob $other): string => ($snapshot->jobs[$other->jobId] ?? null)?->label() ?? (string) $other->jobId, $invoice->jobs());
$targets[] = new MergeTarget($invoice->key(), implode(', ', $labels));
}
return $targets;
}
}