diff --git a/CLAUDE.md b/CLAUDE.md index dec8c26..a0bbe2b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## 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: ``, ``), 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: ``, ``), 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. - **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/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::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. -- **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. - **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`). diff --git a/app/Modules/Billing/Application/Contracts/BillingExpenses.php b/app/Modules/Billing/Application/Contracts/BillingExpenses.php new file mode 100644 index 0000000..4cb088e --- /dev/null +++ b/app/Modules/Billing/Application/Contracts/BillingExpenses.php @@ -0,0 +1,28 @@ + $jobIds + * @return array> Keyed by job id, every job included. + */ + public function forJobs(array $jobIds): array; + + /** + * Marks the job's billable, unbilled expenses billed. + * + * @return list Ids of the expenses marked. + */ + public function markBilled(int $jobId, int $billingExportId): array; +} diff --git a/app/Modules/Billing/Application/Contracts/BillingHours.php b/app/Modules/Billing/Application/Contracts/BillingHours.php new file mode 100644 index 0000000..bab3d41 --- /dev/null +++ b/app/Modules/Billing/Application/Contracts/BillingHours.php @@ -0,0 +1,26 @@ + $jobIds + * @return array Keyed by job id, every job included. + */ + public function forJobs(array $jobIds): array; + + /** + * Marks the job's approved, unbilled hours billed. + * + * @return array The quarters marked, keyed by work type id. + */ + public function markBilled(int $jobId, int $billingExportId): array; +} diff --git a/app/Modules/Billing/Application/Contracts/BillingJobs.php b/app/Modules/Billing/Application/Contracts/BillingJobs.php new file mode 100644 index 0000000..e3b1c82 --- /dev/null +++ b/app/Modules/Billing/Application/Contracts/BillingJobs.php @@ -0,0 +1,31 @@ + + */ + public function done(): array; + + /** + * @param list $jobIds + * @return array 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; +} diff --git a/app/Modules/Billing/Application/Contracts/BillingPrices.php b/app/Modules/Billing/Application/Contracts/BillingPrices.php new file mode 100644 index 0000000..12d7302 --- /dev/null +++ b/app/Modules/Billing/Application/Contracts/BillingPrices.php @@ -0,0 +1,23 @@ + 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; +} diff --git a/app/Modules/Billing/Application/Contracts/BillingQueries.php b/app/Modules/Billing/Application/Contracts/BillingQueries.php new file mode 100644 index 0000000..956906d --- /dev/null +++ b/app/Modules/Billing/Application/Contracts/BillingQueries.php @@ -0,0 +1,20 @@ + + */ + public function exports(): array; +} diff --git a/app/Modules/Billing/Application/DTOs/AvailableJob.php b/app/Modules/Billing/Application/DTOs/AvailableJob.php new file mode 100644 index 0000000..cd5b7c1 --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/AvailableJob.php @@ -0,0 +1,26 @@ + $missingRateNames + */ + public function __construct( + public BillableJob $job, + public int $approvedQuarters, + public int $unapprovedQuarters, + public int $expenseCount, + public ?NotBillableReason $reason, + public array $missingRateNames = [], + ) {} +} diff --git a/app/Modules/Billing/Application/DTOs/BillableExpense.php b/app/Modules/Billing/Application/DTOs/BillableExpense.php new file mode 100644 index 0000000..f99b380 --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/BillableExpense.php @@ -0,0 +1,18 @@ +number.' '.$this->name; + } + + public function toDraftJob(): DraftJob + { + return new DraftJob($this->id, $this->customerId, $this->billingUnitId, $this->customerReference); + } +} diff --git a/app/Modules/Billing/Application/DTOs/ExportSummary.php b/app/Modules/Billing/Application/DTOs/ExportSummary.php new file mode 100644 index 0000000..d2f0052 --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/ExportSummary.php @@ -0,0 +1,26 @@ + $invoices + * @param list $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; + } +} diff --git a/app/Modules/Billing/Application/DTOs/HourlyRate.php b/app/Modules/Billing/Application/DTOs/HourlyRate.php new file mode 100644 index 0000000..3b60085 --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/HourlyRate.php @@ -0,0 +1,17 @@ + $hours + * @param list $lines + * @param list $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; + } +} diff --git a/app/Modules/Billing/Application/DTOs/InvoiceView.php b/app/Modules/Billing/Application/DTOs/InvoiceView.php new file mode 100644 index 0000000..98ca266 --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/InvoiceView.php @@ -0,0 +1,27 @@ + $jobs + * @param array> $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 = [], + ) {} +} diff --git a/app/Modules/Billing/Application/DTOs/JobHours.php b/app/Modules/Billing/Application/DTOs/JobHours.php new file mode 100644 index 0000000..d2a723e --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/JobHours.php @@ -0,0 +1,26 @@ + $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); + } +} diff --git a/app/Modules/Billing/Application/DTOs/MergeTarget.php b/app/Modules/Billing/Application/DTOs/MergeTarget.php new file mode 100644 index 0000000..3297451 --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/MergeTarget.php @@ -0,0 +1,16 @@ + $expenses + * @param array $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 $rates + * @return list + */ + 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 $approvedByWorkType + * @param list $expenses + * @param array $rates + * @return list + */ + 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 $quarters + * @param array $rates + * @return array + */ + 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; + } +} diff --git a/app/Modules/Billing/Application/Services/BillingSnapshot.php b/app/Modules/Billing/Application/Services/BillingSnapshot.php new file mode 100644 index 0000000..dcd0e90 --- /dev/null +++ b/app/Modules/Billing/Application/Services/BillingSnapshot.php @@ -0,0 +1,106 @@ + */ + public array $jobs = []; + + /** @var array */ + public array $hours = []; + + /** @var array> */ + public array $expenses = []; + + /** @var array */ + public array $fixedPriceBilled = []; + + /** @var array */ + 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 $jobIds + * @param list $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 + */ + 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 + */ + public function missingRateNames(BillableJob $job): array + { + return $this->rules->missingRateNames($this->hoursOf($job->id), $this->rates); + } +} diff --git a/app/Modules/Billing/Application/Services/ExportViews.php b/app/Modules/Billing/Application/Services/ExportViews.php new file mode 100644 index 0000000..2244e82 --- /dev/null +++ b/app/Modules/Billing/Application/Services/ExportViews.php @@ -0,0 +1,183 @@ +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 $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 + */ + 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; + } +} diff --git a/app/Modules/Billing/Application/UseCases/AddJobToDraft.php b/app/Modules/Billing/Application/UseCases/AddJobToDraft.php new file mode 100644 index 0000000..a72e2c1 --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/AddJobToDraft.php @@ -0,0 +1,54 @@ +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()); + }); + } +} diff --git a/app/Modules/Billing/Application/UseCases/ChangesDraft.php b/app/Modules/Billing/Application/UseCases/ChangesDraft.php new file mode 100644 index 0000000..ea4de5f --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/ChangesDraft.php @@ -0,0 +1,39 @@ +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); + }); + } +} diff --git a/app/Modules/Billing/Application/UseCases/DiscardDraft.php b/app/Modules/Billing/Application/UseCases/DiscardDraft.php new file mode 100644 index 0000000..82cfdac --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/DiscardDraft.php @@ -0,0 +1,34 @@ +transactions->run(function () use ($exportId): void { + $export = $this->exports->findById($exportId, lock: true) ?? throw new BillingExportNotFound($exportId); + $export->ensureDraft(); + $this->exports->delete($export); + }); + } +} diff --git a/app/Modules/Billing/Application/UseCases/FinalizeBillingExport.php b/app/Modules/Billing/Application/UseCases/FinalizeBillingExport.php new file mode 100644 index 0000000..aa26fc4 --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/FinalizeBillingExport.php @@ -0,0 +1,85 @@ +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()); + }); + } +} diff --git a/app/Modules/Billing/Application/UseCases/MoveJobToInvoice.php b/app/Modules/Billing/Application/UseCases/MoveJobToInvoice.php new file mode 100644 index 0000000..f0442a1 --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/MoveJobToInvoice.php @@ -0,0 +1,40 @@ +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); + }); + } +} diff --git a/app/Modules/Billing/Application/UseCases/OpenBillingDraft.php b/app/Modules/Billing/Application/UseCases/OpenBillingDraft.php new file mode 100644 index 0000000..170d957 --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/OpenBillingDraft.php @@ -0,0 +1,40 @@ +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(); + }); + } +} diff --git a/app/Modules/Billing/Application/UseCases/RemoveJobFromDraft.php b/app/Modules/Billing/Application/UseCases/RemoveJobFromDraft.php new file mode 100644 index 0000000..80ab747 --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/RemoveJobFromDraft.php @@ -0,0 +1,38 @@ +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); + }); + } +} diff --git a/app/Modules/Billing/Application/UseCases/SeparateJob.php b/app/Modules/Billing/Application/UseCases/SeparateJob.php new file mode 100644 index 0000000..674279c --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/SeparateJob.php @@ -0,0 +1,38 @@ +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); + }); + } +} diff --git a/app/Modules/Billing/Application/UseCases/SetBillableHours.php b/app/Modules/Billing/Application/UseCases/SetBillableHours.php new file mode 100644 index 0000000..a23e0fb --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/SetBillableHours.php @@ -0,0 +1,46 @@ +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); + }); + } +} diff --git a/app/Modules/Billing/Domain/Contracts/BillingExportRepository.php b/app/Modules/Billing/Domain/Contracts/BillingExportRepository.php new file mode 100644 index 0000000..6459eda --- /dev/null +++ b/app/Modules/Billing/Domain/Contracts/BillingExportRepository.php @@ -0,0 +1,36 @@ + $jobIds + * @return list + */ + public function fixedPriceBilledJobIds(array $jobIds): array; +} diff --git a/app/Modules/Billing/Domain/Entities/BillingExport.php b/app/Modules/Billing/Domain/Entities/BillingExport.php new file mode 100644 index 0000000..65957ac --- /dev/null +++ b/app/Modules/Billing/Domain/Entities/BillingExport.php @@ -0,0 +1,270 @@ + $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 $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> $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 + */ + public function jobs(): array + { + return array_merge(...array_map(fn (BillingInvoice $invoice): array => $invoice->jobs(), $this->invoices)); + } + + /** + * @return list + */ + 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 + */ + 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())); + } +} diff --git a/app/Modules/Billing/Domain/Entities/BillingInvoice.php b/app/Modules/Billing/Domain/Entities/BillingInvoice.php new file mode 100644 index 0000000..7c2b8fd --- /dev/null +++ b/app/Modules/Billing/Domain/Entities/BillingInvoice.php @@ -0,0 +1,165 @@ + $jobs + * @param list $lines + */ + private function __construct( + private array $jobs, + private array $lines = [], + ) {} + + public static function for(DraftJob $job): self + { + return new self([$job]); + } + + /** + * @param list $jobs + * @param list $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 $lines + */ + public function setLines(array $lines): void + { + $this->lines = $lines; + } + + /** + * @return list + */ + public function jobs(): array + { + return $this->jobs; + } + + /** + * @return list + */ + 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); + } +} diff --git a/app/Modules/Billing/Domain/Enums/BillingMode.php b/app/Modules/Billing/Domain/Enums/BillingMode.php new file mode 100644 index 0000000..d9a4ebf --- /dev/null +++ b/app/Modules/Billing/Domain/Enums/BillingMode.php @@ -0,0 +1,15 @@ +value}."); + } +} diff --git a/app/Modules/Billing/Domain/Exceptions/JobAlreadyInDraft.php b/app/Modules/Billing/Domain/Exceptions/JobAlreadyInDraft.php new file mode 100644 index 0000000..f7c8e6d --- /dev/null +++ b/app/Modules/Billing/Domain/Exceptions/JobAlreadyInDraft.php @@ -0,0 +1,15 @@ +value}."); + } +} diff --git a/app/Modules/Billing/Domain/Exceptions/JobNotInDraft.php b/app/Modules/Billing/Domain/Exceptions/JobNotInDraft.php new file mode 100644 index 0000000..b1c135a --- /dev/null +++ b/app/Modules/Billing/Domain/Exceptions/JobNotInDraft.php @@ -0,0 +1,15 @@ + $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); + } +} diff --git a/app/Modules/Billing/Domain/ValueObjects/InvoiceLine.php b/app/Modules/Billing/Domain/ValueObjects/InvoiceLine.php new file mode 100644 index 0000000..d66ba45 --- /dev/null +++ b/app/Modules/Billing/Domain/ValueObjects/InvoiceLine.php @@ -0,0 +1,58 @@ + $byVatRate Keyed by VAT basis points, highest first. + */ + public function __construct( + public int $netCents, + public int $vatCents, + public array $byVatRate, + ) {} + + /** + * @param list $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 $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; + } +} diff --git a/app/Modules/Billing/Infrastructure/ExpensesForBilling.php b/app/Modules/Billing/Infrastructure/ExpensesForBilling.php new file mode 100644 index 0000000..6bb7222 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/ExpensesForBilling.php @@ -0,0 +1,57 @@ +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, + ]); + } +} diff --git a/app/Modules/Billing/Infrastructure/HoursForBilling.php b/app/Modules/Billing/Infrastructure/HoursForBilling.php new file mode 100644 index 0000000..a063deb --- /dev/null +++ b/app/Modules/Billing/Infrastructure/HoursForBilling.php @@ -0,0 +1,33 @@ + 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); + } +} diff --git a/app/Modules/Billing/Infrastructure/JobsForBilling.php b/app/Modules/Billing/Infrastructure/JobsForBilling.php new file mode 100644 index 0000000..a43f799 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/JobsForBilling.php @@ -0,0 +1,91 @@ +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 $jobs + * @return list + */ + private function toBillable(array $jobs): array + { + /** @var array $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); + } +} diff --git a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingExportModel.php b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingExportModel.php new file mode 100644 index 0000000..b501eb7 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingExportModel.php @@ -0,0 +1,46 @@ + + */ + public function invoices(): HasMany + { + return $this->hasMany(BillingInvoiceModel::class, 'billing_export_id')->orderBy('sort_order')->orderBy('id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'status' => ExportStatus::class, + 'created_by' => 'integer', + 'finalized_by' => 'integer', + 'finalized_at' => 'datetime', + ]; + } +} diff --git a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceJobModel.php b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceJobModel.php new file mode 100644 index 0000000..187be73 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceJobModel.php @@ -0,0 +1,50 @@ + + */ + public function hours(): HasMany + { + return $this->hasMany(BillingJobHoursModel::class, 'billing_invoice_job_id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'billing_invoice_id' => 'integer', + 'customer_job_id' => 'integer', + 'customer_id' => 'integer', + 'billing_unit_id' => 'integer', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceModel.php b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceModel.php new file mode 100644 index 0000000..1220623 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceModel.php @@ -0,0 +1,52 @@ + + */ + public function jobs(): HasMany + { + return $this->hasMany(BillingInvoiceJobModel::class, 'billing_invoice_id')->orderBy('sort_order')->orderBy('id'); + } + + /** + * @return HasMany + */ + public function lines(): HasMany + { + return $this->hasMany(BillingLineModel::class, 'billing_invoice_id')->orderBy('sort_order')->orderBy('id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'billing_export_id' => 'integer', + 'customer_id' => 'integer', + 'billing_unit_id' => 'integer', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingJobHoursModel.php b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingJobHoursModel.php new file mode 100644 index 0000000..962cf55 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingJobHoursModel.php @@ -0,0 +1,34 @@ + + */ + protected function casts(): array + { + return [ + 'billing_invoice_job_id' => 'integer', + 'work_type_id' => 'integer', + 'billable_quarters' => 'integer', + ]; + } +} diff --git a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingLineModel.php b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingLineModel.php new file mode 100644 index 0000000..58fd28d --- /dev/null +++ b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingLineModel.php @@ -0,0 +1,55 @@ + + */ + 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', + ]; + } +} diff --git a/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingExportRepository.php b/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingExportRepository.php new file mode 100644 index 0000000..08bfff4 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingExportRepository.php @@ -0,0 +1,166 @@ +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, + ); + } +} diff --git a/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingQueries.php b/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingQueries.php new file mode 100644 index 0000000..d4e012b --- /dev/null +++ b/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingQueries.php @@ -0,0 +1,56 @@ +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(); + } +} diff --git a/app/Modules/Billing/Infrastructure/PricesForBilling.php b/app/Modules/Billing/Infrastructure/PricesForBilling.php new file mode 100644 index 0000000..7ed766f --- /dev/null +++ b/app/Modules/Billing/Infrastructure/PricesForBilling.php @@ -0,0 +1,33 @@ +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; + } +} diff --git a/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php b/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php new file mode 100644 index 0000000..52b61d9 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php @@ -0,0 +1,54 @@ + + */ + 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()); + } +} diff --git a/app/Modules/Billing/Presentation/Livewire/Concerns/FormatsBilling.php b/app/Modules/Billing/Presentation/Livewire/Concerns/FormatsBilling.php new file mode 100644 index 0000000..89a6ec3 --- /dev/null +++ b/app/Modules/Billing/Presentation/Livewire/Concerns/FormatsBilling.php @@ -0,0 +1,52 @@ +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 $missingRateNames + */ + public function reasonText(NotBillableReason $reason, array $missingRateNames = []): string + { + return __('billing.reasons.'.$reason->value, ['names' => implode(', ', $missingRateNames)]); + } +} diff --git a/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php b/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php new file mode 100644 index 0000000..708d31a --- /dev/null +++ b/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php @@ -0,0 +1,605 @@ + + */ + 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 + */ + public function linesOfKind(InvoiceJobView $job, LineKind $kind): array + { + return array_values(array_filter($job->lines, fn (InvoiceLine $line): bool => $line->kind === $kind)); + } + + /** + * @return list + */ + 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 + */ + 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; + } +}; +?> + +
+ @php($export = $this->export) + +
+

