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,166 @@
<?php
namespace App\Modules\Billing\Infrastructure\Persistence\Repositories;
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\ExportStatus;
use App\Modules\Billing\Domain\Enums\LineKind;
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingInvoiceJobModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingInvoiceModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingJobHoursModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingLineModel;
use DateTimeImmutable;
use Illuminate\Support\Carbon;
/**
* Saving replaces a material's invoices with those of the aggregate: a
* draft is small, and its invoices have no identity of their own.
*/
class EloquentBillingExportRepository implements BillingExportRepository
{
public function findById(int $id, bool $lock = false): ?BillingExport
{
$model = BillingExportModel::query()
->when($lock, fn ($query) => $query->lockForUpdate())
->with(['invoices.jobs.hours', 'invoices.lines'])
->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function openDraftId(): ?int
{
$id = BillingExportModel::query()->where('status', ExportStatus::Draft)->value('id');
return $id === null ? null : (int) $id;
}
public function save(BillingExport $export): BillingExport
{
$model = $export->id() === null ? new BillingExportModel : BillingExportModel::query()->findOrFail($export->id());
$model->fill([
'status' => $export->status(),
'created_by' => $export->createdBy(),
'finalized_by' => $export->finalizedBy(),
'finalized_at' => $export->finalizedAt()?->format('Y-m-d H:i:s'),
]);
if ($export->id() === null) {
$model->created_at = Carbon::instance($export->createdAt());
}
$model->save();
BillingInvoiceModel::query()->where('billing_export_id', $model->id)->delete();
foreach ($export->invoices() as $invoiceOrder => $invoice) {
$invoiceModel = BillingInvoiceModel::query()->create([
'billing_export_id' => $model->id,
'customer_id' => $invoice->customerId(),
'billing_unit_id' => $invoice->billingUnitId(),
'customer_reference' => $invoice->reference(),
'sort_order' => $invoiceOrder,
]);
foreach ($invoice->jobs() as $jobOrder => $job) {
$jobModel = BillingInvoiceJobModel::query()->create([
'billing_invoice_id' => $invoiceModel->id,
'customer_job_id' => $job->jobId,
'customer_id' => $job->customerId,
'billing_unit_id' => $job->billingUnitId,
'customer_reference' => $job->reference,
'sort_order' => $jobOrder,
]);
foreach ($job->billableQuarters as $workTypeId => $quarters) {
BillingJobHoursModel::query()->create([
'billing_invoice_job_id' => $jobModel->id,
'work_type_id' => $workTypeId,
'billable_quarters' => $quarters,
]);
}
}
foreach ($invoice->lines() as $lineOrder => $line) {
BillingLineModel::query()->create([
'billing_invoice_id' => $invoiceModel->id,
'customer_job_id' => $line->jobId,
'kind' => $line->kind,
'work_type_id' => $line->workTypeId,
'expense_id' => $line->expenseId,
'description' => mb_substr($line->description, 0, 255),
'recorded_quarters' => $line->recordedQuarters,
'quantity_quarters' => $line->quantityQuarters,
'unit_price_cents' => $line->unitPriceCents,
'vat_basis_points' => $line->vatBasisPoints,
'net_cents' => $line->netCents,
'sort_order' => $lineOrder,
]);
}
}
return $this->findById($model->id) ?? throw new \LogicException('The billing material was not saved.');
}
public function delete(BillingExport $export): void
{
BillingExportModel::query()->whereKey($export->id())->delete();
}
public function fixedPriceBilledJobIds(array $jobIds): array
{
if ($jobIds === []) {
return [];
}
return BillingLineModel::query()
->whereIn('customer_job_id', $jobIds)
->where('kind', LineKind::FixedPrice)
->distinct()
->pluck('customer_job_id')
->map(fn ($id): int => (int) $id)
->values()
->all();
}
private function toEntity(BillingExportModel $model): BillingExport
{
$invoices = $model->invoices->map(fn (BillingInvoiceModel $invoice): BillingInvoice => BillingInvoice::reconstitute(
$invoice->jobs->map(fn (BillingInvoiceJobModel $job): DraftJob => new DraftJob(
$job->customer_job_id,
$job->customer_id,
$job->billing_unit_id,
$job->customer_reference,
$job->hours->mapWithKeys(fn (BillingJobHoursModel $hours): array => [$hours->work_type_id => $hours->billable_quarters])->all(),
))->values()->all(),
$invoice->lines->map(fn (BillingLineModel $line): InvoiceLine => new InvoiceLine(
$line->customer_job_id,
$line->kind,
$line->work_type_id,
$line->expense_id,
$line->description,
$line->recorded_quarters,
$line->quantity_quarters,
$line->unit_price_cents,
$line->vat_basis_points,
$line->net_cents,
))->values()->all(),
))->values()->all();
return BillingExport::reconstitute(
$model->id,
$model->status,
$model->created_by,
DateTimeImmutable::createFromInterface($model->created_at),
$model->finalized_by,
$model->finalized_at === null ? null : DateTimeImmutable::createFromInterface($model->finalized_at),
$invoices,
);
}
}
@@ -0,0 +1,56 @@
<?php
namespace App\Modules\Billing\Infrastructure\Persistence\Repositories;
use App\Modules\Billing\Application\Contracts\BillingQueries;
use App\Modules\Billing\Application\DTOs\ExportSummary;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingInvoiceJobModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingLineModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use DateTimeImmutable;
class EloquentBillingQueries implements BillingQueries
{
public function __construct(private UserAccountQueries $users) {}
public function exports(): array
{
$models = BillingExportModel::query()->withCount('invoices')->orderByDesc('id')->get();
if ($models->isEmpty()) {
return [];
}
$ids = $models->pluck('id')->all();
$jobCounts = BillingInvoiceJobModel::query()
->join('billing_invoices', 'billing_invoices.id', '=', 'billing_invoice_jobs.billing_invoice_id')
->whereIn('billing_invoices.billing_export_id', $ids)
->groupBy('billing_invoices.billing_export_id')
->selectRaw('billing_invoices.billing_export_id as export_id, count(*) as job_count')
->pluck('job_count', 'export_id');
$netSums = BillingLineModel::query()
->join('billing_invoices', 'billing_invoices.id', '=', 'billing_lines.billing_invoice_id')
->whereIn('billing_invoices.billing_export_id', $ids)
->groupBy('billing_invoices.billing_export_id')
->selectRaw('billing_invoices.billing_export_id as export_id, sum(billing_lines.net_cents) as net_cents')
->pluck('net_cents', 'export_id');
$names = $this->users->namesByIds($models->pluck('created_by')->merge($models->pluck('finalized_by'))->filter()->unique()->values()->all());
return $models->map(fn (BillingExportModel $model): ExportSummary => new ExportSummary(
$model->id,
$model->status,
DateTimeImmutable::createFromInterface($model->created_at),
$names[$model->created_by] ?? '',
$model->finalized_at === null ? null : DateTimeImmutable::createFromInterface($model->finalized_at),
$model->finalized_by === null ? null : ($names[$model->finalized_by] ?? ''),
(int) $model->getAttribute('invoices_count'),
(int) ($jobCounts[$model->id] ?? 0),
$model->status === ExportStatus::Created ? (int) ($netSums[$model->id] ?? 0) : null,
))->values()->all();
}
}