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
+2 -2
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project ## Project
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs, management's billable hours, and on creation invoice lines with price snapshots; reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
- **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec. - **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec.
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start. - **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
@@ -22,7 +22,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`. - **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, `billing.manage`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP. - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP.
- **Company details** (name, business ID, address, phone, email) are kept by `Shared\Application\UseCases\CompanyDetailsStore` in the settings (`shared.company_*`) and edited by the admin on `shared::company` (`/settings/company`, gate `settings.manage`). `BusinessId` (Y-tunnus with check digit) is a Shared value object. - **Company details** (name, business ID, address, phone, email) are kept by `Shared\Application\UseCases\CompanyDetailsStore` in the settings (`shared.company_*`) and edited by the admin on `shared::company` (`/settings/company`, gate `settings.manage`). `BusinessId` (Y-tunnus with check digit) is a Shared value object.
- **PDFs** use `barryvdh/laravel-dompdf` with a plain Blade view (no Tailwind; DejaVu Sans), streamed inline: see the quick sale receipt `Sales\Presentation\Http\Controllers\ShowReceipt` and `Sales/Presentation/Views/receipt.blade.php` (view namespace `sales-views`). - **PDFs** use `barryvdh/laravel-dompdf` with a plain Blade view (no Tailwind; DejaVu Sans), streamed inline: see the quick sale receipt `Sales\Presentation\Http\Controllers\ShowReceipt` and `Sales/Presentation/Views/receipt.blade.php` (view namespace `sales-views`).
@@ -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 forUserInMonth(int $userId, string $month): array;
public function find(int $id): ?ExpenseSummary; 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 { $this->transactions->run(function () use ($expenseId): void {
$expense = $this->expenses->findById($expenseId) ?? throw new ExpenseNotFound($expenseId); $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; throw new ExpenseLocked;
} }
@@ -36,7 +36,7 @@ final class UpdateExpense
$this->transactions->run(function () use ($expenseId, $data, $details): void { $this->transactions->run(function () use ($expenseId, $data, $details): void {
$expense = $this->expenses->findById($expenseId) ?? throw new ExpenseNotFound($expenseId); $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; throw new ExpenseLocked;
} }
@@ -16,4 +16,11 @@ interface ExpenseRepository
public function save(Expense $expense): Expense; public function save(Expense $expense): Expense;
public function delete(Expense $expense): void; 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 * 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 final class Expense
{ {
@@ -18,6 +19,7 @@ final class Expense
private int $userId, private int $userId,
private int $recordedBy, private int $recordedBy,
private ExpenseDetails $details, private ExpenseDetails $details,
private ?int $billingExportId = null,
) {} ) {}
public static function record(int $jobId, int $userId, int $recordedBy, ExpenseDetails $details): self 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); 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 public function change(int $userId, ExpenseDetails $details): void
@@ -30,6 +30,7 @@ use Illuminate\Support\Carbon;
* @property bool $is_billable * @property bool $is_billable
* @property int|null $markup_basis_points * @property int|null $markup_basis_points
* @property int|null $billed_amount_cents * @property int|null $billed_amount_cents
* @property int|null $billing_export_id
*/ */
#[Table('expenses')] #[Table('expenses')]
#[Fillable([ #[Fillable([
@@ -42,6 +42,19 @@ class EloquentExpenseQueries implements ExpenseQueries
return $this->summaries(ExpenseModel::query()->whereKey($id))[0] ?? null; 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 * @param Builder<ExpenseModel> $query
* @return list<ExpenseSummary> * @return list<ExpenseSummary>
@@ -51,6 +51,24 @@ class EloquentExpenseRepository implements ExpenseRepository
ExpenseModel::query()->whereKey($expense->id())->delete(); 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 private function toEntity(ExpenseModel $model): Expense
{ {
$billing = $model->is_billable && $model->billed_amount_cents !== null $billing = $model->is_billable && $model->billed_amount_cents !== null
@@ -77,6 +95,7 @@ class EloquentExpenseRepository implements ExpenseRepository
$model->purpose, $model->purpose,
$billing, $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\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary; 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\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter; use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Contracts\Pagination\LengthAwarePaginator;
/** /**
@@ -41,6 +43,21 @@ interface CustomerJobQueries
*/ */
public function summariesByIds(array $ids): array; 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. * 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\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails; use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary; 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\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter; use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Application\DTOs\NamedId; 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 public function changes(int $jobId): array
{ {
$rows = DB::table('customer_job_changes')->where('customer_job_id', $jobId)->orderByDesc('id')->get(); $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; namespace App\Modules\TimeTracking\Application\Contracts;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek; 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\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet; use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
@@ -41,4 +42,14 @@ interface TimeEntryQueries
* @return list<ApprovalWeek> * @return list<ApprovalWeek>
*/ */
public function approvedWeeks(string $sinceMonday): array; 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. * 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 final class CancelWeekApproval
{ {
@@ -31,7 +32,7 @@ final class CancelWeekApproval
$cancelled = 0; $cancelled = 0;
foreach ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) { foreach ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) {
if (! $entry->isApproved()) { if (! $entry->isApproved() || $entry->isBilled()) {
continue; 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; 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. * 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 * 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. * 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 final class TimeEntry
{ {
@@ -26,6 +27,7 @@ final class TimeEntry
private ?string $note, private ?string $note,
private ?int $approvedBy = null, private ?int $approvedBy = null,
private ?DateTimeImmutable $approvedAt = 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 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)); 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; $this->approvedAt = $approvedAt;
} }
/**
* Cancels the approval, unless the hours are billed.
*/
public function cancelApproval(): void public function cancelApproval(): void
{ {
if ($this->isBilled()) {
return;
}
$this->approvedBy = null; $this->approvedBy = null;
$this->approvedAt = 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 public function isApproved(): bool
{ {
return $this->approvedAt !== null; return $this->approvedAt !== null;
@@ -21,9 +21,10 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $note * @property string|null $note
* @property CarbonImmutable|null $approved_at * @property CarbonImmutable|null $approved_at
* @property int|null $approved_by * @property int|null $approved_by
* @property int|null $billing_export_id
*/ */
#[Table('time_entries')] #[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)] #[UseFactory(TimeEntryFactory::class)]
class TimeEntryModel extends Model class TimeEntryModel extends Model
{ {
@@ -43,6 +44,7 @@ class TimeEntryModel extends Model
'worked_on' => 'immutable_date', 'worked_on' => 'immutable_date',
'approved_at' => 'immutable_datetime', 'approved_at' => 'immutable_datetime',
'approved_by' => 'integer', '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\Jobs\Application\Contracts\TaskQueries;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries; use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek; 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\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekApproval; use App\Modules\TimeTracking\Application\DTOs\WeekApproval;
use App\Modules\TimeTracking\Application\DTOs\WeekRow; 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)); 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 public function entriesForTask(int $taskId, int $userId): array
{ {
return TimeEntryModel::query() return TimeEntryModel::query()
@@ -42,6 +42,7 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
'note' => $entry->note(), 'note' => $entry->note(),
'approved_by' => $entry->approvedBy(), 'approved_by' => $entry->approvedBy(),
'approved_at' => $entry->approvedAt()?->format('Y-m-d H:i:s'), 'approved_at' => $entry->approvedAt()?->format('Y-m-d H:i:s'),
'billing_export_id' => $entry->billingExportId(),
])->save(); ])->save();
return $this->toEntity($model->refresh()); return $this->toEntity($model->refresh());
@@ -64,6 +65,20 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
TimeEntryModel::query()->whereKey($entry->id())->delete(); 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 public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int
{ {
return (int) round((float) TimeEntryModel::query() return (int) round((float) TimeEntryModel::query()
@@ -86,6 +101,7 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
$model->note, $model->note,
$model->approved_by, $model->approved_by,
$model->approved_at === null ? null : DateTimeImmutable::createFromInterface($model->approved_at), $model->approved_at === null ? null : DateTimeImmutable::createFromInterface($model->approved_at),
$model->billing_export_id,
); );
} }
} }
+2
View File
@@ -1,5 +1,6 @@
<?php <?php
use App\Modules\Billing\Infrastructure\Providers\BillingServiceProvider;
use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider; use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider;
use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider;
use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider; use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider;
@@ -22,4 +23,5 @@ return [
TimeTrackingServiceProvider::class, TimeTrackingServiceProvider::class,
ExpensesServiceProvider::class, ExpensesServiceProvider::class,
SalesServiceProvider::class, SalesServiceProvider::class,
BillingServiceProvider::class,
]; ];
@@ -0,0 +1,85 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Billing material (laskuaineisto): a draft of invoices made of finished
* jobs, with management's billable hours per work type, and the invoice
* lines formed when the material is created.
*/
public function up(): void
{
Schema::create('billing_exports', function (Blueprint $table) {
$table->id();
$table->string('status', 20);
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
$table->foreignId('finalized_by')->nullable()->constrained('users')->restrictOnDelete();
$table->timestamp('finalized_at')->nullable();
$table->timestamps();
$table->index('status');
});
Schema::create('billing_invoices', function (Blueprint $table) {
$table->id();
$table->foreignId('billing_export_id')->constrained()->cascadeOnDelete();
$table->foreignId('customer_id')->constrained()->restrictOnDelete();
$table->foreignId('billing_unit_id')->nullable()->constrained()->nullOnDelete();
$table->string('customer_reference')->nullable();
$table->unsignedInteger('sort_order')->default(0);
$table->timestamps();
});
Schema::create('billing_invoice_jobs', function (Blueprint $table) {
$table->id();
$table->foreignId('billing_invoice_id')->constrained()->cascadeOnDelete();
// A job is on one invoice of a material; a later material may bill it again.
$table->foreignId('customer_job_id')->constrained()->restrictOnDelete();
// The job's billing details when it was added, which decide what it may be billed with.
$table->foreignId('customer_id')->constrained()->restrictOnDelete();
$table->foreignId('billing_unit_id')->nullable()->constrained()->nullOnDelete();
$table->string('customer_reference')->nullable();
$table->unsignedInteger('sort_order')->default(0);
});
Schema::create('billing_job_hours', function (Blueprint $table) {
$table->id();
$table->foreignId('billing_invoice_job_id')->constrained()->cascadeOnDelete();
$table->foreignId('work_type_id')->constrained()->restrictOnDelete();
$table->unsignedInteger('billable_quarters');
$table->unique(['billing_invoice_job_id', 'work_type_id']);
});
Schema::create('billing_lines', function (Blueprint $table) {
$table->id();
$table->foreignId('billing_invoice_id')->constrained()->cascadeOnDelete();
$table->foreignId('customer_job_id')->constrained()->restrictOnDelete();
$table->string('kind', 20);
$table->foreignId('work_type_id')->nullable()->constrained()->restrictOnDelete();
$table->foreignId('expense_id')->nullable()->constrained()->restrictOnDelete();
$table->string('description');
$table->unsignedInteger('recorded_quarters')->nullable();
$table->unsignedInteger('quantity_quarters')->nullable();
$table->integer('unit_price_cents');
$table->unsignedSmallInteger('vat_basis_points');
$table->integer('net_cents');
$table->unsignedInteger('sort_order')->default(0);
$table->index(['customer_job_id', 'kind']);
});
}
public function down(): void
{
Schema::dropIfExists('billing_lines');
Schema::dropIfExists('billing_job_hours');
Schema::dropIfExists('billing_invoice_jobs');
Schema::dropIfExists('billing_invoices');
Schema::dropIfExists('billing_exports');
}
};
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Marks hours and expenses billed: the billing material they went to, so
* they are never billed twice.
*/
public function up(): void
{
Schema::table('time_entries', function (Blueprint $table) {
$table->foreignId('billing_export_id')->nullable()->after('approved_by')->constrained()->restrictOnDelete();
});
Schema::table('expenses', function (Blueprint $table) {
$table->foreignId('billing_export_id')->nullable()->after('billed_amount_cents')->constrained()->restrictOnDelete();
});
}
public function down(): void
{
Schema::table('expenses', function (Blueprint $table) {
$table->dropConstrainedForeignId('billing_export_id');
});
Schema::table('time_entries', function (Blueprint $table) {
$table->dropConstrainedForeignId('billing_export_id');
});
}
};
+18 -7
View File
@@ -315,6 +315,10 @@ Hierarkiaa muokataan pohjatietojen hallinnasta.
- **Laskun peruste**: lasku tehdään joko yhdestä asiakastyöstä tai yhdistämällä useampi saman asiakkaan ja saman laskutusyksikön asiakastyö yhdelle laskulle. Johto valitsee aineistoa muodostaessaan, mitkä työt yhdistetään. Eri laskutusyksiköiden töitä ei yhdistetä samalle laskulle. Töitä, joilla on eri asiakkaan viite (PO-numero), ei myöskään yhdistetä: niistä tehdään omat laskunsa. Töitä, joilla ei ole viitettä, voi yhdistää keskenään tai saman viitteen töihin. - **Laskun peruste**: lasku tehdään joko yhdestä asiakastyöstä tai yhdistämällä useampi saman asiakkaan ja saman laskutusyksikön asiakastyö yhdelle laskulle. Johto valitsee aineistoa muodostaessaan, mitkä työt yhdistetään. Eri laskutusyksiköiden töitä ei yhdistetä samalle laskulle. Töitä, joilla on eri asiakkaan viite (PO-numero), ei myöskään yhdistetä: niistä tehdään omat laskunsa. Töitä, joilla ei ole viitettä, voi yhdistää keskenään tai saman viitteen töihin.
- Yhdistetyllä laskulla rivit ryhmitellään asiakastöittäin (työn numero ja nimi otsikkona), jotta asiakas näkee, mistä työstä kukin rivi tulee. - Yhdistetyllä laskulla rivit ryhmitellään asiakastöittäin (työn numero ja nimi otsikkona), jotta asiakas näkee, mistä työstä kukin rivi tulee.
- Aineiston muodostus asettaa töille tilan "Lasku luotu" ja merkitsee rivit laskutetuiksi, jotta niitä ei laskuteta kahdesti. - Aineiston muodostus asettaa töille tilan "Lasku luotu" ja merkitsee rivit laskutetuiksi, jotta niitä ei laskuteta kahdesti.
- Aineistoon tulevat vain **hyväksytyt** tunnit. Hyväksymättömät tunnit näytetään luonnoksessa varoituksena linkillä hyväksyntään; ne jäävät laskuttamatta, kun työ siirtyy tilaan Lasku luotu *(valmis)*.
- **Kiinteä tarjous**: laskulle tulee yksi rivi, jonka summa on työn tarjoussumma (veroton), vain kerran. Hyväksytyt tunnit näytetään tietona ja merkitään laskutetuiksi. Kulut tulevat eriteltyinä *(valmis)*.
- Laskuttamatta jätetään työt, joiden maksuperuste on "ei laskuteta" tai kuukausilaskutus, sisäisen asiakkaan työt, kuluttajat ilman henkilötunnusta ja työt, joiden työtehtävältä puuttuu tuntihinta; syy näytetään johdolle *(valmis)*.
- Laskutetut tunnit pysyvät hyväksyttyinä (hyväksynnän peruminen ohittaa ne), eikä laskutettua kulua voi muuttaa tai poistaa *(valmis)*.
## 13. Ilmoitukset ja raportit *(K52, K53)* ## 13. Ilmoitukset ja raportit *(K52, K53)*
@@ -362,21 +366,22 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
- `workflow_templates` *(V3)*: `work_type_id`, `name`; `workflow_template_steps`: `workflow_template_id`, `title`, `description`, `sort_order` - `workflow_templates` *(V3)*: `work_type_id`, `name`; `workflow_template_steps`: `workflow_template_id`, `title`, `description`, `sort_order`
**TimeTracking** **TimeTracking**
- `time_entries`: `user_id`, `task_id`, `customer_job_id` (denormalisoitu), `work_type_id` (tehtävän työtehtävä kirjaushetkellä), `worked_on`, `hours`, `note` *(olemassa; uniikki käyttäjä + tehtävä + päivä)*, `approved_at`, `approved_by` *(V2, olemassa)*, `billing_export_id` *(V2)* - `time_entries`: `user_id`, `task_id`, `customer_job_id` (denormalisoitu), `work_type_id` (tehtävän työtehtävä kirjaushetkellä), `worked_on`, `hours`, `note` *(olemassa; uniikki käyttäjä + tehtävä + päivä)*, `approved_at`, `approved_by`, `billing_export_id` (laskuaineisto, jolla tunnit laskutettiin) *(V2, olemassa)*
**Expenses** *(V2)* **Expenses** *(V2)*
- `expenses` *(olemassa)*: `customer_job_id`, `user_id` (kenen kulu), `recorded_by`, `category` (`materials`/`mileage`/`other`), `paid_by` (`company`/`employee`), `spent_on`, `description`, `cost_cents` (hankintahinta), `kilometers` (decimal 7,1), `destination`, `purpose`, `is_billable`, `markup_basis_points`, `billed_amount_cents` (laskutettava summa, null jos ei laskuteta); `billing_export_id` lisätään laskutuksen osassa - `expenses` *(olemassa)*: `customer_job_id`, `user_id` (kenen kulu), `recorded_by`, `category` (`materials`/`mileage`/`other`), `paid_by` (`company`/`employee`), `spent_on`, `description`, `cost_cents` (hankintahinta), `kilometers` (decimal 7,1), `destination`, `purpose`, `is_billable`, `markup_basis_points`, `billed_amount_cents` (laskutettava summa, null jos ei laskuteta), `billing_export_id` (laskuaineisto, jolla kulu laskutettiin) *(olemassa)*
**Sales** *(V2, olemassa)* **Sales** *(V2, olemassa)*
- `quick_sales`: `user_id` (myyjä), `customer_id` (nullable), `payment_method` (`cash`/`card`), `sold_at`, `sold_on` (kassapäivä yrityksen aikavyöhykkeellä), `total_cents` (verollinen, hyvityksellä negatiivinen), `credits_quick_sale_id` (nullable, uniikki: hyvitetty myynti) - `quick_sales`: `user_id` (myyjä), `customer_id` (nullable), `payment_method` (`cash`/`card`), `sold_at`, `sold_on` (kassapäivä yrityksen aikavyöhykkeellä), `total_cents` (verollinen, hyvityksellä negatiivinen), `credits_quick_sale_id` (nullable, uniikki: hyvitetty myynti)
- `quick_sale_lines`: `quick_sale_id`, `product_id`, `product_name`, `quantity` (hyvityksellä negatiivinen), `unit_price_cents` (verollinen), `vat_basis_points`, `sort_order` - `quick_sale_lines`: `quick_sale_id`, `product_id`, `product_name`, `quantity` (hyvityksellä negatiivinen), `unit_price_cents` (verollinen), `vat_basis_points`, `sort_order`
- `cash_days`: `day` (uniikki), `closed_by`, `closed_at`, `sale_count`, `cash_cents`, `card_cents`, `total_cents`, `reopened_by`, `reopened_at`; `cash_day_vat_totals`: `cash_day_id`, `vat_basis_points`, `gross_cents`, `net_cents`, `vat_cents` - `cash_days`: `day` (uniikki), `closed_by`, `closed_at`, `sale_count`, `cash_cents`, `card_cents`, `total_cents`, `reopened_by`, `reopened_at`; `cash_day_vat_totals`: `cash_day_id`, `vat_basis_points`, `gross_cents`, `net_cents`, `vat_cents`
**Billing** *(V2)* **Billing** *(V2, olemassa)*
- `billing_exports`: `period` (kuukausi), `created_by`, `file_path` - `billing_exports`: `status` (`draft`/`created`; luonnoksia yksi kerrallaan), `created_by`, `finalized_by`, `finalized_at` (vientitiedosto lisätään Fennoa-viennin osassa)
- `invoices`: `billing_export_id`, `customer_id`, `billing_unit_id`, `customer_reference` (laskun töiden yhteinen PO-viite, jos on) - `billing_invoices`: `billing_export_id`, `customer_id`, `billing_unit_id`, `customer_reference` (laskun töiden yhteinen PO-viite, jos on), `sort_order`
- `invoice_jobs`: `invoice_id`, `customer_job_id` (yksi tai useampi saman asiakkaan, laskutusyksikön ja PO-viitteen työ; työ on yhden kuukauden aineistossa vain yhdellä laskulla) - `billing_invoice_jobs`: `billing_invoice_id`, `customer_job_id`, työn `customer_id`, `billing_unit_id` ja `customer_reference` lisäyshetkellä, `sort_order` (työ on aineistossa vain yhdellä laskulla)
- `billing_export_lines`: `billing_export_id`, `invoice_id`, `customer_job_id`, `type` (`hours`/`expense`/`monthly_fee`/`product`), `work_type_id`, `description`, `recorded_hours` (hyväksytyt tunnit, vain tuntiriveille), `quantity` (laskutettava määrä), `unit_price_cents`, `total_cents` - `billing_job_hours`: `billing_invoice_job_id`, `work_type_id`, `billable_quarters` (johdon kirjaama laskutettava määrä; ilman riviä laskutetaan hyväksytyt tunnit)
- `billing_lines` (muodostuksessa): `billing_invoice_id`, `customer_job_id`, `kind` (`hours`/`fixed_price`/`expense`; kuukausirivit myöhemmin), `work_type_id`, `expense_id`, `description`, `recorded_quarters` (hyväksytyt tunnit), `quantity_quarters` (laskutettu määrä), `unit_price_cents`, `vat_basis_points`, `net_cents`, `sort_order`
## 15. Vaiheistus ## 15. Vaiheistus
@@ -477,6 +482,12 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
- Valikon "Pikamyynti" (`/sales/new`) puhelimelle sopiva lomake: tuotepainikkeet, myynnin lista määrineen (muutokset ja yhteissumma ilmoitetaan ruudunlukijalle), maksutapa ja vapaaehtoinen asiakas. Tallennuksen jälkeen lomake tyhjenee ja ilmoitus kertoo myynnin numeron, summan ja kirjatut tunnit sekä linkin PDF-kuittiin. Myynnit-sivulla on kuittilinkki jokaisella rivillä. - Valikon "Pikamyynti" (`/sales/new`) puhelimelle sopiva lomake: tuotepainikkeet, myynnin lista määrineen (muutokset ja yhteissumma ilmoitetaan ruudunlukijalle), maksutapa ja vapaaehtoinen asiakas. Tallennuksen jälkeen lomake tyhjenee ja ilmoitus kertoo myynnin numeron, summan ja kirjatut tunnit sekä linkin PDF-kuittiin. Myynnit-sivulla on kuittilinkki jokaisella rivillä.
- Myynnit-sivu (`/sales?paiva=VVVV-KK-PP`): päivän myynnit (työntekijä näkee omansa, johto kaikkien ja voi suodattaa myyjän mukaan), hyvitys vahvistusdialogissa, kassapäivän tila, saldo ja ALV-erittely, päättäminen ja johdolle uudelleen avaaminen vahvistusdialogissa, muistutus päättämättömistä aiemmista päivistä. - Myynnit-sivu (`/sales?paiva=VVVV-KK-PP`): päivän myynnit (työntekijä näkee omansa, johto kaikkien ja voi suodattaa myyjän mukaan), hyvitys vahvistusdialogissa, kassapäivän tila, saldo ja ALV-erittely, päättäminen ja johdolle uudelleen avaaminen vahvistusdialogissa, muistutus päättämättömistä aiemmista päivistä.
### 17.7 Laskuaineisto *(valmis, Fennoa-vienti ja kuukausirivit tulossa)*
- Valikon "Laskutus" (`/billing`, pääkäyttäjä ja johto): laskuaineistot (tila, laskujen ja töiden määrä, veroton summa) sekä uuden luonnoksen aloitus tai avoimen jatkaminen.
- Luonnos (`/billing/{aineisto}`): valmiit työt lisätään yksitellen, ja jokainen on aluksi oma laskunsa. Työn voi siirtää toiselle laskulle, jos asiakas, laskutusyksikkö ja viite sallivat (luku 12), tehdä siitä taas oman laskun tai poistaa. Laskutettavat tunnit kirjataan työtehtävittäin (oletuksena hyväksytyt tunnit). Jokaisella laskulla on veroton summa, ALV kannoittain ja verollinen summa (oletus-ALV-kanta). Muutokset tallentuvat heti.
- "Muodosta aineisto" vahvistusdialogissa tarkistaa työt uudelleen, merkitsee hyväksytyt tunnit ja laskutettavat kulut laskutetuiksi, muodostaa rivit hinnan ja ALV:n tilannekuvineen ja siirtää työt tilaan Lasku luotu. Muodostettu aineisto näytetään lukutilassa riveineen. Luonnoksen voi hylätä, jolloin mitään ei laskuteta.
- Tulossa: CSV/Excel-vienti Fennoan tuontimuotoon (avoin kysymys 4) ja kuukausilaskutusrivit.
## 18. Avoimet kysymykset ## 18. Avoimet kysymykset
1. ~~**Lukitus**~~: ratkaistu – vain johto avaa valmiin työn lukituksen siirtämällä työn aiempaan tilaan, ja avaus näkyy muutoshistoriassa (5.3). 1. ~~**Lukitus**~~: ratkaistu – vain johto avaa valmiin työn lukituksen siirtämällä työn aiempaan tilaan, ja avaus näkyy muutoshistoriassa (5.3).
+163
View File
@@ -0,0 +1,163 @@
<?php
return [
'expense_line' => ':category :day: :what',
'statuses' => [
'draft' => 'Luonnos',
'created' => 'Muodostettu',
],
'modes' => [
'hours' => 'Tuntityö',
'fixed_price' => 'Kiinteä hinta',
'none' => 'Ei laskuteta näin',
],
'kinds' => [
'hours' => 'Tunnit',
'fixed_price' => 'Kiinteä hinta',
'expense' => 'Kulu',
],
'reasons' => [
'wrong_status' => 'Työ ei ole valmis.',
'not_billable_basis' => 'Työtä ei laskuteta aineistolla (ei laskuteta, kuukausilaskutus tai sisäinen asiakas).',
'missing_identity_code' => 'Asiakkaan henkilötunnus puuttuu.',
'missing_hourly_rate' => 'Tuntihinta puuttuu: :names',
'missing_quoted_amount' => 'Kiinteän hinnan työltä puuttuu tarjoussumma.',
'nothing_to_bill' => 'Ei laskutettavaa: ei hyväksyttyjä tunteja eikä laskutettavia kuluja.',
],
'merge_refusals' => [
'different_customer' => 'Töillä on eri asiakas.',
'different_billing_unit' => 'Töillä on eri laskutusyksikkö.',
'different_reference' => 'Töillä on eri asiakkaan viite.',
],
'index' => [
'title' => 'Laskutus',
'intro' => 'Laskuaineistoon kootaan kerran kuukaudessa valmiiden töiden hyväksytyt tunnit ja laskutettavat kulut. Aineistoa työstetään luonnoksena, ja muodostus merkitsee rivit laskutetuiksi ja työt tilaan Lasku luotu.',
'new' => 'Uusi aineisto',
'continue' => 'Jatka luonnosta',
'none' => 'Laskuaineistoja ei ole vielä.',
'table' => 'Laskuaineistot',
'columns' => [
'number' => 'Aineisto',
'status' => 'Tila',
'created' => 'Aloitettu',
'finalized' => 'Muodostettu',
'invoices' => 'Laskuja',
'jobs' => 'Töitä',
'net' => 'Veroton summa',
],
'export_label' => 'Aineisto :number',
],
'export' => [
'title' => 'Laskuaineisto :number',
'back' => 'Kaikki laskuaineistot',
'draft_info' => 'Luonnos, aloittanut :name :at. Muutokset tallentuvat heti.',
'created_info' => 'Muodostettu :at, muodostaja :name.',
'summary' => ':invoices laskua, :jobs työtä, veroton yhteensä :net.',
'finalize' => 'Muodosta aineisto',
'finalize_title' => 'Muodostetaanko laskuaineisto?',
'finalize_text' => 'Aineistoon tulee :invoices laskua, veroton yhteensä :net. Muodostus merkitsee tunnit ja kulut laskutetuiksi ja siirtää työt tilaan Lasku luotu. Muodostettua aineistoa ei voi enää muuttaa.',
'finalized' => 'Laskuaineisto muodostettu: :invoices laskua.',
'discard' => 'Hylkää luonnos',
'discard_title' => 'Hylätäänkö luonnos?',
'discard_text' => 'Luonnos poistetaan. Mitään ei ole vielä laskutettu, joten työt pysyvät ennallaan.',
'discarded' => 'Luonnos hylätty.',
'problems' => 'Kaikkia töitä ei voi laskuttaa. Korjaa tai poista merkityt työt ennen muodostusta.',
],
'invoices' => [
'title' => 'Laskut',
'none' => 'Luonnoksessa ei ole vielä töitä. Lisää valmiita töitä alta.',
'heading' => 'Lasku :number: :customer',
'billing_unit' => 'Laskutusyksikkö',
'reference' => 'Asiakkaan viite',
'no_billing_unit' => 'Ei laskutusyksikköä',
'no_reference' => 'Ei viitettä',
'totals' => 'Laskun summat',
'net' => 'Veroton',
'vat' => 'ALV :rate',
'gross' => 'Verollinen',
'export_totals' => 'Aineiston summat',
],
'jobs' => [
'open_job' => 'Avaa työ :job',
'mode' => 'Laskutustapa: :mode',
'unapproved' => 'Hyväksymättömiä tunteja :hours h. Ne eivät tule aineistoon, ja koska työ siirtyy tilaan Lasku luotu, ne jäävät laskuttamatta.',
'approvals_link' => 'Tuntien hyväksyntä',
'hours_caption' => 'Tunnit työtehtävittäin: :job',
'work_type' => 'Työtehtävä',
'approved_hours' => 'Hyväksytyt h',
'billable_hours' => 'Laskutettavat h',
'billable_label' => 'Laskutettavat tunnit: :work_type',
'adjusted' => 'muutettu',
'rate' => 'Tuntihinta',
'net' => 'Veroton',
'no_rate' => 'Puuttuu',
'billable_help' => 'Laskutettavat tunnit ovat oletuksena hyväksyttyjen tuntien summa. Tyhjä kenttä palauttaa oletuksen.',
'fixed_price' => 'Kiinteä hinta: :amount',
'fixed_price_billed' => 'Kiinteä hinta on jo laskutettu aiemmalla aineistolla.',
'fixed_hours' => 'Hyväksytyt tunnit :hours h näytetään tietona ja merkitään laskutetuiksi.',
'no_hours' => 'Ei hyväksyttyjä laskuttamattomia tunteja.',
'expenses_caption' => 'Kulut: :job',
'expense' => 'Kulu',
'amount' => 'Veroton',
'move_label' => 'Siirrä laskulle: :job',
'move_placeholder' => 'Valitse lasku',
'move' => 'Siirrä',
'move_named' => 'Siirrä työ :job',
'moved' => 'Työ :job siirretty laskulle.',
'separate' => 'Oma lasku',
'separate_named' => 'Tee työstä :job oma lasku',
'separated' => 'Työstä :job tehtiin oma lasku.',
'remove' => 'Poista aineistosta',
'remove_named' => 'Poista aineistosta: :job',
'removed' => 'Työ :job poistettu aineistosta.',
'hours_saved' => 'Laskutettavat tunnit tallennettu: :job, :work_type.',
],
'lines' => [
'caption' => 'Laskurivit: :job',
'description' => 'Rivi',
'recorded' => 'Kirjatut h',
'quantity' => 'Laskutetut h',
'unit_price' => 'Yksikköhinta',
'net' => 'Veroton',
],
'available' => [
'title' => 'Valmiit työt',
'intro' => 'Valmiit työt, joita ei ole luonnoksessa. Jokainen lisätty työ on aluksi oma laskunsa.',
'none' => 'Ei muita valmiita töitä.',
'columns' => [
'job' => 'Työ',
'customer' => 'Asiakas',
'mode' => 'Laskutustapa',
'hours' => 'Hyväksytyt h',
'expenses' => 'Kuluja',
'notes' => 'Huomiot',
'actions' => 'Toiminnot',
],
'add' => 'Lisää aineistoon',
'add_named' => 'Lisää aineistoon: :job',
'added' => 'Työ :job lisätty aineistoon.',
'unapproved' => 'Hyväksymättä :hours h',
],
'errors' => [
'draft_open' => 'Luonnos on jo auki. Jatka sitä.',
'not_draft' => 'Aineisto on jo muodostettu, eikä sitä voi muuttaa.',
'not_found' => 'Laskuaineistoa ei löytynyt.',
'empty' => 'Aineistossa ei ole töitä.',
'already_in_draft' => 'Työ on jo aineistossa.',
'not_in_draft' => 'Työ ei ole aineistossa.',
'not_billable' => 'Työtä :job ei voi laskuttaa: :reason',
'hours' => 'Anna tunnit neljännestunnin tarkkuudella, esimerkiksi 12,5 tai 3,25.',
],
];
+1
View File
@@ -11,6 +11,7 @@ return [
'approvals' => 'Hyväksyntä', 'approvals' => 'Hyväksyntä',
'expenses' => 'Kulut', 'expenses' => 'Kulut',
'quick_sale' => 'Pikamyynti', 'quick_sale' => 'Pikamyynti',
'billing' => 'Laskutus',
'customers' => 'Asiakkaat', 'customers' => 'Asiakkaat',
'users' => 'Käyttäjät', 'users' => 'Käyttäjät',
'company' => 'Yritystiedot', 'company' => 'Yritystiedot',
+4
View File
@@ -75,6 +75,10 @@
@include('partials.nav-item', ['route' => 'time.approvals', 'pattern' => 'time.approvals', 'label' => __('layout.approvals')]) @include('partials.nav-item', ['route' => 'time.approvals', 'pattern' => 'time.approvals', 'label' => __('layout.approvals')])
@endcan @endcan
@can('billing.manage')
@include('partials.nav-item', ['route' => 'billing.index', 'pattern' => 'billing.*', 'label' => __('layout.billing')])
@endcan
@can('customers.use') @can('customers.use')
@include('partials.nav-item', ['route' => 'customers.index', 'pattern' => 'customers.*', 'label' => __('layout.customers')]) @include('partials.nav-item', ['route' => 'customers.index', 'pattern' => 'customers.*', 'label' => __('layout.customers')])
@endcan @endcan
@@ -0,0 +1,78 @@
<?php
use App\Models\User;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->manager = User::factory()->management()->create(['name' => 'Maija Johtaja']);
$this->actingAs($this->manager);
$layout = WorkTypeModel::factory()->create(['name' => 'Taitto', 'hourly_rate_cents' => 8000]);
$customer = CustomerModel::factory()->company()->create(['name' => 'Asiakas Oy']);
$this->jobs = [];
foreach (['Esite', 'Juliste'] as $name) {
$job = CustomerJobModel::factory()->create(['name' => $name, 'customer_id' => $customer->id, 'status' => JobStatus::Done, 'payment_basis' => 'hourly']);
$task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => $layout->id]);
TimeEntryModel::factory()->approved()->create(['task_id' => $task->id, 'hours' => 2.5]);
TimeEntryModel::factory()->create(['task_id' => TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => $layout->id])->id, 'hours' => 1]);
$this->jobs[] = $job;
}
ExpenseModel::factory()->create(['customer_job_id' => $this->jobs[0]->id, 'description' => 'Paperi']);
$this->exportId = BillingExportModel::query()->create(['status' => 'draft', 'created_by' => $this->manager->id])->id;
});
it('has no accessibility issues on the billing pages', function (string $page, string $device, string $colorScheme) {
$url = $page === 'index' ? route('billing.index') : route('billing.export', $this->exportId);
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee($page === 'index' ? 'Jatka luonnosta' : 'Esite')
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['index', 'export'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('adds and combines jobs and creates the material', function () {
[$first, $second] = $this->jobs;
$page = visit(route('billing.export', $this->exportId));
$page->click('[wire\\:click="add('.$first->id.')"]')
->assertSee('lisätty aineistoon')
->click('[wire\\:click="add('.$second->id.')"]')
->assertSee('Lasku 2: Asiakas Oy')
->assertSee('Hyväksymättömiä tunteja 1 h')
->assertNoAccessibilityIssues(level: 2)
->select('[wire\\:model="moveTargets.'.$second->id.'"]', (string) $first->id)
->click('[wire\\:click="move('.$second->id.')"]')
->assertSee('siirretty laskulle')
->assertDontSee('Lasku 2: Asiakas Oy')
->click('Muodosta aineisto')
->assertSee('Muodostetaanko laskuaineisto?')
->assertNoAccessibilityIssues(level: 2)
->click('#finalize-dialog button:last-child')
->assertSee('Laskuaineisto muodostettu: 1 laskua.')
->assertSee('Laskutetut h')
->assertNoAccessibilityIssues(level: 2);
expect($first->refresh()->status)->toBe(JobStatus::Invoiced);
});
+15 -1
View File
@@ -20,7 +20,7 @@ class InMemoryExpenseRepository implements ExpenseRepository
public function save(Expense $expense): Expense public function save(Expense $expense): Expense
{ {
$id = $expense->id() ?? $this->nextId++; $id = $expense->id() ?? $this->nextId++;
$this->items[$id] = Expense::reconstitute($id, $expense->jobId(), $expense->userId(), $expense->recordedBy(), $expense->details()); $this->items[$id] = Expense::reconstitute($id, $expense->jobId(), $expense->userId(), $expense->recordedBy(), $expense->details(), $expense->billingExportId());
return clone $this->items[$id]; return clone $this->items[$id];
} }
@@ -29,4 +29,18 @@ class InMemoryExpenseRepository implements ExpenseRepository
{ {
unset($this->items[$expense->id()]); unset($this->items[$expense->id()]);
} }
public function markBillableAsBilled(int $jobId, int $billingExportId): array
{
$ids = [];
foreach ($this->items as $id => $expense) {
if ($expense->jobId() === $jobId && $expense->details()->isBillable() && ! $expense->isBilled()) {
$this->items[$id] = Expense::reconstitute($id, $expense->jobId(), $expense->userId(), $expense->recordedBy(), $expense->details(), $billingExportId);
$ids[] = $id;
}
}
return $ids;
}
} }
+8 -1
View File
@@ -34,7 +34,7 @@ class InMemoryTimeEntryRepository implements TimeEntryRepository
public function save(TimeEntry $entry): TimeEntry public function save(TimeEntry $entry): TimeEntry
{ {
$id = $entry->id() ?? $this->nextId++; $id = $entry->id() ?? $this->nextId++;
$this->entries[$id] = TimeEntry::reconstitute($id, $entry->userId(), $entry->taskId(), $entry->jobId(), $entry->workTypeId(), $entry->workedOn(), $entry->hours(), $entry->note(), $entry->approvedBy(), $entry->approvedAt()); $this->entries[$id] = TimeEntry::reconstitute($id, $entry->userId(), $entry->taskId(), $entry->jobId(), $entry->workTypeId(), $entry->workedOn(), $entry->hours(), $entry->note(), $entry->approvedBy(), $entry->approvedAt(), $entry->billingExportId());
return clone $this->entries[$id]; return clone $this->entries[$id];
} }
@@ -53,6 +53,13 @@ class InMemoryTimeEntryRepository implements TimeEntryRepository
unset($this->entries[$entry->id()]); unset($this->entries[$entry->id()]);
} }
public function approvedUnbilledForJob(int $jobId): array
{
$found = array_filter($this->entries, fn (TimeEntry $entry): bool => $entry->jobId() === $jobId && $entry->isApproved() && ! $entry->isBilled());
return array_values(array_map(fn (TimeEntry $entry): TimeEntry => clone $entry, $found));
}
public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int
{ {
$quarters = 0; $quarters = 0;
@@ -0,0 +1,227 @@
<?php
use App\Models\User;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Domain\Enums\LineKind;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingLineModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Expenses\Application\UseCases\RemoveExpense;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\TimeTracking\Application\UseCases\CancelWeekApproval;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->manager = User::factory()->management()->create(['name' => 'Maija Johtaja']);
$this->actingAs($this->manager);
$this->layout = WorkTypeModel::factory()->create(['name' => 'Taitto', 'hourly_rate_cents' => 8000]);
$this->photo = WorkTypeModel::factory()->create(['name' => 'Kuvaus', 'hourly_rate_cents' => 10000]);
$this->customer = CustomerModel::factory()->company()->create(['name' => 'Asiakas Oy']);
});
/**
* A done job of the test customer with approved hours on the given work types.
*
* @param array<string, mixed> $attributes
* @param array<int, float> $approvedHours Hours keyed by work type id.
*/
function doneJob(array $attributes = [], array $approvedHours = []): CustomerJobModel
{
$job = CustomerJobModel::factory()->create(array_merge([
'customer_id' => test()->customer->id,
'status' => JobStatus::Done,
'payment_basis' => 'hourly',
], $attributes));
foreach ($approvedHours as $workTypeId => $hours) {
$task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => $workTypeId]);
TimeEntryModel::factory()->approved()->create(['task_id' => $task->id, 'hours' => $hours]);
}
return $job;
}
function openDraft(): int
{
Livewire::test('billing::index')->call('openDraftNow')->assertRedirect();
return (int) BillingExportModel::query()->where('status', ExportStatus::Draft)->value('id');
}
it('combines jobs of the same customer on one invoice and creates the billing material', function () {
$first = doneJob(['name' => 'Esite'], [$this->layout->id => 2.5, $this->photo->id => 1]);
$second = doneJob(['name' => 'Juliste', 'customer_reference' => 'PO-1'], [$this->layout->id => 1]);
$waiting = TimeEntryModel::factory()->create([
'task_id' => TaskModel::factory()->create(['customer_job_id' => $first->id, 'work_type_id' => $this->layout->id])->id,
'hours' => 3,
]);
$expense = ExpenseModel::factory()->create(['customer_job_id' => $first->id, 'description' => 'Paperi', 'billed_amount_cents' => 5000]);
ExpenseModel::factory()->notBillable()->create(['customer_job_id' => $first->id]);
$exportId = openDraft();
$page = Livewire::test('billing::export', ['export' => $exportId])
->call('add', $first->id)
->call('add', $second->id)
->assertSet('errorMessage', '')
->set("moveTargets.{$second->id}", (string) $first->id)
->call('move', $second->id)
->assertSet('errorMessage', '')
->call('saveHours', $first->id, $this->layout->id, '2')
->assertHasNoErrors();
$view = $page->get('export');
expect($view->invoices)->toHaveCount(1)
->and($view->invoices[0]->reference)->toBe('PO-1')
->and($view->invoices[0]->jobs[0]->unapprovedQuarters)->toBe(12)
->and($view->invoices[0]->totals->netCents)->toBe(2 * 8000 + 10000 + 5000 + 8000);
$page->call('finalize')->assertSet('errorMessage', '')->assertSet('statusMessage', 'Laskuaineisto muodostettu: 1 laskua.');
$export = BillingExportModel::query()->sole();
expect($export->status)->toBe(ExportStatus::Created)
->and($export->finalized_by)->toBe($this->manager->id);
$lines = BillingLineModel::query()->orderBy('sort_order')->get();
expect($lines->map->only(['customer_job_id', 'kind', 'description', 'recorded_quarters', 'quantity_quarters', 'unit_price_cents', 'vat_basis_points', 'net_cents'])->all())->toBe([
['customer_job_id' => $first->id, 'kind' => LineKind::Hours, 'description' => 'Kuvaus', 'recorded_quarters' => 4, 'quantity_quarters' => 4, 'unit_price_cents' => 10000, 'vat_basis_points' => 2550, 'net_cents' => 10000],
['customer_job_id' => $first->id, 'kind' => LineKind::Hours, 'description' => 'Taitto', 'recorded_quarters' => 10, 'quantity_quarters' => 8, 'unit_price_cents' => 8000, 'vat_basis_points' => 2550, 'net_cents' => 16000],
['customer_job_id' => $first->id, 'kind' => LineKind::Expense, 'description' => 'Tuotteet, tarvikkeet ja materiaalit '.$expense->spent_on->format('j.n.Y').': Paperi', 'recorded_quarters' => null, 'quantity_quarters' => null, 'unit_price_cents' => 5000, 'vat_basis_points' => 2550, 'net_cents' => 5000],
['customer_job_id' => $second->id, 'kind' => LineKind::Hours, 'description' => 'Taitto', 'recorded_quarters' => 4, 'quantity_quarters' => 4, 'unit_price_cents' => 8000, 'vat_basis_points' => 2550, 'net_cents' => 8000],
]);
expect(TimeEntryModel::query()->whereKeyNot($waiting->id)->pluck('billing_export_id')->unique()->all())->toBe([$export->id])
->and($waiting->refresh()->billing_export_id)->toBeNull()
->and($expense->refresh()->billing_export_id)->toBe($export->id)
->and(ExpenseModel::query()->where('is_billable', false)->value('billing_export_id'))->toBeNull()
->and($first->refresh()->status)->toBe(JobStatus::Invoiced)
->and($second->refresh()->status)->toBe(JobStatus::Invoiced)
->and(DB::table('customer_job_changes')->where('customer_job_id', $first->id)->where('field', 'status')->value('user_id'))->toBe($this->manager->id);
Livewire::test('billing::export', ['export' => $export->id])
->assertSee('Muodostettu')
->call('add', $first->id)
->assertSet('errorMessage', 'Aineisto on jo muodostettu, eikä sitä voi muuttaa.');
});
it('bills a fixed price job with its quoted amount once and marks its hours billed', function () {
$job = doneJob(['name' => 'Verkkosivut', 'payment_basis' => 'fixed_quote', 'quoted_amount_cents' => 250000], [$this->layout->id => 10]);
$exportId = openDraft();
Livewire::test('billing::export', ['export' => $exportId])
->call('add', $job->id)
->call('finalize')
->assertSet('errorMessage', '');
$line = BillingLineModel::query()->sole();
expect($line->kind)->toBe(LineKind::FixedPrice)
->and($line->net_cents)->toBe(250000)
->and($line->description)->toBe($job->number.' Verkkosivut')
->and(TimeEntryModel::query()->sole()->billing_export_id)->toBe($exportId);
// Moved back to done by mistake: the fixed price is not billed again.
$job->refresh()->update(['status' => JobStatus::Done]);
$next = openDraft();
Livewire::test('billing::export', ['export' => $next])
->assertSee('Ei laskutettavaa')
->call('add', $job->id)
->assertSet('errorMessage', fn (string $message) => str_contains($message, 'Ei laskutettavaa'));
});
it('does not add jobs that cannot be billed', function () {
$consumer = CustomerModel::factory()->consumer()->create();
$withoutCode = doneJob(['customer_id' => $consumer->id], [$this->layout->id => 1]);
$noRate = WorkTypeModel::factory()->create(['name' => 'Suunnittelu', 'hourly_rate_cents' => null]);
$withoutRate = doneJob([], [$noRate->id => 2]);
$notBillable = doneJob(['payment_basis' => 'not_billable'], [$this->layout->id => 1]);
$notDone = doneJob(['status' => JobStatus::InProduction], [$this->layout->id => 1]);
$page = Livewire::test('billing::export', ['export' => openDraft()])
->assertSee('Asiakkaan henkilötunnus puuttuu.')
->assertSee('Tuntihinta puuttuu: Suunnittelu')
->assertDontSee($notDone->name);
foreach ([$withoutCode, $withoutRate, $notBillable, $notDone] as $job) {
$page->call('add', $job->id)->assertSet('errorMessage', fn (string $message) => $message !== '');
}
expect(DB::table('billing_invoice_jobs')->count())->toBe(0);
});
it('keeps jobs with different customer references on separate invoices', function () {
$first = doneJob(['customer_reference' => 'PO-1'], [$this->layout->id => 1]);
$second = doneJob(['customer_reference' => 'PO-2'], [$this->layout->id => 1]);
Livewire::test('billing::export', ['export' => openDraft()])
->call('add', $first->id)
->call('add', $second->id)
->set("moveTargets.{$second->id}", (string) $first->id)
->call('move', $second->id)
->assertSet('errorMessage', 'Töillä on eri asiakkaan viite.');
expect(DB::table('billing_invoices')->count())->toBe(2);
});
it('rejects billable hours that are not in quarters of an hour', function () {
$job = doneJob([], [$this->layout->id => 1]);
Livewire::test('billing::export', ['export' => openDraft()])
->call('add', $job->id)
->call('saveHours', $job->id, $this->layout->id, '1,1')
->assertHasErrors(["hours.{$job->id}.{$this->layout->id}"])
->call('saveHours', $job->id, $this->layout->id, '0,75')
->assertHasNoErrors();
expect(DB::table('billing_job_hours')->value('billable_quarters'))->toBe(3);
});
it('keeps one draft at a time and discards it without billing anything', function () {
$job = doneJob([], [$this->layout->id => 1]);
$exportId = openDraft();
Livewire::test('billing::index')
->assertSee('Jatka luonnosta')
->call('openDraftNow')
->assertSet('statusMessage', 'Luonnos on jo auki. Jatka sitä.');
Livewire::test('billing::export', ['export' => $exportId])
->call('add', $job->id)
->call('discard')
->assertRedirect(route('billing.index'));
expect(BillingExportModel::query()->count())->toBe(0)
->and(TimeEntryModel::query()->sole()->billing_export_id)->toBeNull()
->and($job->refresh()->status)->toBe(JobStatus::Done);
});
it('keeps billed hours approved and billed expenses unchanged', function () {
$job = doneJob([], [$this->layout->id => 1]);
$expense = ExpenseModel::factory()->create(['customer_job_id' => $job->id]);
Livewire::test('billing::export', ['export' => openDraft()])->call('add', $job->id)->call('finalize');
$job->refresh()->update(['status' => JobStatus::InProduction]);
$entry = TimeEntryModel::query()->sole();
expect(app(CancelWeekApproval::class)->execute($entry->user_id, $entry->worked_on->startOfWeek()->toDateString()))->toBe(0)
->and($entry->refresh()->approved_at)->not->toBeNull();
app(RemoveExpense::class)->execute($expense->id);
})->throws(ExpenseLocked::class);
it('keeps everyone but management out', function (string $role) {
$this->actingAs(User::factory()->{$role}()->create());
$this->get(route('billing.index'))->assertForbidden();
})->with(['employee', 'intern', 'subcontractor']);
@@ -0,0 +1,177 @@
<?php
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\Application\Services\BillingRules;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Domain\Enums\LineKind;
use App\Modules\Billing\Domain\Enums\MergeRefusal;
use App\Modules\Billing\Domain\Enums\NotBillableReason;
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\ValueObjects\DraftJob;
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
function draft(): BillingExport
{
return BillingExport::startDraft(1, new DateTimeImmutable('2026-11-24 10:00'));
}
function billableJob(int $id, BillingMode $mode = BillingMode::Hours, array $overrides = []): BillableJob
{
$values = array_merge([
'id' => $id,
'number' => '2026-000'.$id,
'name' => 'Työ '.$id,
'customerId' => 1,
'customerName' => 'Asiakas Oy',
'isConsumer' => false,
'isInternal' => false,
'hasIdentityCode' => false,
'billingUnitId' => null,
'billingUnitName' => null,
'customerReference' => null,
'mode' => $mode,
'quotedAmountCents' => null,
'isDone' => true,
], $overrides);
return new BillableJob(...$values);
}
it('combines jobs of the same customer and billing unit when at most one has a reference', function () {
$export = draft();
$export->addJob(new DraftJob(1, 10, 5, null));
$export->addJob(new DraftJob(2, 10, 5, 'PO-1'));
$export->addJob(new DraftJob(3, 10, 5, null));
$export->moveJob(2, 1);
$export->moveJob(3, 1);
expect($export->invoices())->toHaveCount(1)
->and($export->invoices()[0]->reference())->toBe('PO-1')
->and($export->jobIds())->toBe([1, 2, 3]);
$export->separate(2);
expect($export->invoices())->toHaveCount(2)
->and($export->invoiceOf(2)?->key())->toBe(2);
});
it('refuses to combine jobs that must be billed apart', function (DraftJob $other, MergeRefusal $refusal) {
$export = draft();
$export->addJob(new DraftJob(1, 10, 5, 'PO-1'));
$export->addJob($other);
try {
$export->moveJob($other->jobId, 1);
$this->fail('The jobs were combined.');
} catch (InvoicesCannotMerge $exception) {
expect($exception->refusal)->toBe($refusal)
->and($export->invoices())->toHaveCount(2);
}
})->with([
'another customer' => [new DraftJob(2, 11, 5, null), MergeRefusal::DifferentCustomer],
'another billing unit' => [new DraftJob(2, 10, null, null), MergeRefusal::DifferentBillingUnit],
'another reference' => [new DraftJob(2, 10, 5, 'PO-2'), MergeRefusal::DifferentReference],
]);
it('drops an invoice left without jobs and does not add a job twice', function () {
$export = draft();
$export->addJob(new DraftJob(1, 10, null, null));
$export->addJob(new DraftJob(2, 10, null, null));
$export->moveJob(2, 1);
$export->removeJob(1);
expect($export->invoices())->toHaveCount(1)
->and($export->invoices()[0]->key())->toBe(2);
$export->addJob(new DraftJob(2, 10, null, null));
})->throws(JobAlreadyInDraft::class);
it('parses billable hours in quarters of an hour', function (string $value, ?int $quarters) {
expect(DraftJob::parseHours($value))->toBe($quarters);
})->with([
['12,5', 50],
['0,25', 1],
['3', 12],
['0', 0],
['', null],
]);
it('rejects billable hours that are not quarters of an hour', function (string $value) {
DraftJob::parseHours($value);
})->throws(InvalidBillableHours::class)->with(['1,1', '-1', 'abc', '10000']);
it('locks the material once it is created', function () {
$export = draft();
$export->addJob(new DraftJob(1, 10, null, null));
$export->finalize([1 => [InvoiceLine::fixedPrice(1, 'Työ', 1000, 2550)]], 2, new DateTimeImmutable('2026-11-24 12:00'));
expect($export->status())->toBe(ExportStatus::Created)
->and($export->invoices()[0]->totals()->netCents)->toBe(1000);
$export->addJob(new DraftJob(2, 10, null, null));
})->throws(ExportNotDraft::class);
it('does not create an empty material', function () {
draft()->finalize([], 1, new DateTimeImmutable);
})->throws(ExportEmpty::class);
it('prices hours by the quarter and rounds half up', function () {
expect(InvoiceLine::hours(1, 2, 'Taitto', 10, 9, 8050, 2550)->netCents)->toBe(18113)
->and(InvoiceLine::hours(1, 2, 'Taitto', 1, 1, 2, 2550)->netCents)->toBe(1)
->and(InvoiceLine::hours(1, 2, 'Taitto', 1, 1, 1, 2550)->netCents)->toBe(0);
});
it('counts the VAT from each rate total', function () {
$totals = InvoiceTotals::of([
InvoiceLine::fixedPrice(1, 'A', 3333, 2550),
InvoiceLine::fixedPrice(1, 'B', 3333, 2550),
InvoiceLine::expense(1, 9, 'C', 1000, 1350),
]);
expect($totals->netCents)->toBe(7666)
->and($totals->byVatRate)->toBe([2550 => ['net' => 6666, 'vat' => 1700], 1350 => ['net' => 1000, 'vat' => 135]])
->and($totals->grossCents())->toBe(7666 + 1835);
});
it('tells why a job cannot be billed', function (BillableJob $job, JobHours $hours, array $expenses, bool $fixedBilled, ?NotBillableReason $reason) {
$rates = [1 => new HourlyRate(1, 'Taitto', 8000), 2 => new HourlyRate(2, 'Suunnittelu', null)];
expect((new BillingRules)->reasonNotBillable($job, $hours, $expenses, $fixedBilled, $rates))->toBe($reason);
})->with([
'billable hours' => [billableJob(1), new JobHours(1, [1 => 4]), [], false, null],
'not done' => [billableJob(1, overrides: ['isDone' => false]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::WrongStatus],
'billed monthly or not billable' => [billableJob(1, overrides: ['mode' => null]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::NotBillableBasis],
'internal customer' => [billableJob(1, overrides: ['isInternal' => true]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::NotBillableBasis],
'consumer without a code' => [billableJob(1, overrides: ['isConsumer' => true]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::MissingIdentityCode],
'consumer with a code' => [billableJob(1, overrides: ['isConsumer' => true, 'hasIdentityCode' => true]), new JobHours(1, [1 => 4]), [], false, null],
'work type without a rate' => [billableJob(1), new JobHours(1, [1 => 4, 2 => 1]), [], false, NotBillableReason::MissingHourlyRate],
'only unapproved hours' => [billableJob(1), new JobHours(1, [], 8), [], false, NotBillableReason::NothingToBill],
'only expenses' => [billableJob(1), new JobHours(1), [new BillableExpense(5, 1, 'Paperi', 500)], false, null],
'fixed price' => [billableJob(1, BillingMode::FixedPrice, ['quotedAmountCents' => 100000]), new JobHours(1), [], false, null],
'fixed price without a quote' => [billableJob(1, BillingMode::FixedPrice), new JobHours(1), [], false, NotBillableReason::MissingQuotedAmount],
'fixed price billed before' => [billableJob(1, BillingMode::FixedPrice, ['quotedAmountCents' => 100000]), new JobHours(1, [1 => 4]), [], true, NotBillableReason::NothingToBill],
]);
it('forms hour lines by work type name with the billable hours, then the expenses', function () {
$rates = [1 => new HourlyRate(1, 'Taitto', 8000), 2 => new HourlyRate(2, 'Kuvaus', 10000)];
$draftJob = (new DraftJob(1, 1, null, null))->withBillableQuarters(1, 6);
$lines = (new BillingRules)->lines(billableJob(1), $draftJob, [1 => 8, 2 => 2], [new BillableExpense(5, 1, 'Paperi', 500)], false, $rates, 2550);
expect(array_map(fn (InvoiceLine $line): array => [$line->kind, $line->description, $line->recordedQuarters, $line->quantityQuarters, $line->netCents], $lines))->toBe([
[LineKind::Hours, 'Kuvaus', 2, 2, 5000],
[LineKind::Hours, 'Taitto', 8, 6, 12000],
[LineKind::Expense, 'Paperi', null, null, 500],
]);
});