{{ __('billing.export.back') }}

+

{{ __('billing.export.title', ['number' => $export->id]) }}

+

+ @if ($export->isDraft()) +

+

+ {{ __('billing.export.summary', ['invoices' => count($export->invoices), 'jobs' => $export->jobCount(), 'net' => $this->money($export->totals->netCents)]) }} +

+
+ +

{{ $statusMessage }}

+ + + @if ($export->isDraft()) + @if ($export->hasProblems()) +

+

+ @endif + +
+ @if ($export->invoices !== []) + + @endif + +
+ @endif + +
+

{{ __('billing.invoices.title') }}

+ + @if ($export->invoices === []) +

{{ __('billing.invoices.none') }}

+ @endif + + @foreach ($export->invoices as $invoiceNumber => $invoice) +
+
+

{{ __('billing.invoices.heading', ['number' => $invoiceNumber + 1, 'customer' => $invoice->customerName]) }}

+
+
{{ __('billing.invoices.billing_unit') }}
+
{{ $invoice->billingUnitName ?? __('billing.invoices.no_billing_unit') }}
+
{{ __('billing.invoices.reference') }}
+
{{ $invoice->reference ?? __('billing.invoices.no_reference') }}
+
+
+ + @foreach ($invoice->jobs as $job) +
+

