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);
});
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Contracts;
use App\Modules\Billing\Domain\Entities\BillingExport;
interface BillingExportRepository
{
/**
* The material with its invoices, jobs, billable hours and lines. With
* $lock the row stays locked until the transaction ends.
*/
public function findById(int $id, bool $lock = false): ?BillingExport;
/**
* The id of the open draft, if there is one.
*/
public function openDraftId(): ?int;
/**
* Inserts a new material or replaces a stored one's invoices, and returns it.
*/
public function save(BillingExport $export): BillingExport;
public function delete(BillingExport $export): void;
/**
* The jobs among the given ones whose fixed price is already on a created material.
*
* @param list<int> $jobIds
* @return list<int>
*/
public function fixedPriceBilledJobIds(array $jobIds): array;
}
@@ -0,0 +1,270 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Entities;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
use App\Modules\Billing\Domain\Exceptions\JobNotInDraft;
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
use DateTimeImmutable;
/**
* A billing material (laskuaineisto): invoices made of finished jobs.
* Management works on it as a draft, adding jobs, combining them on
* invoices and setting billable hours; creating it forms the invoice lines
* and locks it.
*/
final class BillingExport
{
/**
* @param list<BillingInvoice> $invoices
*/
private function __construct(
private ?int $id,
private ExportStatus $status,
private int $createdBy,
private DateTimeImmutable $createdAt,
private ?int $finalizedBy,
private ?DateTimeImmutable $finalizedAt,
private array $invoices,
) {}
public static function startDraft(int $createdBy, DateTimeImmutable $now): self
{
return new self(null, ExportStatus::Draft, $createdBy, $now, null, null, []);
}
/**
* @param list<BillingInvoice> $invoices
*/
public static function reconstitute(int $id, ExportStatus $status, int $createdBy, DateTimeImmutable $createdAt, ?int $finalizedBy, ?DateTimeImmutable $finalizedAt, array $invoices): self
{
return new self($id, $status, $createdBy, $createdAt, $finalizedBy, $finalizedAt, $invoices);
}
/**
* Adds a job as an invoice of its own.
*
* @throws ExportNotDraft
* @throws JobAlreadyInDraft
*/
public function addJob(DraftJob $job): void
{
$this->ensureDraft();
if ($this->invoiceOf($job->jobId) !== null) {
throw new JobAlreadyInDraft($job->jobId);
}
$this->invoices[] = BillingInvoice::for($job);
}
/**
* @throws ExportNotDraft
* @throws JobNotInDraft
*/
public function removeJob(int $jobId): void
{
$this->ensureDraft();
$this->requireInvoiceOf($jobId)->remove($jobId);
$this->dropEmptyInvoices();
}
/**
* Moves a job to the invoice of another job.
*
* @throws ExportNotDraft
* @throws JobNotInDraft
* @throws InvoicesCannotMerge
*/
public function moveJob(int $jobId, int $targetJobId): void
{
$this->ensureDraft();
$from = $this->requireInvoiceOf($jobId);
$to = $this->requireInvoiceOf($targetJobId);
if ($from === $to) {
return;
}
$job = $from->job($jobId);
assert($job !== null);
$refusal = $to->refusalFor($job);
if ($refusal !== null) {
throw new InvoicesCannotMerge($refusal);
}
$from->remove($jobId);
$to->add($job);
$this->dropEmptyInvoices();
}
/**
* Moves a job off a combined invoice to an invoice of its own.
*
* @throws ExportNotDraft
* @throws JobNotInDraft
*/
public function separate(int $jobId): void
{
$this->ensureDraft();
$from = $this->requireInvoiceOf($jobId);
if (count($from->jobs()) === 1) {
return;
}
$job = $from->job($jobId);
assert($job !== null);
$from->remove($jobId);
$this->invoices[] = BillingInvoice::for($job);
}
/**
* Sets management's billable hours of a work type; null returns to the approved hours.
*
* @throws ExportNotDraft
* @throws JobNotInDraft
* @throws InvalidBillableHours
*/
public function setBillableQuarters(int $jobId, int $workTypeId, ?int $quarters): void
{
$this->ensureDraft();
$invoice = $this->requireInvoiceOf($jobId);
$job = $invoice->job($jobId);
assert($job !== null);
$invoice->replace($job->withBillableQuarters($workTypeId, $quarters));
}
/**
* Forms the invoice lines and locks the material.
*
* @param array<int, list<InvoiceLine>> $linesByJob Keyed by job id.
*
* @throws ExportNotDraft
* @throws ExportEmpty
*/
public function finalize(array $linesByJob, int $finalizedBy, DateTimeImmutable $now): void
{
$this->ensureDraft();
if ($this->invoices === []) {
throw new ExportEmpty;
}
foreach ($this->invoices as $invoice) {
$lines = [];
foreach ($invoice->jobs() as $job) {
array_push($lines, ...($linesByJob[$job->jobId] ?? []));
}
$invoice->setLines($lines);
}
$this->status = ExportStatus::Created;
$this->finalizedBy = $finalizedBy;
$this->finalizedAt = $now;
}
/**
* @throws ExportNotDraft
*/
public function ensureDraft(): void
{
if ($this->status !== ExportStatus::Draft) {
throw new ExportNotDraft;
}
}
public function invoiceOf(int $jobId): ?BillingInvoice
{
foreach ($this->invoices as $invoice) {
if ($invoice->has($jobId)) {
return $invoice;
}
}
return null;
}
/**
* @return list<DraftJob>
*/
public function jobs(): array
{
return array_merge(...array_map(fn (BillingInvoice $invoice): array => $invoice->jobs(), $this->invoices));
}
/**
* @return list<int>
*/
public function jobIds(): array
{
return array_map(fn (DraftJob $job): int => $job->jobId, $this->jobs());
}
public function id(): ?int
{
return $this->id;
}
public function status(): ExportStatus
{
return $this->status;
}
public function isDraft(): bool
{
return $this->status === ExportStatus::Draft;
}
public function createdBy(): int
{
return $this->createdBy;
}
public function createdAt(): DateTimeImmutable
{
return $this->createdAt;
}
public function finalizedBy(): ?int
{
return $this->finalizedBy;
}
public function finalizedAt(): ?DateTimeImmutable
{
return $this->finalizedAt;
}
/**
* @return list<BillingInvoice>
*/
public function invoices(): array
{
return $this->invoices;
}
/**
* @throws JobNotInDraft
*/
private function requireInvoiceOf(int $jobId): BillingInvoice
{
return $this->invoiceOf($jobId) ?? throw new JobNotInDraft($jobId);
}
private function dropEmptyInvoices(): void
{
$this->invoices = array_values(array_filter($this->invoices, fn (BillingInvoice $invoice): bool => ! $invoice->isEmpty()));
}
}
@@ -0,0 +1,165 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Entities;
use App\Modules\Billing\Domain\Enums\MergeRefusal;
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
/**
* An invoice of a billing material: one or more jobs of the same customer
* and billing unit, with at most one customer reference among them (spec
* 12). Its lines are formed when the material is created.
*/
final class BillingInvoice
{
/**
* @param list<DraftJob> $jobs
* @param list<InvoiceLine> $lines
*/
private function __construct(
private array $jobs,
private array $lines = [],
) {}
public static function for(DraftJob $job): self
{
return new self([$job]);
}
/**
* @param list<DraftJob> $jobs
* @param list<InvoiceLine> $lines
*/
public static function reconstitute(array $jobs, array $lines = []): self
{
return new self($jobs, $lines);
}
/**
* Why the job may not join this invoice, or null when it may. The job
* itself is left out of the comparison.
*/
public function refusalFor(DraftJob $job): ?MergeRefusal
{
foreach ($this->jobs as $other) {
if ($other->jobId === $job->jobId) {
continue;
}
if ($other->customerId !== $job->customerId) {
return MergeRefusal::DifferentCustomer;
}
if ($other->billingUnitId !== $job->billingUnitId) {
return MergeRefusal::DifferentBillingUnit;
}
if ($other->reference !== null && $job->reference !== null && $other->reference !== $job->reference) {
return MergeRefusal::DifferentReference;
}
}
return null;
}
public function add(DraftJob $job): void
{
$this->jobs[] = $job;
}
public function remove(int $jobId): void
{
$this->jobs = array_values(array_filter($this->jobs, fn (DraftJob $job): bool => $job->jobId !== $jobId));
}
public function replace(DraftJob $job): void
{
$this->jobs = array_map(fn (DraftJob $current): DraftJob => $current->jobId === $job->jobId ? $job : $current, $this->jobs);
}
public function has(int $jobId): bool
{
return $this->job($jobId) !== null;
}
public function job(int $jobId): ?DraftJob
{
foreach ($this->jobs as $job) {
if ($job->jobId === $jobId) {
return $job;
}
}
return null;
}
public function isEmpty(): bool
{
return $this->jobs === [];
}
/**
* @param list<InvoiceLine> $lines
*/
public function setLines(array $lines): void
{
$this->lines = $lines;
}
/**
* @return list<DraftJob>
*/
public function jobs(): array
{
return $this->jobs;
}
/**
* @return list<InvoiceLine>
*/
public function lines(): array
{
return $this->lines;
}
/**
* The first job identifies the invoice on the page.
*/
public function key(): int
{
return $this->jobs[0]->jobId;
}
public function customerId(): int
{
return $this->jobs[0]->customerId;
}
public function billingUnitId(): ?int
{
return $this->jobs[0]->billingUnitId;
}
/**
* The one customer reference of its jobs, if any.
*/
public function reference(): ?string
{
foreach ($this->jobs as $job) {
if ($job->reference !== null) {
return $job->reference;
}
}
return null;
}
public function totals(): InvoiceTotals
{
return InvoiceTotals::of($this->lines);
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Enums;
/**
* How a job is billed: its hours per work type at the hourly rates, or its
* quoted fixed price as one line. Expenses are billed separately either way.
*/
enum BillingMode: string
{
case Hours = 'hours';
case FixedPrice = 'fixed_price';
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Enums;
/**
* A billing material is a draft until it is created, which locks it.
*/
enum ExportStatus: string
{
case Draft = 'draft';
case Created = 'created';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Enums;
/**
* What an invoice line bills.
*/
enum LineKind: string
{
case Hours = 'hours';
case FixedPrice = 'fixed_price';
case Expense = 'expense';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Enums;
/**
* Why two jobs cannot be on the same invoice (spec 12).
*/
enum MergeRefusal: string
{
case DifferentCustomer = 'different_customer';
case DifferentBillingUnit = 'different_billing_unit';
case DifferentReference = 'different_reference';
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Enums;
/**
* Why a job cannot go on a billing material (spec 12).
*/
enum NotBillableReason: string
{
/** The job is not done. */
case WrongStatus = 'wrong_status';
/** Not billable, billed monthly, or the internal customer. */
case NotBillableBasis = 'not_billable_basis';
/** A consumer customer without a personal identity code. */
case MissingIdentityCode = 'missing_identity_code';
/** A work type with approved hours has no hourly rate. */
case MissingHourlyRate = 'missing_hourly_rate';
/** A fixed price job without a quoted amount. */
case MissingQuotedAmount = 'missing_quoted_amount';
/** No approved hours, expenses or fixed price left to bill. */
case NothingToBill = 'nothing_to_bill';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class BillingExportNotFound extends DomainException
{
public function __construct(public readonly int $id)
{
parent::__construct("Billing material {$id} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class DraftAlreadyOpen extends DomainException
{
public function __construct()
{
parent::__construct('A billing material draft is already open.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ExportEmpty extends DomainException
{
public function __construct()
{
parent::__construct('The billing material has no jobs.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ExportNotDraft extends DomainException
{
public function __construct()
{
parent::__construct('The billing material is already created.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidBillableHours extends DomainException
{
public function __construct()
{
parent::__construct('The billable hours are invalid.');
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Billing\Domain\Enums\MergeRefusal;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvoicesCannotMerge extends DomainException
{
public function __construct(public readonly MergeRefusal $refusal)
{
parent::__construct("The jobs cannot be on the same invoice: {$refusal->value}.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class JobAlreadyInDraft extends DomainException
{
public function __construct(public readonly int $jobId)
{
parent::__construct("Job {$jobId} is already on the billing material.");
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Billing\Domain\Enums\NotBillableReason;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class JobNotBillable extends DomainException
{
public function __construct(public readonly int $jobId, public readonly NotBillableReason $reason)
{
parent::__construct("Job {$jobId} cannot be billed: {$reason->value}.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class JobNotInDraft extends DomainException
{
public function __construct(public readonly int $jobId)
{
parent::__construct("Job {$jobId} is not on the billing material.");
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\ValueObjects;
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
/**
* A job on a draft invoice: who it bills (customer, billing unit, the
* customer's reference) and management's billable hours per work type.
* A work type without its own billable hours bills its approved hours.
*/
final readonly class DraftJob
{
/** 9 999 hours. */
public const int MAX_QUARTERS = 39_996;
/**
* @param array<int, int> $billableQuarters Keyed by work type id.
*/
public function __construct(
public int $jobId,
public int $customerId,
public ?int $billingUnitId,
public ?string $reference,
public array $billableQuarters = [],
) {}
/**
* @throws InvalidBillableHours
*/
public function withBillableQuarters(int $workTypeId, ?int $quarters): self
{
$billable = $this->billableQuarters;
if ($quarters === null) {
unset($billable[$workTypeId]);
} elseif ($quarters < 0 || $quarters > self::MAX_QUARTERS) {
throw new InvalidBillableHours;
} else {
$billable[$workTypeId] = $quarters;
}
return new self($this->jobId, $this->customerId, $this->billingUnitId, $this->reference, $billable);
}
/**
* The billable quarters of a work type: management's own, or the approved ones.
*/
public function billableOf(int $workTypeId, int $approvedQuarters): int
{
return $this->billableQuarters[$workTypeId] ?? $approvedQuarters;
}
/**
* Parses billable hours such as "2,5", "2.5" or "2" to quarters of an
* hour; null for an empty value (back to the approved hours).
*
* @throws InvalidBillableHours
*/
public static function parseHours(string $value): ?int
{
$value = str_replace(',', '.', trim($value));
if ($value === '') {
return null;
}
if (preg_match('/^\d{1,4}(\.\d{1,2})?$/', $value) !== 1) {
throw new InvalidBillableHours;
}
$quarters = (float) $value * 4;
if (abs($quarters - round($quarters)) > 0.0001) {
throw new InvalidBillableHours;
}
return (int) round($quarters);
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\ValueObjects;
use App\Modules\Billing\Domain\Enums\LineKind;
/**
* A line of an invoice, without VAT: a work type's billable hours at its
* hourly rate, a job's fixed price, or an expense. Prices and descriptions
* are snapshots taken when the material is formed.
*/
final readonly class InvoiceLine
{
public function __construct(
public int $jobId,
public LineKind $kind,
public ?int $workTypeId,
public ?int $expenseId,
public string $description,
public ?int $recordedQuarters,
public ?int $quantityQuarters,
public int $unitPriceCents,
public int $vatBasisPoints,
public int $netCents,
) {}
/**
* Billable hours × the hourly rate, rounded half up to the cent. The
* approved (recorded) hours are kept beside them for reports.
*/
public static function hours(int $jobId, int $workTypeId, string $workTypeName, int $recordedQuarters, int $billableQuarters, int $hourlyRateCents, int $vatBasisPoints): self
{
return new self(
$jobId,
LineKind::Hours,
$workTypeId,
null,
$workTypeName,
$recordedQuarters,
$billableQuarters,
$hourlyRateCents,
$vatBasisPoints,
intdiv($billableQuarters * $hourlyRateCents * 2 + 4, 8),
);
}
public static function fixedPrice(int $jobId, string $description, int $amountCents, int $vatBasisPoints): self
{
return new self($jobId, LineKind::FixedPrice, null, null, $description, null, null, $amountCents, $vatBasisPoints, $amountCents);
}
public static function expense(int $jobId, int $expenseId, string $description, int $amountCents, int $vatBasisPoints): self
{
return new self($jobId, LineKind::Expense, null, $expenseId, $description, null, null, $amountCents, $vatBasisPoints, $amountCents);
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\ValueObjects;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
/**
* An invoice's sum without VAT, its VAT per rate (counted from the rate's
* total, rounded half up) and the sum with VAT.
*/
final readonly class InvoiceTotals
{
/**
* @param array<int, array{net: int, vat: int}> $byVatRate Keyed by VAT basis points, highest first.
*/
public function __construct(
public int $netCents,
public int $vatCents,
public array $byVatRate,
) {}
/**
* @param list<InvoiceLine> $lines
*/
public static function of(array $lines): self
{
$netByRate = [];
foreach ($lines as $line) {
$netByRate[$line->vatBasisPoints] = ($netByRate[$line->vatBasisPoints] ?? 0) + $line->netCents;
}
krsort($netByRate);
$byRate = [];
$net = 0;
$vat = 0;
foreach ($netByRate as $basisPoints => $rateNet) {
$rateVat = Money::fromCents($rateNet)->addVat(new VatPercentage($basisPoints))->cents - $rateNet;
$byRate[$basisPoints] = ['net' => $rateNet, 'vat' => $rateVat];
$net += $rateNet;
$vat += $rateVat;
}
return new self($net, $vat, $byRate);
}
/**
* @param list<self> $totals
*/
public static function sum(array $totals): self
{
$byRate = [];
foreach ($totals as $total) {
foreach ($total->byVatRate as $basisPoints => $amounts) {
$byRate[$basisPoints] = [
'net' => ($byRate[$basisPoints]['net'] ?? 0) + $amounts['net'],
'vat' => ($byRate[$basisPoints]['vat'] ?? 0) + $amounts['vat'],
];
}
}
krsort($byRate);
return new self(
array_sum(array_column($byRate, 'net')),
array_sum(array_column($byRate, 'vat')),
$byRate,
);
}
public function grossCents(): int
{
return $this->netCents + $this->vatCents;
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Modules\Billing\Infrastructure;
use App\Modules\Billing\Application\Contracts\BillingExpenses;
use App\Modules\Billing\Application\DTOs\BillableExpense;
use App\Modules\Expenses\Application\Contracts\ExpenseQueries;
use App\Modules\Expenses\Application\DTOs\ExpenseSummary;
use App\Modules\Expenses\Application\UseCases\MarkJobExpensesBilled;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\ValueObjects\Kilometers;
use Carbon\CarbonImmutable;
/**
* Billable expenses through the Expenses module. The line text is the
* category, the day and what was bought (or the trip).
*/
class ExpensesForBilling implements BillingExpenses
{
public function __construct(
private ExpenseQueries $expenses,
private MarkJobExpensesBilled $markBilled,
) {}
public function forJobs(array $jobIds): array
{
$result = array_fill_keys($jobIds, []);
foreach ($this->expenses->unbilledBillable($jobIds) as $expense) {
$result[$expense->job->id][] = new BillableExpense($expense->id, $expense->job->id, $this->description($expense), (int) $expense->billedAmountCents);
}
return $result;
}
public function markBilled(int $jobId, int $billingExportId): array
{
return $this->markBilled->execute($jobId, $billingExportId);
}
private function description(ExpenseSummary $expense): string
{
$what = $expense->category === ExpenseCategory::Mileage && $expense->kilometerTenths !== null
? __('expenses.mileage_summary', [
'km' => (new Kilometers($expense->kilometerTenths))->format(),
'destination' => $expense->destination,
'purpose' => $expense->purpose,
])
: (string) $expense->description;
return __('billing.expense_line', [
'category' => __('expenses.categories.'.$expense->category->value),
'day' => CarbonImmutable::parse($expense->spentOn)->format('j.n.Y'),
'what' => $what,
]);
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Modules\Billing\Infrastructure;
use App\Modules\Billing\Application\Contracts\BillingHours;
use App\Modules\Billing\Application\DTOs\JobHours;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\JobBillingHours;
use App\Modules\TimeTracking\Application\UseCases\MarkJobHoursBilled;
/**
* Hours for billing through the TimeTracking module.
*/
class HoursForBilling implements BillingHours
{
public function __construct(
private TimeEntryQueries $entries,
private MarkJobHoursBilled $markBilled,
) {}
public function forJobs(array $jobIds): array
{
return array_map(
fn (JobBillingHours $hours): JobHours => new JobHours($hours->jobId, $hours->approvedQuartersByWorkType, $hours->unapprovedQuarters),
$this->entries->billingHours($jobIds),
);
}
public function markBilled(int $jobId, int $billingExportId): array
{
return $this->markBilled->execute($jobId, $billingExportId);
}
}
@@ -0,0 +1,91 @@
<?php
namespace App\Modules\Billing\Infrastructure;
use App\Modules\Billing\Application\Contracts\BillingJobs;
use App\Modules\Billing\Application\DTOs\BillableJob;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\JobBillingInfo;
use App\Modules\Jobs\Application\UseCases\ChangeJobStatus;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\PaymentBasis;
/**
* Customer jobs for billing through the Jobs module's queries and status
* change, with the customer's type and identity code from Customers (only
* whether there is a code, never the code).
*/
class JobsForBilling implements BillingJobs
{
public function __construct(
private CustomerJobQueries $jobs,
private CustomerQueries $customers,
private ChangeJobStatus $changeStatus,
) {}
public function done(): array
{
return $this->toBillable($this->jobs->billingInfoWithStatus(JobStatus::Done));
}
public function find(array $jobIds): array
{
$result = [];
foreach ($this->toBillable(array_values($this->jobs->billingInfoOf($jobIds))) as $job) {
$result[$job->id] = $job;
}
return $result;
}
public function markInvoiced(int $jobId, int $actorUserId): void
{
$this->changeStatus->execute($jobId, JobStatus::Invoiced, $actorUserId);
}
/**
* @param list<JobBillingInfo> $jobs
* @return list<BillableJob>
*/
private function toBillable(array $jobs): array
{
/** @var array<int, CustomerSummary|null> $customers */
$customers = [];
foreach ($jobs as $job) {
if (! array_key_exists($job->customerId, $customers)) {
$customers[$job->customerId] = $this->customers->findSummary($job->customerId);
}
}
return array_map(function (JobBillingInfo $job) use ($customers): BillableJob {
$customer = $customers[$job->customerId] ?? null;
return new BillableJob(
$job->id,
$job->number,
$job->name,
$job->customerId,
$job->customerName,
$customer?->type === CustomerType::Consumer,
$customer->isInternal ?? false,
$customer?->hasPersonalIdentityCode() ?? false,
$job->billingUnitId,
$job->billingUnitName,
$job->customerReference,
match ($job->paymentBasis) {
PaymentBasis::FixedQuote => BillingMode::FixedPrice,
PaymentBasis::NotBillable, PaymentBasis::MonthlyFee => null,
default => BillingMode::Hours,
},
$job->quotedAmountCents,
$job->status === JobStatus::Done,
);
}, $jobs);
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Modules\Billing\Infrastructure\Persistence\Eloquent;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
/**
* Persistence model, used only inside the Billing Infrastructure layer.
*
* @property int $id
* @property ExportStatus $status
* @property int $created_by
* @property int|null $finalized_by
* @property Carbon|null $finalized_at
* @property Carbon $created_at
*/
#[Table('billing_exports')]
#[Fillable(['status', 'created_by', 'finalized_by', 'finalized_at'])]
class BillingExportModel extends Model
{
/**
* @return HasMany<BillingInvoiceModel, $this>
*/
public function invoices(): HasMany
{
return $this->hasMany(BillingInvoiceModel::class, 'billing_export_id')->orderBy('sort_order')->orderBy('id');
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'status' => ExportStatus::class,
'created_by' => 'integer',
'finalized_by' => 'integer',
'finalized_at' => 'datetime',
];
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Modules\Billing\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* A job on an invoice of a billing material, with its job's billing
* details as the draft knows them. Persistence model, used only inside the
* Billing Infrastructure layer.
*
* @property int $id
* @property int $billing_invoice_id
* @property int $customer_job_id
* @property int $customer_id
* @property int|null $billing_unit_id
* @property string|null $customer_reference
* @property int $sort_order
*/
#[Table('billing_invoice_jobs')]
#[Fillable(['billing_invoice_id', 'customer_job_id', 'customer_id', 'billing_unit_id', 'customer_reference', 'sort_order'])]
class BillingInvoiceJobModel extends Model
{
public $timestamps = false;
/**
* @return HasMany<BillingJobHoursModel, $this>
*/
public function hours(): HasMany
{
return $this->hasMany(BillingJobHoursModel::class, 'billing_invoice_job_id');
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'billing_invoice_id' => 'integer',
'customer_job_id' => 'integer',
'customer_id' => 'integer',
'billing_unit_id' => 'integer',
'sort_order' => 'integer',
];
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Modules\Billing\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Persistence model, used only inside the Billing Infrastructure layer.
*
* @property int $id
* @property int $billing_export_id
* @property int $customer_id
* @property int|null $billing_unit_id
* @property string|null $customer_reference
* @property int $sort_order
*/
#[Table('billing_invoices')]
#[Fillable(['billing_export_id', 'customer_id', 'billing_unit_id', 'customer_reference', 'sort_order'])]
class BillingInvoiceModel extends Model
{
/**
* @return HasMany<BillingInvoiceJobModel, $this>
*/
public function jobs(): HasMany
{
return $this->hasMany(BillingInvoiceJobModel::class, 'billing_invoice_id')->orderBy('sort_order')->orderBy('id');
}
/**
* @return HasMany<BillingLineModel, $this>
*/
public function lines(): HasMany
{
return $this->hasMany(BillingLineModel::class, 'billing_invoice_id')->orderBy('sort_order')->orderBy('id');
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'billing_export_id' => 'integer',
'customer_id' => 'integer',
'billing_unit_id' => 'integer',
'sort_order' => 'integer',
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Modules\Billing\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model, used only inside the Billing Infrastructure layer.
*
* @property int $id
* @property int $billing_invoice_job_id
* @property int $work_type_id
* @property int $billable_quarters
*/
#[Table('billing_job_hours')]
#[Fillable(['billing_invoice_job_id', 'work_type_id', 'billable_quarters'])]
class BillingJobHoursModel extends Model
{
public $timestamps = false;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'billing_invoice_job_id' => 'integer',
'work_type_id' => 'integer',
'billable_quarters' => 'integer',
];
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Modules\Billing\Infrastructure\Persistence\Eloquent;
use App\Modules\Billing\Domain\Enums\LineKind;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model, used only inside the Billing Infrastructure layer.
*
* @property int $id
* @property int $billing_invoice_id
* @property int $customer_job_id
* @property LineKind $kind
* @property int|null $work_type_id
* @property int|null $expense_id
* @property string $description
* @property int|null $recorded_quarters
* @property int|null $quantity_quarters
* @property int $unit_price_cents
* @property int $vat_basis_points
* @property int $net_cents
* @property int $sort_order
*/
#[Table('billing_lines')]
#[Fillable([
'billing_invoice_id', 'customer_job_id', 'kind', 'work_type_id', 'expense_id', 'description',
'recorded_quarters', 'quantity_quarters', 'unit_price_cents', 'vat_basis_points', 'net_cents', 'sort_order',
])]
class BillingLineModel extends Model
{
public $timestamps = false;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'billing_invoice_id' => 'integer',
'customer_job_id' => 'integer',
'kind' => LineKind::class,
'work_type_id' => 'integer',
'expense_id' => 'integer',
'recorded_quarters' => 'integer',
'quantity_quarters' => 'integer',
'unit_price_cents' => 'integer',
'vat_basis_points' => 'integer',
'net_cents' => 'integer',
'sort_order' => 'integer',
];
}
}
@@ -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();
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Modules\Billing\Infrastructure;
use App\Modules\Billing\Application\Contracts\BillingPrices;
use App\Modules\Billing\Application\DTOs\HourlyRate;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
/**
* Hourly rates and the default VAT rate from the Catalog module's price list.
*/
class PricesForBilling implements BillingPrices
{
public function __construct(private PriceListQueries $priceList) {}
public function hourlyRates(): array
{
$rates = [];
foreach ($this->priceList->hourlyRates() as $group) {
foreach ($group->rows as $row) {
$rates[$row->workTypeId] = new HourlyRate($row->workTypeId, $row->name, $row->hourlyRateCents);
}
}
return $rates;
}
public function defaultVatBasisPoints(): int
{
return $this->priceList->defaultVatRate()->basisPoints ?? 0;
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Modules\Billing\Infrastructure\Providers;
use App\Models\User;
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\Contracts\BillingQueries;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Infrastructure\ExpensesForBilling;
use App\Modules\Billing\Infrastructure\HoursForBilling;
use App\Modules\Billing\Infrastructure\JobsForBilling;
use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBillingExportRepository;
use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBillingQueries;
use App\Modules\Billing\Infrastructure\PricesForBilling;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Billing module (billing material for invoicing) into Laravel:
* bindings, routes, the `billing::` Livewire namespace and the
* `billing.manage` ability.
*/
class BillingServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
BillingExportRepository::class => EloquentBillingExportRepository::class,
BillingQueries::class => EloquentBillingQueries::class,
BillingJobs::class => JobsForBilling::class,
BillingHours::class => HoursForBilling::class,
BillingExpenses::class => ExpensesForBilling::class,
BillingPrices::class => PricesForBilling::class,
];
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('billing', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
// Management forms the billing material once a month (spec 12).
Gate::define('billing.manage', fn (User $user): bool => $user->role->seesAllMoney());
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Modules\Billing\Presentation\Livewire\Concerns;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Billing\Domain\Enums\NotBillableReason;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
use Carbon\CarbonImmutable;
use DateTimeInterface;
/**
* Formatting shared by the billing pages.
*/
trait FormatsBilling
{
public function money(int $cents): string
{
return ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format();
}
public function vatRate(int $basisPoints): string
{
return (new VatPercentage($basisPoints))->format();
}
public function hours(int $quarters): string
{
return rtrim(rtrim(number_format($quarters / 4, 2, ',', ''), '0'), ',');
}
/**
* E.g. "24.11.2026 klo 14.05" in the business time zone.
*/
public function timeLabel(DateTimeInterface $at): string
{
return CarbonImmutable::instance($at)->setTimezone((string) config('app.business_timezone'))->format('j.n.Y \k\l\o H.i');
}
public function modeLabel(?BillingMode $mode): string
{
return __('billing.modes.'.($mode->value ?? 'none'));
}
/**
* @param list<string> $missingRateNames
*/
public function reasonText(NotBillableReason $reason, array $missingRateNames = []): string
{
return __('billing.reasons.'.$reason->value, ['names' => implode(', ', $missingRateNames)]);
}
}
@@ -0,0 +1,605 @@
<?php
use App\Modules\Billing\Application\DTOs\ExportView;
use App\Modules\Billing\Application\DTOs\InvoiceJobView;
use App\Modules\Billing\Application\Services\ExportViews;
use App\Modules\Billing\Application\UseCases\AddJobToDraft;
use App\Modules\Billing\Application\UseCases\DiscardDraft;
use App\Modules\Billing\Application\UseCases\FinalizeBillingExport;
use App\Modules\Billing\Application\UseCases\MoveJobToInvoice;
use App\Modules\Billing\Application\UseCases\RemoveJobFromDraft;
use App\Modules\Billing\Application\UseCases\SeparateJob;
use App\Modules\Billing\Application\UseCases\SetBillableHours;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Billing\Domain\Enums\LineKind;
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\InvalidBillableHours;
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
use App\Modules\Billing\Domain\Exceptions\JobNotBillable;
use App\Modules\Billing\Domain\Exceptions\JobNotInDraft;
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
use App\Modules\Billing\Presentation\Livewire\Concerns\FormatsBilling;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* A billing material (laskuaineisto). As a draft: its invoices with the
* jobs' approved hours, management's billable hours and the expenses,
* the done jobs that may be added, combining jobs on invoices, and
* creating the material. Once created: its invoices and lines, read only.
*/
new class extends Component
{
use FormatsBilling;
#[Locked]
public int $exportId = 0;
#[Locked]
public string $statusMessage = '';
#[Locked]
public string $errorMessage = '';
/**
* The invoice chosen in each job's "move to invoice" select, keyed by job id.
*
* @var array<int|string, string>
*/
public array $moveTargets = [];
public function mount(int $export): void
{
$this->authorize('billing.manage');
$this->exportId = $export;
if (app(ExportViews::class)->of($export) === null) {
abort(404);
}
}
#[Computed]
public function export(): ExportView
{
return app(ExportViews::class)->of($this->exportId) ?? abort(404);
}
public function add(int $jobId, AddJobToDraft $addJobToDraft): void
{
$label = $this->availableLabel($jobId);
$this->attempt(fn () => $addJobToDraft->execute($this->exportId, $jobId), __('billing.available.added', ['job' => $label]), $label);
}
public function remove(int $jobId, RemoveJobFromDraft $removeJobFromDraft): void
{
$label = $this->jobLabel($jobId);
$this->attempt(fn () => $removeJobFromDraft->execute($this->exportId, $jobId), __('billing.jobs.removed', ['job' => $label]), $label);
}
public function move(int $jobId, MoveJobToInvoice $moveJobToInvoice): void
{
$label = $this->jobLabel($jobId);
$target = (int) ($this->moveTargets[$jobId] ?? 0);
if ($target === 0) {
return;
}
$this->attempt(fn () => $moveJobToInvoice->execute($this->exportId, $jobId, $target), __('billing.jobs.moved', ['job' => $label]), $label);
unset($this->moveTargets[$jobId]);
}
public function separate(int $jobId, SeparateJob $separateJob): void
{
$label = $this->jobLabel($jobId);
$this->attempt(fn () => $separateJob->execute($this->exportId, $jobId), __('billing.jobs.separated', ['job' => $label]), $label);
}
public function saveHours(int $jobId, int $workTypeId, string $value, SetBillableHours $setBillableHours): void
{
$this->authorize('billing.manage');
$field = 'hours.'.$jobId.'.'.$workTypeId;
$this->resetErrorBag($field);
$label = $this->jobLabel($jobId);
$workType = $this->workTypeName($jobId, $workTypeId);
try {
$setBillableHours->execute($this->exportId, $jobId, $workTypeId, mb_substr($value, 0, 20));
$this->statusMessage = __('billing.jobs.hours_saved', ['job' => $label, 'work_type' => $workType]);
$this->errorMessage = '';
} catch (InvalidBillableHours) {
$this->addError($field, __('billing.errors.hours'));
} catch (ExportNotDraft|BillingExportNotFound|JobNotInDraft $exception) {
$this->errorMessage = $this->errorText($exception, $label);
}
unset($this->export);
}
public function confirmFinalize(): void
{
$this->authorize('billing.manage');
$this->js("document.getElementById('finalize-dialog').showModal()");
}
public function finalize(FinalizeBillingExport $finalizeBillingExport): void
{
$this->authorize('billing.manage');
$this->statusMessage = '';
$this->errorMessage = '';
try {
$invoices = $finalizeBillingExport->execute($this->exportId, (int) auth()->id());
$this->statusMessage = __('billing.export.finalized', ['invoices' => $invoices]);
} catch (ExportNotDraft|BillingExportNotFound|ExportEmpty|JobNotBillable $exception) {
$this->errorMessage = $this->errorText($exception, $exception instanceof JobNotBillable ? $this->jobLabel($exception->jobId) : '');
}
unset($this->export);
$this->js("document.getElementById('finalize-dialog').close(); document.getElementById('billing-status').focus()");
}
public function confirmDiscard(): void
{
$this->authorize('billing.manage');
$this->js("document.getElementById('discard-dialog').showModal()");
}
public function discard(DiscardDraft $discardDraft): void
{
$this->authorize('billing.manage');
try {
$discardDraft->execute($this->exportId);
session()->flash('billing-status', __('billing.export.discarded'));
$this->redirectRoute('billing.index', navigate: true);
} catch (ExportNotDraft|BillingExportNotFound $exception) {
$this->errorMessage = $this->errorText($exception, '');
unset($this->export);
$this->js("document.getElementById('discard-dialog').close(); document.getElementById('billing-error').focus()");
}
}
/**
* @return list<InvoiceLine>
*/
public function linesOfKind(InvoiceJobView $job, LineKind $kind): array
{
return array_values(array_filter($job->lines, fn (InvoiceLine $line): bool => $line->kind === $kind));
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function availableHeaders(): array
{
return [
['index' => 'job', 'label' => __('billing.available.columns.job'), 'sortable' => false],
['index' => 'customer', 'label' => __('billing.available.columns.customer'), 'sortable' => false],
['index' => 'mode', 'label' => __('billing.available.columns.mode'), 'sortable' => false],
['index' => 'hours', 'label' => __('billing.available.columns.hours'), 'sortable' => false, 'align' => 'right'],
['index' => 'expenses', 'label' => __('billing.available.columns.expenses'), 'sortable' => false, 'align' => 'right'],
['index' => 'actions', 'label' => __('billing.available.columns.actions'), 'sortable' => false],
];
}
public function render(): mixed
{
return $this->view()->title(__('billing.export.title', ['number' => $this->exportId]));
}
/**
* Runs a change of the draft and reports it in the status or error area.
*/
private function attempt(callable $change, string $success, string $jobLabel): void
{
$this->authorize('billing.manage');
$this->statusMessage = '';
$this->errorMessage = '';
try {
$change();
$this->statusMessage = $success;
} catch (BillingExportNotFound|ExportNotDraft|JobAlreadyInDraft|JobNotInDraft|JobNotBillable|InvoicesCannotMerge $exception) {
$this->errorMessage = $this->errorText($exception, $jobLabel);
}
unset($this->export);
}
private function errorText(\Throwable $exception, string $jobLabel): string
{
return match (true) {
$exception instanceof JobNotBillable => __('billing.errors.not_billable', ['job' => $jobLabel, 'reason' => $this->reasonText($exception->reason, $this->missingRates($exception->jobId))]),
$exception instanceof InvoicesCannotMerge => __('billing.merge_refusals.'.$exception->refusal->value),
$exception instanceof ExportNotDraft => __('billing.errors.not_draft'),
$exception instanceof ExportEmpty => __('billing.errors.empty'),
$exception instanceof JobAlreadyInDraft => __('billing.errors.already_in_draft'),
$exception instanceof JobNotInDraft => __('billing.errors.not_in_draft'),
default => __('billing.errors.not_found'),
};
}
/**
* @return list<string>
*/
private function missingRates(int $jobId): array
{
foreach ($this->export->availableJobs as $available) {
if ($available->job->id === $jobId) {
return $available->missingRateNames;
}
}
return $this->findJob($jobId)->missingRateNames ?? [];
}
private function availableLabel(int $jobId): string
{
foreach ($this->export->availableJobs as $available) {
if ($available->job->id === $jobId) {
return $available->job->label();
}
}
return (string) $jobId;
}
private function jobLabel(int $jobId): string
{
return $this->findJob($jobId)?->label() ?? $this->availableLabel($jobId);
}
private function workTypeName(int $jobId, int $workTypeId): string
{
foreach ($this->findJob($jobId)->hours ?? [] as $row) {
if ($row->workTypeId === $workTypeId) {
return $row->name;
}
}
return '';
}
private function findJob(int $jobId): ?InvoiceJobView
{
foreach ($this->export->invoices as $invoice) {
foreach ($invoice->jobs as $job) {
if ($job->jobId === $jobId) {
return $job;
}
}
}
return null;
}
};
?>
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
@php($export = $this->export)
<div class="space-y-2">
<p><x-link :href="route('billing.index')" navigate>{{ __('billing.export.back') }}</x-link></p>
<h1 class="text-2xl font-semibold">{{ __('billing.export.title', ['number' => $export->id]) }}</h1>
<p class="flex items-center gap-2 text-sm">
@if ($export->isDraft())
<x-icon name="pencil-square" class="size-5 shrink-0" aria-hidden="true" />
{{ __('billing.export.draft_info', ['name' => $export->createdByName, 'at' => $this->timeLabel($export->createdAt)]) }}
@else
<x-icon name="lock-closed" class="size-5 shrink-0" aria-hidden="true" />
{{ __('billing.export.created_info', ['name' => (string) $export->finalizedByName, 'at' => $this->timeLabel($export->finalizedAt ?? $export->createdAt)]) }}
@endif
</p>
<p class="text-sm font-medium">
{{ __('billing.export.summary', ['invoices' => count($export->invoices), 'jobs' => $export->jobCount(), 'net' => $this->money($export->totals->netCents)]) }}
</p>
</div>
<p id="billing-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $statusMessage }}</p>
<p id="billing-error" tabindex="-1" role="alert" class="text-sm font-medium text-red-700 focus:outline-none dark:text-red-400">{{ $errorMessage }}</p>
@if ($export->isDraft())
@if ($export->hasProblems())
<p class="flex items-start gap-2 rounded-lg border border-amber-700 p-4 text-sm dark:border-amber-400">
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
{{ __('billing.export.problems') }}
</p>
@endif
<div class="flex flex-wrap gap-3">
@if ($export->invoices !== [])
<x-button wire:click="confirmFinalize" icon="lock-closed" :text="__('billing.export.finalize')" />
@endif
<x-button wire:click="confirmDiscard" subtle color="black" icon="trash" :text="__('billing.export.discard')" />
</div>
@endif
<section aria-labelledby="invoices-heading" class="space-y-6">
<h2 id="invoices-heading" class="text-xl font-semibold">{{ __('billing.invoices.title') }}</h2>
@if ($export->invoices === [])
<p class="text-sm">{{ __('billing.invoices.none') }}</p>
@endif
@foreach ($export->invoices as $invoiceNumber => $invoice)
<section wire:key="invoice-{{ $invoice->key }}" aria-labelledby="invoice-{{ $invoice->key }}-heading" class="space-y-4 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<div class="space-y-1">
<h3 id="invoice-{{ $invoice->key }}-heading" class="text-lg font-semibold">{{ __('billing.invoices.heading', ['number' => $invoiceNumber + 1, 'customer' => $invoice->customerName]) }}</h3>
<dl class="grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[auto_1fr]">
<dt class="font-medium">{{ __('billing.invoices.billing_unit') }}</dt>
<dd>{{ $invoice->billingUnitName ?? __('billing.invoices.no_billing_unit') }}</dd>
<dt class="font-medium">{{ __('billing.invoices.reference') }}</dt>
<dd>{{ $invoice->reference ?? __('billing.invoices.no_reference') }}</dd>
</dl>
</div>
@foreach ($invoice->jobs as $job)
<article wire:key="job-{{ $job->jobId }}" aria-labelledby="job-{{ $job->jobId }}-heading" class="space-y-3 border-t border-zinc-200 pt-3 dark:border-zinc-700">
<h4 id="job-{{ $job->jobId }}-heading" class="font-semibold">
<x-link :href="route('jobs.show', $job->jobId)" navigate>{{ $job->label() }}</x-link>
</h4>
<p class="text-sm">{{ __('billing.jobs.mode', ['mode' => $this->modeLabel($job->mode)]) }}</p>
@if ($job->problem !== null)
<p class="flex items-start gap-2 text-sm font-medium text-red-700 dark:text-red-400">
<x-icon name="x-circle" class="size-5 shrink-0" aria-hidden="true" />
{{ $this->reasonText($job->problem, $job->missingRateNames) }}
</p>
@endif
@if ($export->isDraft() && $job->unapprovedQuarters > 0)
<p class="flex items-start gap-2 text-sm">
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
<span>
{{ __('billing.jobs.unapproved', ['hours' => $this->hours($job->unapprovedQuarters)]) }}
<x-link :href="route('time.approvals')" navigate underline>{{ __('billing.jobs.approvals_link') }}</x-link>
</span>
</p>
@endif
@if ($export->isDraft())
@if ($job->mode === BillingMode::FixedPrice)
@php($fixed = $this->linesOfKind($job, LineKind::FixedPrice))
<p class="text-sm">
{{ $fixed === [] ? __('billing.jobs.fixed_price_billed') : __('billing.jobs.fixed_price', ['amount' => $this->money($fixed[0]->netCents)]) }}
</p>
@php($approved = array_sum(array_map(fn ($row) => $row->approvedQuarters, $job->hours)))
@if ($approved > 0)
<p class="text-sm">{{ __('billing.jobs.fixed_hours', ['hours' => $this->hours($approved)]) }}</p>
@endif
@elseif ($job->hours === [])
<p class="text-sm">{{ __('billing.jobs.no_hours') }}</p>
@else
<div class="overflow-x-auto">
<table class="w-full text-sm">
<caption class="sr-only">{{ __('billing.jobs.hours_caption', ['job' => $job->label()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.work_type') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.jobs.approved_hours') }}</th>
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.billable_hours') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.jobs.rate') }}</th>
<th scope="col" class="py-2 text-right">{{ __('billing.jobs.net') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($job->hours as $row)
@php($fieldId = 'hours-'.$job->jobId.'-'.$row->workTypeId)
<tr wire:key="{{ $fieldId }}">
<th scope="row" class="py-2 pr-3 text-left font-normal">{{ $row->name }}</th>
<td class="py-2 pr-3 text-right">{{ $this->hours($row->approvedQuarters) }}</td>
<td class="py-2 pr-3">
<input
id="{{ $fieldId }}"
type="text"
inputmode="decimal"
autocomplete="off"
value="{{ $this->hours($row->billableQuarters) }}"
wire:change="saveHours({{ $job->jobId }}, {{ $row->workTypeId }}, $event.target.value)"
aria-label="{{ __('billing.jobs.billable_label', ['work_type' => $row->name]) }}"
aria-describedby="hours-help-{{ $job->jobId }}"
@error('hours.'.$job->jobId.'.'.$row->workTypeId) aria-invalid="true" aria-errormessage="{{ $fieldId }}-error" @enderror
class="w-20 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
/>
@if ($row->isAdjusted)
<span class="ml-1 text-xs">({{ __('billing.jobs.adjusted') }})</span>
@endif
@error('hours.'.$job->jobId.'.'.$row->workTypeId)
<span id="{{ $fieldId }}-error" class="mt-1 block text-xs text-red-700 dark:text-red-400">{{ $message }}</span>
@enderror
</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $row->rateCents === null ? __('billing.jobs.no_rate') : $this->money($row->rateCents) }}</td>
<td class="py-2 text-right whitespace-nowrap">{{ $this->money($row->netCents) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<p id="hours-help-{{ $job->jobId }}" class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('billing.jobs.billable_help') }}</p>
@endif
@php($expenseLines = $this->linesOfKind($job, LineKind::Expense))
@if ($expenseLines !== [])
<table class="w-full text-sm">
<caption class="mb-1 text-left font-medium">{{ __('billing.jobs.expenses_caption', ['job' => $job->label()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.expense') }}</th>
<th scope="col" class="py-2 text-right">{{ __('billing.jobs.amount') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($expenseLines as $line)
<tr wire:key="expense-{{ $line->expenseId }}">
<td class="py-2 pr-3">{{ $line->description }}</td>
<td class="py-2 text-right whitespace-nowrap">{{ $this->money($line->netCents) }}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
<div class="flex flex-wrap items-end gap-3">
@if (($invoice->mergeTargets[$job->jobId] ?? []) !== [])
<div class="w-full max-w-xs">
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native
wire:model="moveTargets.{{ $job->jobId }}"
:label="__('billing.jobs.move_label', ['job' => $job->number])"
:aria-label="__('billing.jobs.move_label', ['job' => $job->number])"
>
<option value="">{{ __('billing.jobs.move_placeholder') }}</option>
@foreach ($invoice->mergeTargets[$job->jobId] as $target)
<option value="{{ $target->invoiceKey }}">{{ $target->label }}</option>
@endforeach
</x-select.native>
</div>
<x-button wire:click="move({{ $job->jobId }})" subtle color="black" sm icon="arrows-right-left" :text="__('billing.jobs.move')" :aria-label="__('billing.jobs.move_named', ['job' => $job->label()])" />
@endif
@if (count($invoice->jobs) > 1)
<x-button wire:click="separate({{ $job->jobId }})" subtle color="black" sm icon="document-duplicate" :text="__('billing.jobs.separate')" :aria-label="__('billing.jobs.separate_named', ['job' => $job->label()])" />
@endif
<x-button wire:click="remove({{ $job->jobId }})" subtle color="black" sm icon="minus-circle" :text="__('billing.jobs.remove')" :aria-label="__('billing.jobs.remove_named', ['job' => $job->label()])" />
</div>
@else
<div class="overflow-x-auto">
<table class="w-full text-sm">
<caption class="sr-only">{{ __('billing.lines.caption', ['job' => $job->label()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<th scope="col" class="py-2 pr-3">{{ __('billing.lines.description') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.recorded') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.quantity') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.unit_price') }}</th>
<th scope="col" class="py-2 text-right">{{ __('billing.lines.net') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($job->lines as $index => $line)
<tr wire:key="line-{{ $job->jobId }}-{{ $index }}">
<td class="py-2 pr-3">
<span class="block text-xs">{{ __('billing.kinds.'.$line->kind->value) }}</span>
{{ $line->description }}
</td>
<td class="py-2 pr-3 text-right">{{ $line->recordedQuarters === null ? '' : $this->hours($line->recordedQuarters) }}</td>
<td class="py-2 pr-3 text-right">{{ $line->quantityQuarters === null ? '' : $this->hours($line->quantityQuarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($line->unitPriceCents) }}</td>
<td class="py-2 text-right whitespace-nowrap">{{ $this->money($line->netCents) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
</article>
@endforeach
<table class="ml-auto w-full max-w-sm text-sm">
<caption class="mb-1 text-left font-semibold">{{ __('billing.invoices.totals') }}</caption>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
<tr>
<th scope="row" class="py-1 text-left font-normal">{{ __('billing.invoices.net') }}</th>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($invoice->totals->netCents) }}</td>
</tr>
@foreach ($invoice->totals->byVatRate as $basisPoints => $amounts)
<tr wire:key="invoice-{{ $invoice->key }}-vat-{{ $basisPoints }}">
<th scope="row" class="py-1 text-left font-normal">{{ __('billing.invoices.vat', ['rate' => $this->vatRate($basisPoints)]) }}</th>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($amounts['vat']) }}</td>
</tr>
@endforeach
<tr>
<th scope="row" class="py-1 text-left font-semibold">{{ __('billing.invoices.gross') }}</th>
<td class="py-1 text-right font-semibold whitespace-nowrap">{{ $this->money($invoice->totals->grossCents()) }}</td>
</tr>
</tbody>
</table>
</section>
@endforeach
@if (count($export->invoices) > 1)
<table class="ml-auto w-full max-w-sm text-sm">
<caption class="mb-1 text-left font-semibold">{{ __('billing.invoices.export_totals') }}</caption>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
<tr>
<th scope="row" class="py-1 text-left font-normal">{{ __('billing.invoices.net') }}</th>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($export->totals->netCents) }}</td>
</tr>
<tr>
<th scope="row" class="py-1 text-left font-semibold">{{ __('billing.invoices.gross') }}</th>
<td class="py-1 text-right font-semibold whitespace-nowrap">{{ $this->money($export->totals->grossCents()) }}</td>
</tr>
</tbody>
</table>
@endif
</section>
@if ($export->isDraft())
<section aria-labelledby="available-heading" class="space-y-3">
<h2 id="available-heading" class="text-xl font-semibold">{{ __('billing.available.title') }}</h2>
<p class="text-sm">{{ __('billing.available.intro') }}</p>
@if ($export->availableJobs === [])
<p class="text-sm">{{ __('billing.available.none') }}</p>
@else
<x-table :headers="$this->availableHeaders()" :rows="$export->availableJobs">
@interact('column_job', $available)
<x-link :href="route('jobs.show', $available->job->id)" navigate>{{ $available->job->label() }}</x-link>
@endinteract
@interact('column_customer', $available)
<span class="whitespace-normal">{{ $available->job->customerName }}</span>
@endinteract
@interact('column_mode', $available)
{{ $this->modeLabel($available->job->mode) }}
@endinteract
@interact('column_hours', $available)
{{ $this->hours($available->approvedQuarters) }}
@if ($available->unapprovedQuarters > 0)
<span class="block text-xs">{{ __('billing.available.unapproved', ['hours' => $this->hours($available->unapprovedQuarters)]) }}</span>
@endif
@endinteract
@interact('column_expenses', $available)
{{ $available->expenseCount }}
@endinteract
@interact('column_actions', $available)
@if ($available->reason === null)
<x-button wire:click="add({{ $available->job->id }})" sm icon="plus" :text="__('billing.available.add')" :aria-label="__('billing.available.add_named', ['job' => $available->job->label()])" />
@else
<span class="flex items-start gap-1 whitespace-normal text-sm">
<x-icon name="x-circle" class="size-4 shrink-0" aria-hidden="true" />
{{ $this->reasonText($available->reason, $available->missingRateNames) }}
</span>
@endif
@endinteract
</x-table>
@endif
</section>
<x-confirm-dialog id="finalize-dialog" :title="__('billing.export.finalize_title')">
<p>{{ __('billing.export.finalize_text', ['invoices' => count($export->invoices), 'net' => $this->money($export->totals->netCents)]) }}</p>
<x-slot:actions>
<x-button wire:click="finalize" :text="__('billing.export.finalize')" />
</x-slot:actions>
</x-confirm-dialog>
<x-confirm-dialog id="discard-dialog" :title="__('billing.export.discard_title')">
<p>{{ __('billing.export.discard_text') }}</p>
<x-slot:actions>
<x-button wire:click="discard" color="red" :text="__('billing.export.discard')" />
</x-slot:actions>
</x-confirm-dialog>
@endif
</div>
@@ -0,0 +1,143 @@
<?php
use App\Modules\Billing\Application\Contracts\BillingQueries;
use App\Modules\Billing\Application\DTOs\ExportSummary;
use App\Modules\Billing\Application\UseCases\OpenBillingDraft;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Domain\Exceptions\DraftAlreadyOpen;
use App\Modules\Billing\Presentation\Livewire\Concerns\FormatsBilling;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Billing materials (laskuaineistot), newest first, and the way to start
* a new draft or continue the open one. Management only.
*/
new class extends Component
{
use FormatsBilling;
#[Locked]
public string $statusMessage = '';
public function mount(): void
{
$this->authorize('billing.manage');
$this->statusMessage = (string) session('billing-status', '');
}
/**
* @return list<ExportSummary>
*/
#[Computed]
public function exports(): array
{
return app(BillingQueries::class)->exports();
}
#[Computed]
public function openDraft(): ?ExportSummary
{
foreach ($this->exports as $export) {
if ($export->status === ExportStatus::Draft) {
return $export;
}
}
return null;
}
public function openDraftNow(OpenBillingDraft $openBillingDraft): void
{
$this->authorize('billing.manage');
try {
$id = $openBillingDraft->execute((int) auth()->id());
$this->redirectRoute('billing.export', ['export' => $id], navigate: true);
} catch (DraftAlreadyOpen) {
$this->statusMessage = __('billing.errors.draft_open');
unset($this->exports, $this->openDraft);
}
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function headers(): array
{
return [
['index' => 'number', 'label' => __('billing.index.columns.number'), 'sortable' => false],
['index' => 'status', 'label' => __('billing.index.columns.status'), 'sortable' => false],
['index' => 'created', 'label' => __('billing.index.columns.created'), 'sortable' => false],
['index' => 'finalized', 'label' => __('billing.index.columns.finalized'), 'sortable' => false],
['index' => 'invoices', 'label' => __('billing.index.columns.invoices'), 'sortable' => false, 'align' => 'right'],
['index' => 'jobs', 'label' => __('billing.index.columns.jobs'), 'sortable' => false, 'align' => 'right'],
['index' => 'net', 'label' => __('billing.index.columns.net'), 'sortable' => false, 'align' => 'right'],
];
}
public function render(): mixed
{
return $this->view()->title(__('billing.index.title'));
}
};
?>
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('billing.index.title') }}</h1>
<p class="max-w-3xl text-sm">{{ __('billing.index.intro') }}</p>
</div>
<p>
@if ($this->openDraft !== null)
<x-button :href="route('billing.export', $this->openDraft->id)" wire:navigate icon="pencil-square" :text="__('billing.index.continue')" />
@else
<x-button wire:click="openDraftNow" icon="plus" :text="__('billing.index.new')" />
@endif
</p>
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $statusMessage }}</p>
@if ($this->exports === [])
<p class="text-sm">{{ __('billing.index.none') }}</p>
@else
<x-table :headers="$this->headers()" :rows="$this->exports">
@interact('column_number', $export)
<x-link :href="route('billing.export', $export->id)" navigate>{{ __('billing.index.export_label', ['number' => $export->id]) }}</x-link>
@endinteract
@interact('column_status', $export)
<span class="inline-flex items-center gap-1">
<x-icon :name="$export->status->value === 'draft' ? 'pencil-square' : 'lock-closed'" class="size-4" aria-hidden="true" />
{{ __('billing.statuses.'.$export->status->value) }}
</span>
@endinteract
@interact('column_created', $export)
<span class="whitespace-nowrap">{{ $this->timeLabel($export->createdAt) }}</span>
<span class="block text-xs">{{ $export->createdByName }}</span>
@endinteract
@interact('column_finalized', $export)
@if ($export->finalizedAt !== null)
<span class="whitespace-nowrap">{{ $this->timeLabel($export->finalizedAt) }}</span>
<span class="block text-xs">{{ $export->finalizedByName }}</span>
@endif
@endinteract
@interact('column_invoices', $export)
{{ $export->invoiceCount }}
@endinteract
@interact('column_jobs', $export)
{{ $export->jobCount }}
@endinteract
@interact('column_net', $export)
<span class="whitespace-nowrap">{{ $export->netCents === null ? '' : $this->money($export->netCents) }}</span>
@endinteract
</x-table>
@endif
</div>
@@ -0,0 +1,11 @@
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:billing.manage'])
->prefix('billing')
->name('billing.')
->group(function () {
Route::livewire('/', 'billing::index')->name('index');
Route::livewire('/{export}', 'billing::export')->whereNumber('export')->name('export');
});
@@ -25,4 +25,12 @@ interface ExpenseQueries
public function forUserInMonth(int $userId, string $month): array;
public function find(int $id): ?ExpenseSummary;
/**
* The jobs' billable expenses that are not billed yet, oldest first.
*
* @param list<int> $jobIds
* @return list<ExpenseSummary>
*/
public function unbilledBillable(array $jobIds): array;
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\UseCases;
use App\Modules\Expenses\Domain\Contracts\ExpenseRepository;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Marks a job's billable, unbilled expenses billed on a billing material,
* so they are never billed twice and can no longer be changed. The caller
* (billing) checks who may do this.
*/
final class MarkJobExpensesBilled
{
public function __construct(
private ExpenseRepository $expenses,
private TransactionManager $transactions,
) {}
/**
* @return list<int> Ids of the expenses marked billed.
*/
public function execute(int $jobId, int $billingExportId): array
{
return $this->transactions->run(fn (): array => $this->expenses->markBillableAsBilled($jobId, $billingExportId));
}
}
@@ -30,7 +30,7 @@ final class RemoveExpense
$this->transactions->run(function () use ($expenseId): void {
$expense = $this->expenses->findById($expenseId) ?? throw new ExpenseNotFound($expenseId);
if ($this->jobs->find($expense->jobId())->isLocked ?? true) {
if ($expense->isBilled() || ($this->jobs->find($expense->jobId())->isLocked ?? true)) {
throw new ExpenseLocked;
}
@@ -36,7 +36,7 @@ final class UpdateExpense
$this->transactions->run(function () use ($expenseId, $data, $details): void {
$expense = $this->expenses->findById($expenseId) ?? throw new ExpenseNotFound($expenseId);
if ($this->jobs->find($expense->jobId())->isLocked ?? true) {
if ($expense->isBilled() || ($this->jobs->find($expense->jobId())->isLocked ?? true)) {
throw new ExpenseLocked;
}
@@ -16,4 +16,11 @@ interface ExpenseRepository
public function save(Expense $expense): Expense;
public function delete(Expense $expense): void;
/**
* Marks the job's billable, unbilled expenses billed on a billing material.
*
* @return list<int> Ids of the expenses marked.
*/
public function markBillableAsBilled(int $jobId, int $billingExportId): array;
}
@@ -8,7 +8,8 @@ use App\Modules\Expenses\Domain\ValueObjects\ExpenseDetails;
/**
* An expense on a customer job: whose it is, who recorded it (management
* records subcontractors' expenses) and what it is.
* records subcontractors' expenses) and what it is. A billed expense (on a
* billing material) can no longer be changed or removed.
*/
final class Expense
{
@@ -18,6 +19,7 @@ final class Expense
private int $userId,
private int $recordedBy,
private ExpenseDetails $details,
private ?int $billingExportId = null,
) {}
public static function record(int $jobId, int $userId, int $recordedBy, ExpenseDetails $details): self
@@ -25,9 +27,19 @@ final class Expense
return new self(null, $jobId, $userId, $recordedBy, $details);
}
public static function reconstitute(int $id, int $jobId, int $userId, int $recordedBy, ExpenseDetails $details): self
public static function reconstitute(int $id, int $jobId, int $userId, int $recordedBy, ExpenseDetails $details, ?int $billingExportId = null): self
{
return new self($id, $jobId, $userId, $recordedBy, $details);
return new self($id, $jobId, $userId, $recordedBy, $details, $billingExportId);
}
public function isBilled(): bool
{
return $this->billingExportId !== null;
}
public function billingExportId(): ?int
{
return $this->billingExportId;
}
public function change(int $userId, ExpenseDetails $details): void
@@ -30,6 +30,7 @@ use Illuminate\Support\Carbon;
* @property bool $is_billable
* @property int|null $markup_basis_points
* @property int|null $billed_amount_cents
* @property int|null $billing_export_id
*/
#[Table('expenses')]
#[Fillable([
@@ -42,6 +42,19 @@ class EloquentExpenseQueries implements ExpenseQueries
return $this->summaries(ExpenseModel::query()->whereKey($id))[0] ?? null;
}
public function unbilledBillable(array $jobIds): array
{
if ($jobIds === []) {
return [];
}
return array_reverse($this->summaries(ExpenseModel::query()
->whereIn('customer_job_id', $jobIds)
->where('is_billable', true)
->whereNotNull('billed_amount_cents')
->whereNull('billing_export_id')));
}
/**
* @param Builder<ExpenseModel> $query
* @return list<ExpenseSummary>
@@ -51,6 +51,24 @@ class EloquentExpenseRepository implements ExpenseRepository
ExpenseModel::query()->whereKey($expense->id())->delete();
}
public function markBillableAsBilled(int $jobId, int $billingExportId): array
{
$ids = ExpenseModel::query()
->where('customer_job_id', $jobId)
->where('is_billable', true)
->whereNotNull('billed_amount_cents')
->whereNull('billing_export_id')
->orderBy('spent_on')
->orderBy('id')
->pluck('id')
->map(fn ($id): int => (int) $id)
->all();
ExpenseModel::query()->whereKey($ids)->update(['billing_export_id' => $billingExportId]);
return $ids;
}
private function toEntity(ExpenseModel $model): Expense
{
$billing = $model->is_billable && $model->billed_amount_cents !== null
@@ -77,6 +95,7 @@ class EloquentExpenseRepository implements ExpenseRepository
$model->purpose,
$billing,
),
$model->billing_export_id,
);
}
}
@@ -6,8 +6,10 @@ namespace App\Modules\Jobs\Application\Contracts;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\JobBillingInfo;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
/**
@@ -41,6 +43,21 @@ interface CustomerJobQueries
*/
public function summariesByIds(array $ids): array;
/**
* Billing details of the jobs in a status, by job number.
*
* @return list<JobBillingInfo>
*/
public function billingInfoWithStatus(JobStatus $status): array;
/**
* Billing details of the given jobs, keyed by id; unknown ids are left out.
*
* @param list<int> $ids
* @return array<int, JobBillingInfo>
*/
public function billingInfoOf(array $ids): array;
/**
* The job's history, newest first.
*
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\PaymentBasis;
/**
* A customer job as billing sees it: who is billed, under which billing
* unit and reference, and how (payment basis, quoted amount without VAT).
*/
final readonly class JobBillingInfo
{
public function __construct(
public int $id,
public string $number,
public string $name,
public int $customerId,
public string $customerName,
public JobStatus $status,
public ?PaymentBasis $paymentBasis,
public ?int $quotedAmountCents,
public ?string $customerReference,
public ?int $billingUnitId,
public ?string $billingUnitName,
) {}
}
@@ -7,6 +7,7 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\JobBillingInfo;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Application\DTOs\NamedId;
@@ -184,6 +185,52 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
);
}
public function billingInfoWithStatus(JobStatus $status): array
{
return array_values($this->billingInfo(CustomerJobModel::query()->where('status', $status)->orderBy('number')->get()));
}
public function billingInfoOf(array $ids): array
{
return $ids === [] ? [] : $this->billingInfo(CustomerJobModel::query()->whereIn('id', $ids)->orderBy('number')->get());
}
/**
* @param Collection<int, CustomerJobModel> $models
* @return array<int, JobBillingInfo>
*/
private function billingInfo(Collection $models): array
{
$customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all());
$billingUnitNames = [];
$result = [];
foreach ($models as $model) {
if ($model->billing_unit_id !== null && ! isset($billingUnitNames[$model->customer_id])) {
$billingUnitNames[$model->customer_id] = [];
foreach ($this->customers->billingUnitsOf($model->customer_id) as $unit) {
$billingUnitNames[$model->customer_id][$unit->id] = $unit->name;
}
}
$result[$model->id] = new JobBillingInfo(
$model->id,
$model->number,
$model->name,
$model->customer_id,
$customerNames[$model->customer_id] ?? '',
$model->status,
$model->payment_basis,
$model->quoted_amount_cents,
$model->customer_reference,
$model->billing_unit_id,
$model->billing_unit_id === null ? null : ($billingUnitNames[$model->customer_id][$model->billing_unit_id] ?? null),
);
}
return $result;
}
public function changes(int $jobId): array
{
$rows = DB::table('customer_job_changes')->where('customer_job_id', $jobId)->orderByDesc('id')->get();
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\Contracts;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek;
use App\Modules\TimeTracking\Application\DTOs\JobBillingHours;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
@@ -41,4 +42,14 @@ interface TimeEntryQueries
* @return list<ApprovalWeek>
*/
public function approvedWeeks(string $sinceMonday): array;
/**
* Unbilled hours of the jobs for billing: approved hours by work type,
* and the hours still waiting for approval. Keyed by job id; every job
* asked for is included.
*
* @param list<int> $jobIds
* @return array<int, JobBillingHours>
*/
public function billingHours(array $jobIds): array;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* A job's unbilled hours for billing, in quarters of an hour.
*/
final readonly class JobBillingHours
{
/**
* @param array<int, int> $approvedQuartersByWorkType Approved, unbilled hours keyed by work type id.
* @param int $unapprovedQuarters Hours still waiting for approval.
*/
public function __construct(
public int $jobId,
public array $approvedQuartersByWorkType,
public int $unapprovedQuarters,
) {}
}
@@ -10,7 +10,8 @@ use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
/**
* Cancels the approval of a user's week so the hours can be corrected.
* Only management may do this; the caller checks it.
* Billed hours keep their approval. Only management may do this; the
* caller checks it.
*/
final class CancelWeekApproval
{
@@ -31,7 +32,7 @@ final class CancelWeekApproval
$cancelled = 0;
foreach ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) {
if (! $entry->isApproved()) {
if (! $entry->isApproved() || $entry->isBilled()) {
continue;
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
/**
* Marks a job's approved, unbilled hours billed on a billing material, so
* they are never billed twice. Hours waiting for approval are left as they
* are. The caller (billing) checks who may do this.
*/
final class MarkJobHoursBilled
{
public function __construct(
private TimeEntryRepository $entries,
private TransactionManager $transactions,
) {}
/**
* @return array<int, int> The quarters marked billed, keyed by work type id.
*/
public function execute(int $jobId, int $billingExportId): array
{
return $this->transactions->run(function () use ($jobId, $billingExportId): array {
$quarters = [];
foreach ($this->entries->approvedUnbilledForJob($jobId) as $entry) {
$entry->markBilled($billingExportId);
$this->entries->save($entry);
$quarters[$entry->workTypeId()] = ($quarters[$entry->workTypeId()] ?? 0) + $entry->hours()->quarters;
}
return $quarters;
});
}
}
@@ -27,6 +27,13 @@ interface TimeEntryRepository
public function delete(TimeEntry $entry): void;
/**
* The job's approved entries that are not billed yet.
*
* @return list<TimeEntry>
*/
public function approvedUnbilledForJob(int $jobId): array;
/**
* The user's recorded quarters of an hour on the day, all tasks.
*/
@@ -11,7 +11,8 @@ use DateTimeImmutable;
/**
* A user's hours on one task on one day (one entry per day). The job and
* work type are copied from the task when the entry is made, for billing.
* Approved hours are locked until management cancels the approval.
* Approved hours are locked until management cancels the approval; billed
* hours (on a billing material) stay approved for good.
*/
final class TimeEntry
{
@@ -26,6 +27,7 @@ final class TimeEntry
private ?string $note,
private ?int $approvedBy = null,
private ?DateTimeImmutable $approvedAt = null,
private ?int $billingExportId = null,
) {}
public static function create(int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note = null): self
@@ -33,9 +35,9 @@ final class TimeEntry
return new self(null, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, self::text($note));
}
public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null): self
public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null, ?int $billingExportId = null): self
{
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt);
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt, $billingExportId);
}
/**
@@ -75,12 +77,39 @@ final class TimeEntry
$this->approvedAt = $approvedAt;
}
/**
* Cancels the approval, unless the hours are billed.
*/
public function cancelApproval(): void
{
if ($this->isBilled()) {
return;
}
$this->approvedBy = null;
$this->approvedAt = null;
}
/**
* Marks approved hours billed on the given billing material.
*/
public function markBilled(int $billingExportId): void
{
if ($this->isApproved() && ! $this->isBilled()) {
$this->billingExportId = $billingExportId;
}
}
public function isBilled(): bool
{
return $this->billingExportId !== null;
}
public function billingExportId(): ?int
{
return $this->billingExportId;
}
public function isApproved(): bool
{
return $this->approvedAt !== null;
@@ -21,9 +21,10 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $note
* @property CarbonImmutable|null $approved_at
* @property int|null $approved_by
* @property int|null $billing_export_id
*/
#[Table('time_entries')]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by'])]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by', 'billing_export_id'])]
#[UseFactory(TimeEntryFactory::class)]
class TimeEntryModel extends Model
{
@@ -43,6 +44,7 @@ class TimeEntryModel extends Model
'worked_on' => 'immutable_date',
'approved_at' => 'immutable_datetime',
'approved_by' => 'integer',
'billing_export_id' => 'integer',
];
}
@@ -5,6 +5,7 @@ namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek;
use App\Modules\TimeTracking\Application\DTOs\JobBillingHours;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekApproval;
use App\Modules\TimeTracking\Application\DTOs\WeekRow;
@@ -68,6 +69,34 @@ class EloquentTimeEntryQueries implements TimeEntryQueries
return new WeekSheet($days, $rows, $dayTotals, array_sum($dayTotals), (int) $unapproved, $this->latestApproval($entries));
}
public function billingHours(array $jobIds): array
{
$approved = array_fill_keys($jobIds, []);
$unapproved = array_fill_keys($jobIds, 0);
if ($jobIds !== []) {
$entries = TimeEntryModel::query()
->whereIn('customer_job_id', $jobIds)
->whereNull('billing_export_id')
->get(['customer_job_id', 'work_type_id', 'hours', 'approved_at']);
foreach ($entries as $entry) {
if ($entry->approved_at === null) {
$unapproved[$entry->customer_job_id] += $entry->quarters();
} else {
$approved[$entry->customer_job_id][$entry->work_type_id] = ($approved[$entry->customer_job_id][$entry->work_type_id] ?? 0) + $entry->quarters();
}
}
}
$result = [];
foreach ($jobIds as $jobId) {
$result[$jobId] = new JobBillingHours($jobId, $approved[$jobId], $unapproved[$jobId]);
}
return $result;
}
public function entriesForTask(int $taskId, int $userId): array
{
return TimeEntryModel::query()
@@ -42,6 +42,7 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
'note' => $entry->note(),
'approved_by' => $entry->approvedBy(),
'approved_at' => $entry->approvedAt()?->format('Y-m-d H:i:s'),
'billing_export_id' => $entry->billingExportId(),
])->save();
return $this->toEntity($model->refresh());
@@ -64,6 +65,20 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
TimeEntryModel::query()->whereKey($entry->id())->delete();
}
public function approvedUnbilledForJob(int $jobId): array
{
return TimeEntryModel::query()
->where('customer_job_id', $jobId)
->whereNotNull('approved_at')
->whereNull('billing_export_id')
->orderBy('worked_on')
->orderBy('id')
->get()
->map(fn (TimeEntryModel $model): TimeEntry => $this->toEntity($model))
->values()
->all();
}
public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int
{
return (int) round((float) TimeEntryModel::query()
@@ -86,6 +101,7 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
$model->note,
$model->approved_by,
$model->approved_at === null ? null : DateTimeImmutable::createFromInterface($model->approved_at),
$model->billing_export_id,
);
}
}