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,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Contracts;
use App\Modules\Billing\Application\DTOs\BillableExpense;
/**
* The jobs' billable expenses, from the Expenses module.
*/
interface BillingExpenses
{
/**
* Billable, unbilled expenses, oldest first.
*
* @param list<int> $jobIds
* @return array<int, list<BillableExpense>> Keyed by job id, every job included.
*/
public function forJobs(array $jobIds): array;
/**
* Marks the job's billable, unbilled expenses billed.
*
* @return list<int> Ids of the expenses marked.
*/
public function markBilled(int $jobId, int $billingExportId): array;
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Contracts;
use App\Modules\Billing\Application\DTOs\JobHours;
/**
* The jobs' hours for billing, from the TimeTracking module.
*/
interface BillingHours
{
/**
* @param list<int> $jobIds
* @return array<int, JobHours> Keyed by job id, every job included.
*/
public function forJobs(array $jobIds): array;
/**
* Marks the job's approved, unbilled hours billed.
*
* @return array<int, int> The quarters marked, keyed by work type id.
*/
public function markBilled(int $jobId, int $billingExportId): array;
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Contracts;
use App\Modules\Billing\Application\DTOs\BillableJob;
/**
* Customer jobs for billing, from the Jobs and Customers modules.
*/
interface BillingJobs
{
/**
* Done jobs, by job number.
*
* @return list<BillableJob>
*/
public function done(): array;
/**
* @param list<int> $jobIds
* @return array<int, BillableJob> Keyed by id; unknown ids are left out.
*/
public function find(array $jobIds): array;
/**
* Moves the job to "Lasku luotu", recorded in its history.
*/
public function markInvoiced(int $jobId, int $actorUserId): void;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Contracts;
use App\Modules\Billing\Application\DTOs\HourlyRate;
/**
* Hourly rates and the VAT rate for billing, from the price list.
*/
interface BillingPrices
{
/**
* @return array<int, HourlyRate> Keyed by work type id, inactive work types included.
*/
public function hourlyRates(): array;
/**
* The default VAT rate in hundredths of a percent (2550 = 25,5 %).
*/
public function defaultVatBasisPoints(): int;
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Contracts;
use App\Modules\Billing\Application\DTOs\ExportSummary;
/**
* Read side of billing materials for lists.
*/
interface BillingQueries
{
/**
* Every billing material, newest first.
*
* @return list<ExportSummary>
*/
public function exports(): array;
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
use App\Modules\Billing\Domain\Enums\NotBillableReason;
/**
* A done job that is not on the draft: what it has to bill, and why it
* cannot be added, if it cannot.
*/
final readonly class AvailableJob
{
/**
* @param list<string> $missingRateNames
*/
public function __construct(
public BillableJob $job,
public int $approvedQuarters,
public int $unapprovedQuarters,
public int $expenseCount,
public ?NotBillableReason $reason,
public array $missingRateNames = [],
) {}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
/**
* A billable, unbilled expense of a job, with its amount to bill without VAT.
*/
final readonly class BillableExpense
{
public function __construct(
public int $id,
public int $jobId,
public string $description,
public int $amountCents,
) {}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
/**
* A customer job as billing sees it. A null mode means the job is not
* billed this way (not billable, or billed monthly).
*/
final readonly class BillableJob
{
public function __construct(
public int $id,
public string $number,
public string $name,
public int $customerId,
public string $customerName,
public bool $isConsumer,
public bool $isInternal,
public bool $hasIdentityCode,
public ?int $billingUnitId,
public ?string $billingUnitName,
public ?string $customerReference,
public ?BillingMode $mode,
public ?int $quotedAmountCents,
public bool $isDone,
) {}
/**
* E.g. "2026-0005 Messuvideo".
*/
public function label(): string
{
return $this->number.' '.$this->name;
}
public function toDraftJob(): DraftJob
{
return new DraftJob($this->id, $this->customerId, $this->billingUnitId, $this->customerReference);
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use DateTimeImmutable;
/**
* A billing material on the list. The sum without VAT is known once it is created.
*/
final readonly class ExportSummary
{
public function __construct(
public int $id,
public ExportStatus $status,
public DateTimeImmutable $createdAt,
public string $createdByName,
public ?DateTimeImmutable $finalizedAt,
public ?string $finalizedByName,
public int $invoiceCount,
public int $jobCount,
public ?int $netCents,
) {}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
use DateTimeImmutable;
/**
* A billing material for its page: a draft with its preview and the done
* jobs that may be added, or a created material with its lines.
*/
final readonly class ExportView
{
/**
* @param list<InvoiceView> $invoices
* @param list<AvailableJob> $availableJobs
*/
public function __construct(
public int $id,
public ExportStatus $status,
public DateTimeImmutable $createdAt,
public string $createdByName,
public ?DateTimeImmutable $finalizedAt,
public ?string $finalizedByName,
public array $invoices,
public InvoiceTotals $totals,
public array $availableJobs = [],
) {}
public function isDraft(): bool
{
return $this->status === ExportStatus::Draft;
}
public function jobCount(): int
{
return array_sum(array_map(fn (InvoiceView $invoice): int => count($invoice->jobs), $this->invoices));
}
/**
* Whether some job on the draft cannot be billed as it is.
*/
public function hasProblems(): bool
{
foreach ($this->invoices as $invoice) {
foreach ($invoice->jobs as $job) {
if ($job->problem !== null) {
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
/**
* A work type's name and hourly rate without VAT, if it has one.
*/
final readonly class HourlyRate
{
public function __construct(
public int $workTypeId,
public string $name,
public ?int $rateCents,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
/**
* A work type's hours on a draft invoice: approved and billable quarters,
* and the line's sum without VAT.
*/
final readonly class HoursRow
{
public function __construct(
public int $workTypeId,
public string $name,
public int $approvedQuarters,
public int $billableQuarters,
public bool $isAdjusted,
public ?int $rateCents,
public int $netCents,
) {}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Billing\Domain\Enums\NotBillableReason;
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
/**
* A job on an invoice of a billing material: its hours per work type (on a
* draft), its lines, and on a draft what may stop it from being billed.
*/
final readonly class InvoiceJobView
{
/**
* @param list<HoursRow> $hours
* @param list<InvoiceLine> $lines
* @param list<string> $missingRateNames
*/
public function __construct(
public int $jobId,
public string $number,
public string $name,
public ?BillingMode $mode,
public array $hours,
public array $lines,
public int $unapprovedQuarters,
public ?NotBillableReason $problem,
public array $missingRateNames = [],
) {}
public function label(): string
{
return $this->number.' '.$this->name;
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
/**
* An invoice of a billing material for its page.
*/
final readonly class InvoiceView
{
/**
* @param list<InvoiceJobView> $jobs
* @param array<int, list<MergeTarget>> $mergeTargets Invoices each job may move to, keyed by job id.
*/
public function __construct(
public int $key,
public string $customerName,
public ?string $billingUnitName,
public ?string $reference,
public array $jobs,
public InvoiceTotals $totals,
public array $mergeTargets = [],
) {}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
/**
* A job's unbilled hours in quarters of an hour: approved ones by work
* type, and those still waiting for approval (never billed).
*/
final readonly class JobHours
{
/**
* @param array<int, int> $approvedByWorkType Keyed by work type id.
*/
public function __construct(
public int $jobId,
public array $approvedByWorkType = [],
public int $unapprovedQuarters = 0,
) {}
public function approvedQuarters(): int
{
return array_sum($this->approvedByWorkType);
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
/**
* An invoice a job may be moved to, named by its jobs.
*/
final readonly class MergeTarget
{
public function __construct(
public int $invoiceKey,
public string $label,
) {}
}
@@ -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;
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
use App\Modules\Billing\Application\Services\BillingSnapshot;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Enums\NotBillableReason;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
use App\Modules\Billing\Domain\Exceptions\JobNotBillable;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Adds a done job to the draft as an invoice of its own, if it has
* something to bill and nothing stops it from being billed.
*/
final class AddJobToDraft
{
use ChangesDraft;
public function __construct(
BillingExportRepository $exports,
TransactionManager $transactions,
private BillingSnapshot $snapshots,
) {
$this->exports = $exports;
$this->transactions = $transactions;
}
/**
* @throws BillingExportNotFound
* @throws ExportNotDraft
* @throws JobAlreadyInDraft
* @throws JobNotBillable
*/
public function execute(int $exportId, int $jobId): void
{
$this->changeDraft($exportId, function (BillingExport $export) use ($jobId): void {
$snapshot = $this->snapshots->load([$jobId]);
$job = $snapshot->jobs[$jobId] ?? throw new JobNotBillable($jobId, NotBillableReason::WrongStatus);
$reason = $snapshot->reasonNotBillable($job);
if ($reason !== null) {
throw new JobNotBillable($jobId, $reason);
}
$export->addJob($job->toDraftJob());
});
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Loads a draft locked, lets the use case change it and saves it.
*/
trait ChangesDraft
{
private BillingExportRepository $exports;
private TransactionManager $transactions;
/**
* @param-immediately-invoked-callable $change
*
* @param callable(BillingExport): void $change
*
* @throws BillingExportNotFound
* @throws ExportNotDraft
*/
private function changeDraft(int $exportId, callable $change): void
{
$this->transactions->run(function () use ($exportId, $change): void {
$export = $this->exports->findById($exportId, lock: true) ?? throw new BillingExportNotFound($exportId);
$export->ensureDraft();
$change($export);
$this->exports->save($export);
});
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Throws a draft away. Nothing was billed yet, so the jobs stay as they are.
*/
final class DiscardDraft
{
public function __construct(
private BillingExportRepository $exports,
private TransactionManager $transactions,
) {}
/**
* @throws BillingExportNotFound
* @throws ExportNotDraft
*/
public function execute(int $exportId): void
{
$this->transactions->run(function () use ($exportId): void {
$export = $this->exports->findById($exportId, lock: true) ?? throw new BillingExportNotFound($exportId);
$export->ensureDraft();
$this->exports->delete($export);
});
}
}
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
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\DTOs\BillableExpense;
use App\Modules\Billing\Application\Services\BillingSnapshot;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Enums\NotBillableReason;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Billing\Domain\Exceptions\JobNotBillable;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Creates the billing material from its draft (spec 12), all or nothing:
* checks every job again, marks the approved hours and billable expenses
* billed, forms the invoice lines from what was marked with the current
* prices, and moves the jobs to "Lasku luotu".
*/
final class FinalizeBillingExport
{
public function __construct(
private BillingExportRepository $exports,
private BillingJobs $jobs,
private BillingHours $hours,
private BillingExpenses $expenses,
private BillingSnapshot $snapshots,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int How many invoices the material has.
*
* @throws BillingExportNotFound
* @throws ExportNotDraft
* @throws ExportEmpty
* @throws JobNotBillable
*/
public function execute(int $exportId, int $actorUserId): int
{
return $this->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->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->rules->lines($job, $draftJob, $billedHours, $billedExpenses, $snapshot->isFixedPriceBilled($job->id), $snapshot->rates, $snapshot->vatBasisPoints);
$this->jobs->markInvoiced($job->id, $actorUserId);
}
$export->finalize($linesByJob, $actorUserId, $this->clock->now());
$this->exports->save($export);
return count($export->invoices());
});
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
use App\Modules\Billing\Domain\Exceptions\JobNotInDraft;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Moves a job to another invoice of the draft, when the jobs may be billed together (same customer and billing unit, no two references).
*/
final class MoveJobToInvoice
{
use ChangesDraft;
public function __construct(BillingExportRepository $exports, TransactionManager $transactions)
{
$this->exports = $exports;
$this->transactions = $transactions;
}
/**
* @throws BillingExportNotFound
* @throws ExportNotDraft
* @throws JobNotInDraft
* @throws InvoicesCannotMerge
*/
public function execute(int $exportId, int $jobId, int $invoiceKey): void
{
$this->changeDraft($exportId, function (BillingExport $export) use ($jobId, $invoiceKey): void {
$export->moveJob($jobId, $invoiceKey);
});
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Exceptions\DraftAlreadyOpen;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Opens a new billing material draft. There is one draft at a time, so
* two people never bill the same jobs on separate drafts.
*/
final class OpenBillingDraft
{
public function __construct(
private BillingExportRepository $exports,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The draft's id.
*
* @throws DraftAlreadyOpen
*/
public function execute(int $actorUserId): int
{
return $this->transactions->run(function () use ($actorUserId): int {
if ($this->exports->openDraftId() !== null) {
throw new DraftAlreadyOpen;
}
return (int) $this->exports->save(BillingExport::startDraft($actorUserId, $this->clock->now()))->id();
});
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Billing\Domain\Exceptions\JobNotInDraft;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes a job off the draft; an invoice left without jobs goes too.
*/
final class RemoveJobFromDraft
{
use ChangesDraft;
public function __construct(BillingExportRepository $exports, TransactionManager $transactions)
{
$this->exports = $exports;
$this->transactions = $transactions;
}
/**
* @throws BillingExportNotFound
* @throws ExportNotDraft
* @throws JobNotInDraft
*/
public function execute(int $exportId, int $jobId): void
{
$this->changeDraft($exportId, function (BillingExport $export) use ($jobId): void {
$export->removeJob($jobId);
});
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Billing\Domain\Exceptions\JobNotInDraft;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Moves a job off a combined invoice to an invoice of its own.
*/
final class SeparateJob
{
use ChangesDraft;
public function __construct(BillingExportRepository $exports, TransactionManager $transactions)
{
$this->exports = $exports;
$this->transactions = $transactions;
}
/**
* @throws BillingExportNotFound
* @throws ExportNotDraft
* @throws JobNotInDraft
*/
public function execute(int $exportId, int $jobId): void
{
$this->changeDraft($exportId, function (BillingExport $export) use ($jobId): void {
$export->separate($jobId);
});
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\UseCases;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
use App\Modules\Billing\Domain\Exceptions\JobNotInDraft;
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Sets the hours management bills for a work type of a job (spec 12); an
* empty value returns to the approved hours. Both are kept on the line.
*/
final class SetBillableHours
{
use ChangesDraft;
public function __construct(BillingExportRepository $exports, TransactionManager $transactions)
{
$this->exports = $exports;
$this->transactions = $transactions;
}
/**
* @param string $hours E.g. "12,5"; empty for the approved hours.
*
* @throws BillingExportNotFound
* @throws ExportNotDraft
* @throws JobNotInDraft
* @throws InvalidBillableHours
*/
public function execute(int $exportId, int $jobId, int $workTypeId, string $hours): void
{
$quarters = DraftJob::parseHours($hours);
$this->changeDraft($exportId, function (BillingExport $export) use ($jobId, $workTypeId, $quarters): void {
$export->setBillableQuarters($jobId, $workTypeId, $quarters);
});
}
}