+ {{ $job->label() }} +

+

{{ __('billing.jobs.mode', ['mode' => $this->modeLabel($job->mode)]) }}

+ + @if ($job->problem !== null) +

+

+ @endif + + @if ($export->isDraft() && $job->unapprovedQuarters > 0) +

+

+ @endif + + @if ($export->isDraft()) + @if ($job->mode === BillingMode::FixedPrice) + @php($fixed = $this->linesOfKind($job, LineKind::FixedPrice)) +

+ {{ $fixed === [] ? __('billing.jobs.fixed_price_billed') : __('billing.jobs.fixed_price', ['amount' => $this->money($fixed[0]->netCents)]) }} +

+ @php($approved = array_sum(array_map(fn ($row) => $row->approvedQuarters, $job->hours))) + @if ($approved > 0) +

{{ __('billing.jobs.fixed_hours', ['hours' => $this->hours($approved)]) }}

+ @endif + @elseif ($job->hours === []) +

{{ __('billing.jobs.no_hours') }}

+ @else +
+ + + + + + + + + + + + + @foreach ($job->hours as $row) + @php($fieldId = 'hours-'.$job->jobId.'-'.$row->workTypeId) + + + + + + + + @endforeach + +
{{ __('billing.jobs.hours_caption', ['job' => $job->label()]) }}
{{ __('billing.jobs.work_type') }}{{ __('billing.jobs.approved_hours') }}{{ __('billing.jobs.billable_hours') }}{{ __('billing.jobs.rate') }}{{ __('billing.jobs.net') }}
{{ $row->name }}{{ $this->hours($row->approvedQuarters) }} + 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) + ({{ __('billing.jobs.adjusted') }}) + @endif + @error('hours.'.$job->jobId.'.'.$row->workTypeId) + {{ $message }} + @enderror + {{ $row->rateCents === null ? __('billing.jobs.no_rate') : $this->money($row->rateCents) }}{{ $this->money($row->netCents) }}
+
+

