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:
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Billing\Application\Services;
|
||||
|
||||
use App\Modules\Billing\Application\DTOs\BillableExpense;
|
||||
use App\Modules\Billing\Application\DTOs\BillableJob;
|
||||
use App\Modules\Billing\Application\DTOs\HourlyRate;
|
||||
use App\Modules\Billing\Application\DTOs\JobHours;
|
||||
use App\Modules\Billing\Domain\Enums\BillingMode;
|
||||
use App\Modules\Billing\Domain\Enums\NotBillableReason;
|
||||
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
||||
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
|
||||
|
||||
/**
|
||||
* What a job may bill and its invoice lines (spec 12): hours per work type
|
||||
* at the hourly rates, or the quoted fixed price once, and the billable
|
||||
* expenses separately. Only approved hours are billed.
|
||||
*/
|
||||
final class BillingRules
|
||||
{
|
||||
/**
|
||||
* @param list<BillableExpense> $expenses
|
||||
* @param array<int, HourlyRate> $rates
|
||||
*/
|
||||
public function reasonNotBillable(BillableJob $job, JobHours $hours, array $expenses, bool $fixedPriceBilled, array $rates): ?NotBillableReason
|
||||
{
|
||||
if (! $job->isDone) {
|
||||
return NotBillableReason::WrongStatus;
|
||||
}
|
||||
|
||||
if ($job->mode === null || $job->isInternal) {
|
||||
return NotBillableReason::NotBillableBasis;
|
||||
}
|
||||
|
||||
if ($job->isConsumer && ! $job->hasIdentityCode) {
|
||||
return NotBillableReason::MissingIdentityCode;
|
||||
}
|
||||
|
||||
if ($job->mode === BillingMode::FixedPrice) {
|
||||
if (! $fixedPriceBilled && $job->quotedAmountCents === null) {
|
||||
return NotBillableReason::MissingQuotedAmount;
|
||||
}
|
||||
|
||||
return $fixedPriceBilled && $expenses === [] ? NotBillableReason::NothingToBill : null;
|
||||
}
|
||||
|
||||
if ($this->missingRateNames($hours, $rates) !== []) {
|
||||
return NotBillableReason::MissingHourlyRate;
|
||||
}
|
||||
|
||||
return $hours->approvedQuarters() === 0 && $expenses === [] ? NotBillableReason::NothingToBill : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Work types with approved hours but no hourly rate, for an hours job.
|
||||
*
|
||||
* @param array<int, HourlyRate> $rates
|
||||
* @return list<string>
|
||||
*/
|
||||
public function missingRateNames(JobHours $hours, array $rates): array
|
||||
{
|
||||
$names = [];
|
||||
|
||||
foreach ($hours->approvedByWorkType as $workTypeId => $quarters) {
|
||||
if ($quarters > 0 && ($rates[$workTypeId]->rateCents ?? null) === null) {
|
||||
$names[] = $rates[$workTypeId]->name ?? (string) $workTypeId;
|
||||
}
|
||||
}
|
||||
|
||||
sort($names);
|
||||
|
||||
return $names;
|
||||
}
|
||||
|
||||
/**
|
||||
* The job's lines: hours per work type by name (management's billable
|
||||
* hours or the approved ones) or the fixed price, then the expenses.
|
||||
*
|
||||
* @param array<int, int> $approvedByWorkType
|
||||
* @param list<BillableExpense> $expenses
|
||||
* @param array<int, HourlyRate> $rates
|
||||
* @return list<InvoiceLine>
|
||||
*/
|
||||
public function lines(BillableJob $job, DraftJob $draftJob, array $approvedByWorkType, array $expenses, bool $fixedPriceBilled, array $rates, int $vatBasisPoints): array
|
||||
{
|
||||
$lines = [];
|
||||
|
||||
if ($job->mode === BillingMode::FixedPrice) {
|
||||
if (! $fixedPriceBilled && $job->quotedAmountCents !== null) {
|
||||
$lines[] = InvoiceLine::fixedPrice($job->id, $job->label(), $job->quotedAmountCents, $vatBasisPoints);
|
||||
}
|
||||
} else {
|
||||
foreach ($this->sortedByName($approvedByWorkType, $rates) as $workTypeId => $approved) {
|
||||
$rate = $rates[$workTypeId] ?? null;
|
||||
|
||||
if ($approved <= 0 || $rate?->rateCents === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$lines[] = InvoiceLine::hours($job->id, $workTypeId, $rate->name, $approved, $draftJob->billableOf($workTypeId, $approved), $rate->rateCents, $vatBasisPoints);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($expenses as $expense) {
|
||||
$lines[] = InvoiceLine::expense($job->id, $expense->id, $expense->description, $expense->amountCents, $vatBasisPoints);
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $quarters
|
||||
* @param array<int, HourlyRate> $rates
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function sortedByName(array $quarters, array $rates): array
|
||||
{
|
||||
uksort($quarters, fn (int $a, int $b): int => strcmp($rates[$a]->name ?? '', $rates[$b]->name ?? '') ?: $a <=> $b);
|
||||
|
||||
return $quarters;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Billing\Application\Services;
|
||||
|
||||
use App\Modules\Billing\Application\Contracts\BillingExpenses;
|
||||
use App\Modules\Billing\Application\Contracts\BillingHours;
|
||||
use App\Modules\Billing\Application\Contracts\BillingJobs;
|
||||
use App\Modules\Billing\Application\Contracts\BillingPrices;
|
||||
use App\Modules\Billing\Application\DTOs\BillableExpense;
|
||||
use App\Modules\Billing\Application\DTOs\BillableJob;
|
||||
use App\Modules\Billing\Application\DTOs\HourlyRate;
|
||||
use App\Modules\Billing\Application\DTOs\JobHours;
|
||||
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
|
||||
use App\Modules\Billing\Domain\Enums\NotBillableReason;
|
||||
|
||||
/**
|
||||
* What the given jobs have to bill right now, read once for a page or a
|
||||
* use case: the jobs, their unbilled hours and expenses, whose fixed price
|
||||
* is already billed, the hourly rates and the VAT rate.
|
||||
*/
|
||||
final class BillingSnapshot
|
||||
{
|
||||
/** @var array<int, BillableJob> */
|
||||
public array $jobs = [];
|
||||
|
||||
/** @var array<int, JobHours> */
|
||||
public array $hours = [];
|
||||
|
||||
/** @var array<int, list<BillableExpense>> */
|
||||
public array $expenses = [];
|
||||
|
||||
/** @var array<int, true> */
|
||||
public array $fixedPriceBilled = [];
|
||||
|
||||
/** @var array<int, HourlyRate> */
|
||||
public array $rates = [];
|
||||
|
||||
public int $vatBasisPoints = 0;
|
||||
|
||||
public function __construct(
|
||||
private BillingJobs $billingJobs,
|
||||
private BillingHours $billingHours,
|
||||
private BillingExpenses $billingExpenses,
|
||||
private BillingPrices $prices,
|
||||
private BillingExportRepository $exports,
|
||||
public readonly BillingRules $rules,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param list<int> $jobIds
|
||||
* @param list<BillableJob> $knownJobs Jobs already read, e.g. the done ones.
|
||||
*/
|
||||
public function load(array $jobIds, array $knownJobs = []): self
|
||||
{
|
||||
$snapshot = clone $this;
|
||||
|
||||
foreach ($knownJobs as $job) {
|
||||
$snapshot->jobs[$job->id] = $job;
|
||||
}
|
||||
|
||||
$missing = array_values(array_diff($jobIds, array_keys($snapshot->jobs)));
|
||||
$snapshot->jobs += $this->billingJobs->find($missing);
|
||||
|
||||
$ids = array_keys($snapshot->jobs);
|
||||
$snapshot->hours = $this->billingHours->forJobs($ids);
|
||||
$snapshot->expenses = $this->billingExpenses->forJobs($ids);
|
||||
$snapshot->fixedPriceBilled = array_fill_keys($this->exports->fixedPriceBilledJobIds($ids), true);
|
||||
$snapshot->rates = $this->prices->hourlyRates();
|
||||
$snapshot->vatBasisPoints = $this->prices->defaultVatBasisPoints();
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
public function hoursOf(int $jobId): JobHours
|
||||
{
|
||||
return $this->hours[$jobId] ?? new JobHours($jobId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<BillableExpense>
|
||||
*/
|
||||
public function expensesOf(int $jobId): array
|
||||
{
|
||||
return $this->expenses[$jobId] ?? [];
|
||||
}
|
||||
|
||||
public function isFixedPriceBilled(int $jobId): bool
|
||||
{
|
||||
return isset($this->fixedPriceBilled[$jobId]);
|
||||
}
|
||||
|
||||
public function reasonNotBillable(BillableJob $job): ?NotBillableReason
|
||||
{
|
||||
return $this->rules->reasonNotBillable($job, $this->hoursOf($job->id), $this->expensesOf($job->id), $this->isFixedPriceBilled($job->id), $this->rates);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function missingRateNames(BillableJob $job): array
|
||||
{
|
||||
return $this->rules->missingRateNames($this->hoursOf($job->id), $this->rates);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user