{{ __('billing.jobs.billable_help') }}

+ @endif + + @php($expenseLines = $this->linesOfKind($job, LineKind::Expense)) + @if ($expenseLines !== []) + + + + + + + + + + @foreach ($expenseLines as $line) + + + + + @endforeach + +
{{ __('billing.jobs.expenses_caption', ['job' => $job->label()]) }}
{{ __('billing.jobs.expense') }}{{ __('billing.jobs.amount') }}
{{ $line->description }}{{ $this->money($line->netCents) }}
+ @endif + +
+ @if (($invoice->mergeTargets[$job->jobId] ?? []) !== []) +
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($invoice->mergeTargets[$job->jobId] as $target) + + @endforeach + +
+ + @endif + + @if (count($invoice->jobs) > 1) + + @endif + + +
+ @else +
+ + + + + + + + + + + + + @foreach ($job->lines as $index => $line) + + + + + + + + @endforeach + +
{{ __('billing.lines.caption', ['job' => $job->label()]) }}
{{ __('billing.lines.description') }}{{ __('billing.lines.recorded') }}{{ __('billing.lines.quantity') }}{{ __('billing.lines.unit_price') }}{{ __('billing.lines.net') }}
+ {{ __('billing.kinds.'.$line->kind->value) }} + {{ $line->description }} + {{ $line->recordedQuarters === null ? '' : $this->hours($line->recordedQuarters) }}{{ $line->quantityQuarters === null ? '' : $this->hours($line->quantityQuarters) }}{{ $this->money($line->unitPriceCents) }}{{ $this->money($line->netCents) }}
+
+ @endif +
+ @endforeach + + + + + + + + + @foreach ($invoice->totals->byVatRate as $basisPoints => $amounts) + + + + + @endforeach + + + + + +
{{ __('billing.invoices.totals') }}
{{ __('billing.invoices.net') }}{{ $this->money($invoice->totals->netCents) }}
{{ __('billing.invoices.vat', ['rate' => $this->vatRate($basisPoints)]) }}{{ $this->money($amounts['vat']) }}
{{ __('billing.invoices.gross') }}{{ $this->money($invoice->totals->grossCents()) }}
+
+ @endforeach + + @if (count($export->invoices) > 1) + + + + + + + + + + + + +
{{ __('billing.invoices.export_totals') }}
{{ __('billing.invoices.net') }}{{ $this->money($export->totals->netCents) }}
{{ __('billing.invoices.gross') }}{{ $this->money($export->totals->grossCents()) }}
+ @endif +
+ + @if ($export->isDraft()) +
+

{{ __('billing.available.title') }}

+

{{ __('billing.available.intro') }}

+ + @if ($export->availableJobs === []) +

{{ __('billing.available.none') }}

+ @else + + @interact('column_job', $available) + {{ $available->job->label() }} + @endinteract + + @interact('column_customer', $available) + {{ $available->job->customerName }} + @endinteract + + @interact('column_mode', $available) + {{ $this->modeLabel($available->job->mode) }} + @endinteract + + @interact('column_hours', $available) + {{ $this->hours($available->approvedQuarters) }} + @if ($available->unapprovedQuarters > 0) + {{ __('billing.available.unapproved', ['hours' => $this->hours($available->unapprovedQuarters)]) }} + @endif + @endinteract + + @interact('column_expenses', $available) + {{ $available->expenseCount }} + @endinteract + + @interact('column_actions', $available) + @if ($available->reason === null) + + @else + + + @endif + @endinteract + + @endif +
+ + +

{{ __('billing.export.finalize_text', ['invoices' => count($export->invoices), 'net' => $this->money($export->totals->netCents)]) }}

+ + + + +
+ + +

{{ __('billing.export.discard_text') }}

+ + + + +
+ @endif +
diff --git a/app/Modules/Billing/Presentation/Livewire/⚡index.blade.php b/app/Modules/Billing/Presentation/Livewire/⚡index.blade.php new file mode 100644 index 0000000..1cc89a0 --- /dev/null +++ b/app/Modules/Billing/Presentation/Livewire/⚡index.blade.php @@ -0,0 +1,143 @@ +authorize('billing.manage'); + $this->statusMessage = (string) session('billing-status', ''); + } + + /** + * @return list + */ + #[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 + */ + 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')); + } +}; +?> + +
+
+

{{ __('billing.index.title') }}

+

{{ __('billing.index.intro') }}

+
+ +

+ @if ($this->openDraft !== null) + + @else + + @endif +

+ +

{{ $statusMessage }}

+ + @if ($this->exports === []) +

{{ __('billing.index.none') }}

+ @else + + @interact('column_number', $export) + {{ __('billing.index.export_label', ['number' => $export->id]) }} + @endinteract + + @interact('column_status', $export) + + + @endinteract + + @interact('column_created', $export) + {{ $this->timeLabel($export->createdAt) }} + {{ $export->createdByName }} + @endinteract + + @interact('column_finalized', $export) + @if ($export->finalizedAt !== null) + {{ $this->timeLabel($export->finalizedAt) }} + {{ $export->finalizedByName }} + @endif + @endinteract + + @interact('column_invoices', $export) + {{ $export->invoiceCount }} + @endinteract + + @interact('column_jobs', $export) + {{ $export->jobCount }} + @endinteract + + @interact('column_net', $export) + {{ $export->netCents === null ? '' : $this->money($export->netCents) }} + @endinteract + + @endif +
diff --git a/app/Modules/Billing/Presentation/Routes/web.php b/app/Modules/Billing/Presentation/Routes/web.php new file mode 100644 index 0000000..bf15e1e --- /dev/null +++ b/app/Modules/Billing/Presentation/Routes/web.php @@ -0,0 +1,11 @@ +prefix('billing') + ->name('billing.') + ->group(function () { + Route::livewire('/', 'billing::index')->name('index'); + Route::livewire('/{export}', 'billing::export')->whereNumber('export')->name('export'); + }); diff --git a/app/Modules/Expenses/Application/Contracts/ExpenseQueries.php b/app/Modules/Expenses/Application/Contracts/ExpenseQueries.php index e13e133..13fc519 100644 --- a/app/Modules/Expenses/Application/Contracts/ExpenseQueries.php +++ b/app/Modules/Expenses/Application/Contracts/ExpenseQueries.php @@ -25,4 +25,12 @@ interface ExpenseQueries public function forUserInMonth(int $userId, string $month): array; public function find(int $id): ?ExpenseSummary; + + /** + * The jobs' billable expenses that are not billed yet, oldest first. + * + * @param list $jobIds + * @return list + */ + public function unbilledBillable(array $jobIds): array; } diff --git a/app/Modules/Expenses/Application/UseCases/MarkJobExpensesBilled.php b/app/Modules/Expenses/Application/UseCases/MarkJobExpensesBilled.php new file mode 100644 index 0000000..8802d29 --- /dev/null +++ b/app/Modules/Expenses/Application/UseCases/MarkJobExpensesBilled.php @@ -0,0 +1,29 @@ + 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)); + } +} diff --git a/app/Modules/Expenses/Application/UseCases/RemoveExpense.php b/app/Modules/Expenses/Application/UseCases/RemoveExpense.php index 638e639..677491a 100644 --- a/app/Modules/Expenses/Application/UseCases/RemoveExpense.php +++ b/app/Modules/Expenses/Application/UseCases/RemoveExpense.php @@ -30,7 +30,7 @@ final class RemoveExpense $this->transactions->run(function () use ($expenseId): void { $expense = $this->expenses->findById($expenseId) ?? throw new ExpenseNotFound($expenseId); - if ($this->jobs->find($expense->jobId())->isLocked ?? true) { + if ($expense->isBilled() || ($this->jobs->find($expense->jobId())->isLocked ?? true)) { throw new ExpenseLocked; } diff --git a/app/Modules/Expenses/Application/UseCases/UpdateExpense.php b/app/Modules/Expenses/Application/UseCases/UpdateExpense.php index 01365c7..5d7522d 100644 --- a/app/Modules/Expenses/Application/UseCases/UpdateExpense.php +++ b/app/Modules/Expenses/Application/UseCases/UpdateExpense.php @@ -36,7 +36,7 @@ final class UpdateExpense $this->transactions->run(function () use ($expenseId, $data, $details): void { $expense = $this->expenses->findById($expenseId) ?? throw new ExpenseNotFound($expenseId); - if ($this->jobs->find($expense->jobId())->isLocked ?? true) { + if ($expense->isBilled() || ($this->jobs->find($expense->jobId())->isLocked ?? true)) { throw new ExpenseLocked; } diff --git a/app/Modules/Expenses/Domain/Contracts/ExpenseRepository.php b/app/Modules/Expenses/Domain/Contracts/ExpenseRepository.php index d9dd7fe..0794fe1 100644 --- a/app/Modules/Expenses/Domain/Contracts/ExpenseRepository.php +++ b/app/Modules/Expenses/Domain/Contracts/ExpenseRepository.php @@ -16,4 +16,11 @@ interface ExpenseRepository public function save(Expense $expense): Expense; public function delete(Expense $expense): void; + + /** + * Marks the job's billable, unbilled expenses billed on a billing material. + * + * @return list Ids of the expenses marked. + */ + public function markBillableAsBilled(int $jobId, int $billingExportId): array; } diff --git a/app/Modules/Expenses/Domain/Entities/Expense.php b/app/Modules/Expenses/Domain/Entities/Expense.php index 1a08100..1f850f9 100644 --- a/app/Modules/Expenses/Domain/Entities/Expense.php +++ b/app/Modules/Expenses/Domain/Entities/Expense.php @@ -8,7 +8,8 @@ use App\Modules\Expenses\Domain\ValueObjects\ExpenseDetails; /** * An expense on a customer job: whose it is, who recorded it (management - * records subcontractors' expenses) and what it is. + * records subcontractors' expenses) and what it is. A billed expense (on a + * billing material) can no longer be changed or removed. */ final class Expense { @@ -18,6 +19,7 @@ final class Expense private int $userId, private int $recordedBy, private ExpenseDetails $details, + private ?int $billingExportId = null, ) {} public static function record(int $jobId, int $userId, int $recordedBy, ExpenseDetails $details): self @@ -25,9 +27,19 @@ final class Expense return new self(null, $jobId, $userId, $recordedBy, $details); } - public static function reconstitute(int $id, int $jobId, int $userId, int $recordedBy, ExpenseDetails $details): self + public static function reconstitute(int $id, int $jobId, int $userId, int $recordedBy, ExpenseDetails $details, ?int $billingExportId = null): self { - return new self($id, $jobId, $userId, $recordedBy, $details); + return new self($id, $jobId, $userId, $recordedBy, $details, $billingExportId); + } + + public function isBilled(): bool + { + return $this->billingExportId !== null; + } + + public function billingExportId(): ?int + { + return $this->billingExportId; } public function change(int $userId, ExpenseDetails $details): void diff --git a/app/Modules/Expenses/Infrastructure/Persistence/Eloquent/ExpenseModel.php b/app/Modules/Expenses/Infrastructure/Persistence/Eloquent/ExpenseModel.php index 1d10d74..fbe9af3 100644 --- a/app/Modules/Expenses/Infrastructure/Persistence/Eloquent/ExpenseModel.php +++ b/app/Modules/Expenses/Infrastructure/Persistence/Eloquent/ExpenseModel.php @@ -30,6 +30,7 @@ use Illuminate\Support\Carbon; * @property bool $is_billable * @property int|null $markup_basis_points * @property int|null $billed_amount_cents + * @property int|null $billing_export_id */ #[Table('expenses')] #[Fillable([ diff --git a/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseQueries.php b/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseQueries.php index cd2602d..1c37186 100644 --- a/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseQueries.php +++ b/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseQueries.php @@ -42,6 +42,19 @@ class EloquentExpenseQueries implements ExpenseQueries return $this->summaries(ExpenseModel::query()->whereKey($id))[0] ?? null; } + public function unbilledBillable(array $jobIds): array + { + if ($jobIds === []) { + return []; + } + + return array_reverse($this->summaries(ExpenseModel::query() + ->whereIn('customer_job_id', $jobIds) + ->where('is_billable', true) + ->whereNotNull('billed_amount_cents') + ->whereNull('billing_export_id'))); + } + /** * @param Builder $query * @return list diff --git a/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseRepository.php b/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseRepository.php index 4105a90..6a07c9d 100644 --- a/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseRepository.php +++ b/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseRepository.php @@ -51,6 +51,24 @@ class EloquentExpenseRepository implements ExpenseRepository ExpenseModel::query()->whereKey($expense->id())->delete(); } + public function markBillableAsBilled(int $jobId, int $billingExportId): array + { + $ids = ExpenseModel::query() + ->where('customer_job_id', $jobId) + ->where('is_billable', true) + ->whereNotNull('billed_amount_cents') + ->whereNull('billing_export_id') + ->orderBy('spent_on') + ->orderBy('id') + ->pluck('id') + ->map(fn ($id): int => (int) $id) + ->all(); + + ExpenseModel::query()->whereKey($ids)->update(['billing_export_id' => $billingExportId]); + + return $ids; + } + private function toEntity(ExpenseModel $model): Expense { $billing = $model->is_billable && $model->billed_amount_cents !== null @@ -77,6 +95,7 @@ class EloquentExpenseRepository implements ExpenseRepository $model->purpose, $billing, ), + $model->billing_export_id, ); } } diff --git a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php index 2a0f1b1..91727f0 100644 --- a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php +++ b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php @@ -6,8 +6,10 @@ namespace App\Modules\Jobs\Application\Contracts; use App\Modules\Jobs\Application\DTOs\CustomerJobDetails; use App\Modules\Jobs\Application\DTOs\CustomerJobSummary; +use App\Modules\Jobs\Application\DTOs\JobBillingInfo; use App\Modules\Jobs\Application\DTOs\JobChangeEntry; use App\Modules\Jobs\Application\DTOs\JobListFilter; +use App\Modules\Jobs\Domain\Enums\JobStatus; use Illuminate\Contracts\Pagination\LengthAwarePaginator; /** @@ -41,6 +43,21 @@ interface CustomerJobQueries */ public function summariesByIds(array $ids): array; + /** + * Billing details of the jobs in a status, by job number. + * + * @return list + */ + public function billingInfoWithStatus(JobStatus $status): array; + + /** + * Billing details of the given jobs, keyed by id; unknown ids are left out. + * + * @param list $ids + * @return array + */ + public function billingInfoOf(array $ids): array; + /** * The job's history, newest first. * diff --git a/app/Modules/Jobs/Application/DTOs/JobBillingInfo.php b/app/Modules/Jobs/Application/DTOs/JobBillingInfo.php new file mode 100644 index 0000000..8f2c6ea --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/JobBillingInfo.php @@ -0,0 +1,29 @@ +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 $models + * @return array + */ + private function billingInfo(Collection $models): array + { + $customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all()); + $billingUnitNames = []; + $result = []; + + foreach ($models as $model) { + if ($model->billing_unit_id !== null && ! isset($billingUnitNames[$model->customer_id])) { + $billingUnitNames[$model->customer_id] = []; + foreach ($this->customers->billingUnitsOf($model->customer_id) as $unit) { + $billingUnitNames[$model->customer_id][$unit->id] = $unit->name; + } + } + + $result[$model->id] = new JobBillingInfo( + $model->id, + $model->number, + $model->name, + $model->customer_id, + $customerNames[$model->customer_id] ?? '', + $model->status, + $model->payment_basis, + $model->quoted_amount_cents, + $model->customer_reference, + $model->billing_unit_id, + $model->billing_unit_id === null ? null : ($billingUnitNames[$model->customer_id][$model->billing_unit_id] ?? null), + ); + } + + return $result; + } + public function changes(int $jobId): array { $rows = DB::table('customer_job_changes')->where('customer_job_id', $jobId)->orderByDesc('id')->get(); diff --git a/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php b/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php index db4b326..8ac8cf3 100644 --- a/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php +++ b/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Modules\TimeTracking\Application\Contracts; use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek; +use App\Modules\TimeTracking\Application\DTOs\JobBillingHours; use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary; use App\Modules\TimeTracking\Application\DTOs\WeekSheet; @@ -41,4 +42,14 @@ interface TimeEntryQueries * @return list */ 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 $jobIds + * @return array + */ + public function billingHours(array $jobIds): array; } diff --git a/app/Modules/TimeTracking/Application/DTOs/JobBillingHours.php b/app/Modules/TimeTracking/Application/DTOs/JobBillingHours.php new file mode 100644 index 0000000..e6c4a02 --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/JobBillingHours.php @@ -0,0 +1,21 @@ + $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, + ) {} +} diff --git a/app/Modules/TimeTracking/Application/UseCases/CancelWeekApproval.php b/app/Modules/TimeTracking/Application/UseCases/CancelWeekApproval.php index 4803bd7..3eb4bee 100644 --- a/app/Modules/TimeTracking/Application/UseCases/CancelWeekApproval.php +++ b/app/Modules/TimeTracking/Application/UseCases/CancelWeekApproval.php @@ -10,7 +10,8 @@ use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository; /** * Cancels the approval of a user's week so the hours can be corrected. - * Only management may do this; the caller checks it. + * Billed hours keep their approval. Only management may do this; the + * caller checks it. */ final class CancelWeekApproval { @@ -31,7 +32,7 @@ final class CancelWeekApproval $cancelled = 0; foreach ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) { - if (! $entry->isApproved()) { + if (! $entry->isApproved() || $entry->isBilled()) { continue; } diff --git a/app/Modules/TimeTracking/Application/UseCases/MarkJobHoursBilled.php b/app/Modules/TimeTracking/Application/UseCases/MarkJobHoursBilled.php new file mode 100644 index 0000000..d278faf --- /dev/null +++ b/app/Modules/TimeTracking/Application/UseCases/MarkJobHoursBilled.php @@ -0,0 +1,39 @@ + 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; + }); + } +} diff --git a/app/Modules/TimeTracking/Domain/Contracts/TimeEntryRepository.php b/app/Modules/TimeTracking/Domain/Contracts/TimeEntryRepository.php index 226c890..533c900 100644 --- a/app/Modules/TimeTracking/Domain/Contracts/TimeEntryRepository.php +++ b/app/Modules/TimeTracking/Domain/Contracts/TimeEntryRepository.php @@ -27,6 +27,13 @@ interface TimeEntryRepository public function delete(TimeEntry $entry): void; + /** + * The job's approved entries that are not billed yet. + * + * @return list + */ + public function approvedUnbilledForJob(int $jobId): array; + /** * The user's recorded quarters of an hour on the day, all tasks. */ diff --git a/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php b/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php index 78d6cec..a7a185a 100644 --- a/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php +++ b/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php @@ -11,7 +11,8 @@ use DateTimeImmutable; /** * A user's hours on one task on one day (one entry per day). The job and * work type are copied from the task when the entry is made, for billing. - * Approved hours are locked until management cancels the approval. + * Approved hours are locked until management cancels the approval; billed + * hours (on a billing material) stay approved for good. */ final class TimeEntry { @@ -26,6 +27,7 @@ final class TimeEntry private ?string $note, private ?int $approvedBy = null, private ?DateTimeImmutable $approvedAt = null, + private ?int $billingExportId = null, ) {} public static function create(int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note = null): self @@ -33,9 +35,9 @@ final class TimeEntry return new self(null, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, self::text($note)); } - public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null): self + public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null, ?int $billingExportId = null): self { - return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt); + return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt, $billingExportId); } /** @@ -75,12 +77,39 @@ final class TimeEntry $this->approvedAt = $approvedAt; } + /** + * Cancels the approval, unless the hours are billed. + */ public function cancelApproval(): void { + if ($this->isBilled()) { + return; + } + $this->approvedBy = null; $this->approvedAt = null; } + /** + * Marks approved hours billed on the given billing material. + */ + public function markBilled(int $billingExportId): void + { + if ($this->isApproved() && ! $this->isBilled()) { + $this->billingExportId = $billingExportId; + } + } + + public function isBilled(): bool + { + return $this->billingExportId !== null; + } + + public function billingExportId(): ?int + { + return $this->billingExportId; + } + public function isApproved(): bool { return $this->approvedAt !== null; diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Eloquent/TimeEntryModel.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Eloquent/TimeEntryModel.php index 7b88efc..6b83d0b 100644 --- a/app/Modules/TimeTracking/Infrastructure/Persistence/Eloquent/TimeEntryModel.php +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Eloquent/TimeEntryModel.php @@ -21,9 +21,10 @@ use Illuminate\Database\Eloquent\Model; * @property string|null $note * @property CarbonImmutable|null $approved_at * @property int|null $approved_by + * @property int|null $billing_export_id */ #[Table('time_entries')] -#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by'])] +#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by', 'billing_export_id'])] #[UseFactory(TimeEntryFactory::class)] class TimeEntryModel extends Model { @@ -43,6 +44,7 @@ class TimeEntryModel extends Model 'worked_on' => 'immutable_date', 'approved_at' => 'immutable_datetime', 'approved_by' => 'integer', + 'billing_export_id' => 'integer', ]; } diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php index fd9a2b0..7f3a852 100644 --- a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php @@ -5,6 +5,7 @@ namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories; use App\Modules\Jobs\Application\Contracts\TaskQueries; use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries; use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek; +use App\Modules\TimeTracking\Application\DTOs\JobBillingHours; use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary; use App\Modules\TimeTracking\Application\DTOs\WeekApproval; use App\Modules\TimeTracking\Application\DTOs\WeekRow; @@ -68,6 +69,34 @@ class EloquentTimeEntryQueries implements TimeEntryQueries return new WeekSheet($days, $rows, $dayTotals, array_sum($dayTotals), (int) $unapproved, $this->latestApproval($entries)); } + public function billingHours(array $jobIds): array + { + $approved = array_fill_keys($jobIds, []); + $unapproved = array_fill_keys($jobIds, 0); + + if ($jobIds !== []) { + $entries = TimeEntryModel::query() + ->whereIn('customer_job_id', $jobIds) + ->whereNull('billing_export_id') + ->get(['customer_job_id', 'work_type_id', 'hours', 'approved_at']); + + foreach ($entries as $entry) { + if ($entry->approved_at === null) { + $unapproved[$entry->customer_job_id] += $entry->quarters(); + } else { + $approved[$entry->customer_job_id][$entry->work_type_id] = ($approved[$entry->customer_job_id][$entry->work_type_id] ?? 0) + $entry->quarters(); + } + } + } + + $result = []; + foreach ($jobIds as $jobId) { + $result[$jobId] = new JobBillingHours($jobId, $approved[$jobId], $unapproved[$jobId]); + } + + return $result; + } + public function entriesForTask(int $taskId, int $userId): array { return TimeEntryModel::query() diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php index f7d5274..e3393e0 100644 --- a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php @@ -42,6 +42,7 @@ class EloquentTimeEntryRepository implements TimeEntryRepository 'note' => $entry->note(), 'approved_by' => $entry->approvedBy(), 'approved_at' => $entry->approvedAt()?->format('Y-m-d H:i:s'), + 'billing_export_id' => $entry->billingExportId(), ])->save(); return $this->toEntity($model->refresh()); @@ -64,6 +65,20 @@ class EloquentTimeEntryRepository implements TimeEntryRepository TimeEntryModel::query()->whereKey($entry->id())->delete(); } + public function approvedUnbilledForJob(int $jobId): array + { + return TimeEntryModel::query() + ->where('customer_job_id', $jobId) + ->whereNotNull('approved_at') + ->whereNull('billing_export_id') + ->orderBy('worked_on') + ->orderBy('id') + ->get() + ->map(fn (TimeEntryModel $model): TimeEntry => $this->toEntity($model)) + ->values() + ->all(); + } + public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int { return (int) round((float) TimeEntryModel::query() @@ -86,6 +101,7 @@ class EloquentTimeEntryRepository implements TimeEntryRepository $model->note, $model->approved_by, $model->approved_at === null ? null : DateTimeImmutable::createFromInterface($model->approved_at), + $model->billing_export_id, ); } } diff --git a/bootstrap/providers.php b/bootstrap/providers.php index 5d3d6eb..98eaae4 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -1,5 +1,6 @@ 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'); + } +}; diff --git a/database/migrations/2026_11_24_104540_add_billing_export_to_time_entries_and_expenses.php b/database/migrations/2026_11_24_104540_add_billing_export_to_time_entries_and_expenses.php new file mode 100644 index 0000000..578cad3 --- /dev/null +++ b/database/migrations/2026_11_24_104540_add_billing_export_to_time_entries_and_expenses.php @@ -0,0 +1,34 @@ +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'); + }); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index d3cf9eb..d6cd784 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -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. - 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. +- 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)* @@ -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` **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` *(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)* - `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` - `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_exports`: `period` (kuukausi), `created_by`, `file_path` -- `invoices`: `billing_export_id`, `customer_id`, `billing_unit_id`, `customer_reference` (laskun töiden yhteinen PO-viite, jos on) -- `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_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** *(V2, olemassa)* +- `billing_exports`: `status` (`draft`/`created`; luonnoksia yksi kerrallaan), `created_by`, `finalized_by`, `finalized_at` (vientitiedosto lisätään Fennoa-viennin osassa) +- `billing_invoices`: `billing_export_id`, `customer_id`, `billing_unit_id`, `customer_reference` (laskun töiden yhteinen PO-viite, jos on), `sort_order` +- `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_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 @@ -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ä. - 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 1. ~~**Lukitus**~~: ratkaistu – vain johto avaa valmiin työn lukituksen siirtämällä työn aiempaan tilaan, ja avaus näkyy muutoshistoriassa (5.3). diff --git a/lang/fi/billing.php b/lang/fi/billing.php new file mode 100644 index 0000000..3f982b6 --- /dev/null +++ b/lang/fi/billing.php @@ -0,0 +1,163 @@ + ':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.', + ], +]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index 183bdd8..b907f74 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -11,6 +11,7 @@ return [ 'approvals' => 'Hyväksyntä', 'expenses' => 'Kulut', 'quick_sale' => 'Pikamyynti', + 'billing' => 'Laskutus', 'customers' => 'Asiakkaat', 'users' => 'Käyttäjät', 'company' => 'Yritystiedot', diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 2edf3c9..e9f536c 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -75,6 +75,10 @@ @include('partials.nav-item', ['route' => 'time.approvals', 'pattern' => 'time.approvals', 'label' => __('layout.approvals')]) @endcan + @can('billing.manage') + @include('partials.nav-item', ['route' => 'billing.index', 'pattern' => 'billing.*', 'label' => __('layout.billing')]) + @endcan + @can('customers.use') @include('partials.nav-item', ['route' => 'customers.index', 'pattern' => 'customers.*', 'label' => __('layout.customers')]) @endcan diff --git a/tests/Browser/BillingAccessibilityTest.php b/tests/Browser/BillingAccessibilityTest.php new file mode 100644 index 0000000..028ef18 --- /dev/null +++ b/tests/Browser/BillingAccessibilityTest.php @@ -0,0 +1,78 @@ +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); +}); diff --git a/tests/Fakes/InMemoryExpenseRepository.php b/tests/Fakes/InMemoryExpenseRepository.php index 5c6e8ee..0f92abe 100644 --- a/tests/Fakes/InMemoryExpenseRepository.php +++ b/tests/Fakes/InMemoryExpenseRepository.php @@ -20,7 +20,7 @@ class InMemoryExpenseRepository implements ExpenseRepository public function save(Expense $expense): Expense { $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]; } @@ -29,4 +29,18 @@ class InMemoryExpenseRepository implements ExpenseRepository { 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; + } } diff --git a/tests/Fakes/InMemoryTimeEntryRepository.php b/tests/Fakes/InMemoryTimeEntryRepository.php index cf7a228..94b4259 100644 --- a/tests/Fakes/InMemoryTimeEntryRepository.php +++ b/tests/Fakes/InMemoryTimeEntryRepository.php @@ -34,7 +34,7 @@ class InMemoryTimeEntryRepository implements TimeEntryRepository public function save(TimeEntry $entry): TimeEntry { $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]; } @@ -53,6 +53,13 @@ class InMemoryTimeEntryRepository implements TimeEntryRepository 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 { $quarters = 0; diff --git a/tests/Feature/Modules/Billing/BillingExportTest.php b/tests/Feature/Modules/Billing/BillingExportTest.php new file mode 100644 index 0000000..d4f8c8a --- /dev/null +++ b/tests/Feature/Modules/Billing/BillingExportTest.php @@ -0,0 +1,227 @@ +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 $attributes + * @param array $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']); diff --git a/tests/Unit/Modules/Billing/BillingDraftTest.php b/tests/Unit/Modules/Billing/BillingDraftTest.php new file mode 100644 index 0000000..5037b8d --- /dev/null +++ b/tests/Unit/Modules/Billing/BillingDraftTest.php @@ -0,0 +1,177 @@ + $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], + ]); +});