From 5f9423a3c362704ed5e24224ee5dfd027844ba04 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Tue, 24 Nov 2026 13:23:46 +0200 Subject: [PATCH] Add monthly fee billing lines to the billing material Jobs billed by a fixed monthly fee get a monthly fee field, kept behind the quotes permission like the quoted amount. A billing material now has a billing month: a new draft adds every monthly fee job with something to bill, each on an invoice of its own, and bills one line for every unbilled month from the job's start up to the billing month (or its end or completion), so skipped months are caught up and no month is billed twice. Their expenses are billed alongside, their hours are covered by the fee and marked billed, and the job keeps running. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- .../Application/Contracts/BillingJobs.php | 12 +++- .../Billing/Application/DTOs/BillableJob.php | 11 ++- .../Billing/Application/DTOs/ExportView.php | 6 +- .../Application/Services/BillingRules.php | 33 +++++++-- .../Application/Services/BillingSnapshot.php | 48 +++++++++++-- .../Application/Services/ExportViews.php | 9 +-- .../Application/UseCases/AddJobToDraft.php | 5 +- .../UseCases/FinalizeBillingExport.php | 13 ++-- .../Application/UseCases/OpenBillingDraft.php | 22 +++++- .../Application/UseCases/SetBillingPeriod.php | 38 ++++++++++ .../Contracts/BillingExportRepository.php | 8 +++ .../Billing/Domain/Entities/BillingExport.php | 29 +++++++- .../Domain/Entities/BillingInvoice.php | 4 ++ .../Billing/Domain/Enums/BillingMode.php | 6 +- app/Modules/Billing/Domain/Enums/LineKind.php | 1 + .../Billing/Domain/Enums/MergeRefusal.php | 3 + .../Domain/Enums/NotBillableReason.php | 9 ++- .../Exceptions/InvalidBillingPeriod.php | 15 ++++ .../Domain/ValueObjects/BillingMonths.php | 70 ++++++++++++++++++ .../Billing/Domain/ValueObjects/DraftJob.php | 4 +- .../Domain/ValueObjects/InvoiceLine.php | 11 ++- .../Billing/Infrastructure/JobsForBilling.php | 37 +++++++--- .../Eloquent/BillingExportModel.php | 3 +- .../Eloquent/BillingInvoiceJobModel.php | 4 +- .../Persistence/Eloquent/BillingLineModel.php | 3 +- .../EloquentBillingExportRepository.php | 21 ++++++ .../Presentation/Livewire/⚡export.blade.php | 71 ++++++++++++++++++- .../Contracts/CustomerJobQueries.php | 8 +++ .../Jobs/Application/DTOs/CustomerJobData.php | 1 + .../Application/DTOs/CustomerJobDetails.php | 1 + .../Jobs/Application/DTOs/JobBillingInfo.php | 8 ++- .../Services/JobDetailsFactory.php | 14 ++++ .../Domain/Exceptions/InvalidMonthlyFee.php | 15 ++++ .../Jobs/Domain/ValueObjects/JobDetails.php | 6 +- .../Persistence/Eloquent/CustomerJobModel.php | 4 +- .../EloquentCustomerJobQueries.php | 17 +++++ .../EloquentCustomerJobRepository.php | 2 + .../Presentation/Livewire/Forms/JobForm.php | 8 +++ .../Presentation/Livewire/⚡form.blade.php | 12 +++- .../Presentation/Livewire/⚡show.blade.php | 9 ++- .../2026_11_24_111257_add_monthly_billing.php | 54 ++++++++++++++ docs/maarittely.md | 20 ++++-- lang/fi/billing.php | 24 +++++-- lang/fi/jobs.php | 3 + tests/Browser/BillingAccessibilityTest.php | 21 ++++-- .../Modules/Billing/BillingExportTest.php | 70 ++++++++++++++++++ .../Modules/Jobs/JobMoneyFieldsTest.php | 29 ++++++++ .../Unit/Modules/Billing/BillingDraftTest.php | 57 ++++++++++++++- 49 files changed, 799 insertions(+), 82 deletions(-) create mode 100644 app/Modules/Billing/Application/UseCases/SetBillingPeriod.php create mode 100644 app/Modules/Billing/Domain/Exceptions/InvalidBillingPeriod.php create mode 100644 app/Modules/Billing/Domain/ValueObjects/BillingMonths.php create mode 100644 app/Modules/Jobs/Domain/Exceptions/InvalidMonthlyFee.php create mode 100644 database/migrations/2026_11_24_111257_add_monthly_billing.php diff --git a/CLAUDE.md b/CLAUDE.md index a0bbe2b..eface27 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) `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). +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 and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), 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. diff --git a/app/Modules/Billing/Application/Contracts/BillingJobs.php b/app/Modules/Billing/Application/Contracts/BillingJobs.php index e3b1c82..185d652 100644 --- a/app/Modules/Billing/Application/Contracts/BillingJobs.php +++ b/app/Modules/Billing/Application/Contracts/BillingJobs.php @@ -12,11 +12,19 @@ use App\Modules\Billing\Application\DTOs\BillableJob; interface BillingJobs { /** - * Done jobs, by job number. + * Jobs that may go on a material: done jobs, and monthly fee jobs that + * are running or done, by job number. * * @return list */ - public function done(): array; + public function candidates(): array; + + /** + * Monthly fee jobs that are running or done, by job number. + * + * @return list + */ + public function monthly(): array; /** * @param list $jobIds diff --git a/app/Modules/Billing/Application/DTOs/BillableJob.php b/app/Modules/Billing/Application/DTOs/BillableJob.php index 7ce71a3..b55adc6 100644 --- a/app/Modules/Billing/Application/DTOs/BillableJob.php +++ b/app/Modules/Billing/Application/DTOs/BillableJob.php @@ -9,7 +9,9 @@ use App\Modules\Billing\Domain\ValueObjects\DraftJob; /** * A customer job as billing sees it. A null mode means the job is not - * billed this way (not billable, or billed monthly). + * billed on a material. A monthly fee job runs from $billingStartsOn + * (its start or creation day) to $billingEndsOn (its last day or the day + * it was done), if that is set. */ final readonly class BillableJob { @@ -27,7 +29,10 @@ final readonly class BillableJob public ?string $customerReference, public ?BillingMode $mode, public ?int $quotedAmountCents, - public bool $isDone, + public bool $inBillableStatus, + public ?int $monthlyFeeCents = null, + public string $billingStartsOn = '', + public ?string $billingEndsOn = null, ) {} /** @@ -40,6 +45,6 @@ final readonly class BillableJob public function toDraftJob(): DraftJob { - return new DraftJob($this->id, $this->customerId, $this->billingUnitId, $this->customerReference); + return new DraftJob($this->id, $this->customerId, $this->billingUnitId, $this->customerReference, [], $this->mode === BillingMode::MonthlyFee); } } diff --git a/app/Modules/Billing/Application/DTOs/ExportView.php b/app/Modules/Billing/Application/DTOs/ExportView.php index 9a347d0..e672455 100644 --- a/app/Modules/Billing/Application/DTOs/ExportView.php +++ b/app/Modules/Billing/Application/DTOs/ExportView.php @@ -9,8 +9,9 @@ use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals; use DateTimeImmutable; /** - * A billing material for its page: a draft with its preview and the done - * jobs that may be added, or a created material with its lines. + * A billing material for its page: a draft with its preview and the jobs + * that may be added, or a created material with its lines. The period + * (Y-m) is the month monthly fees are billed up to. */ final readonly class ExportView { @@ -21,6 +22,7 @@ final readonly class ExportView public function __construct( public int $id, public ExportStatus $status, + public string $period, public DateTimeImmutable $createdAt, public string $createdByName, public ?DateTimeImmutable $finalizedAt, diff --git a/app/Modules/Billing/Application/Services/BillingRules.php b/app/Modules/Billing/Application/Services/BillingRules.php index f6d2c1e..6de083e 100644 --- a/app/Modules/Billing/Application/Services/BillingRules.php +++ b/app/Modules/Billing/Application/Services/BillingRules.php @@ -10,23 +10,26 @@ use App\Modules\Billing\Application\DTOs\HourlyRate; use App\Modules\Billing\Application\DTOs\JobHours; use App\Modules\Billing\Domain\Enums\BillingMode; use App\Modules\Billing\Domain\Enums\NotBillableReason; +use App\Modules\Billing\Domain\ValueObjects\BillingMonths; use App\Modules\Billing\Domain\ValueObjects\DraftJob; use App\Modules\Billing\Domain\ValueObjects\InvoiceLine; /** * What a job may bill and its invoice lines (spec 12): hours per work type - * at the hourly rates, or the quoted fixed price once, and the billable - * expenses separately. Only approved hours are billed. + * at the hourly rates, the quoted fixed price once, or the monthly fee of + * every unbilled month (spec 5.5), and the billable expenses separately. + * Only approved hours are billed; a fixed price or a monthly fee covers them. */ final class BillingRules { /** * @param list $expenses * @param array $rates + * @param list $unbilledMonths For a monthly fee job, as Y-m. */ - public function reasonNotBillable(BillableJob $job, JobHours $hours, array $expenses, bool $fixedPriceBilled, array $rates): ?NotBillableReason + public function reasonNotBillable(BillableJob $job, JobHours $hours, array $expenses, bool $fixedPriceBilled, array $rates, array $unbilledMonths = []): ?NotBillableReason { - if (! $job->isDone) { + if (! $job->inBillableStatus) { return NotBillableReason::WrongStatus; } @@ -38,6 +41,14 @@ final class BillingRules return NotBillableReason::MissingIdentityCode; } + if ($job->mode === BillingMode::MonthlyFee) { + if ($job->monthlyFeeCents === null) { + return NotBillableReason::MissingMonthlyFee; + } + + return $unbilledMonths === [] && $expenses === [] ? NotBillableReason::NothingToBill : null; + } + if ($job->mode === BillingMode::FixedPrice) { if (! $fixedPriceBilled && $job->quotedAmountCents === null) { return NotBillableReason::MissingQuotedAmount; @@ -76,18 +87,26 @@ final class BillingRules /** * 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. + * hours or the approved ones), the fixed price or the monthly fees, + * then the expenses. * * @param array $approvedByWorkType * @param list $expenses * @param array $rates + * @param list $unbilledMonths For a monthly fee job, as Y-m. * @return list */ - public function lines(BillableJob $job, DraftJob $draftJob, array $approvedByWorkType, array $expenses, bool $fixedPriceBilled, array $rates, int $vatBasisPoints): array + public function lines(BillableJob $job, DraftJob $draftJob, array $approvedByWorkType, array $expenses, bool $fixedPriceBilled, array $rates, int $vatBasisPoints, array $unbilledMonths = []): array { $lines = []; - if ($job->mode === BillingMode::FixedPrice) { + if ($job->mode === BillingMode::MonthlyFee) { + if ($job->monthlyFeeCents !== null) { + foreach ($unbilledMonths as $month) { + $lines[] = InvoiceLine::monthlyFee($job->id, $month, BillingMonths::label($month).' '.$job->label(), $job->monthlyFeeCents, $vatBasisPoints); + } + } + } elseif ($job->mode === BillingMode::FixedPrice) { if (! $fixedPriceBilled && $job->quotedAmountCents !== null) { $lines[] = InvoiceLine::fixedPrice($job->id, $job->label(), $job->quotedAmountCents, $vatBasisPoints); } diff --git a/app/Modules/Billing/Application/Services/BillingSnapshot.php b/app/Modules/Billing/Application/Services/BillingSnapshot.php index dcd0e90..862f4ac 100644 --- a/app/Modules/Billing/Application/Services/BillingSnapshot.php +++ b/app/Modules/Billing/Application/Services/BillingSnapshot.php @@ -13,12 +13,17 @@ use App\Modules\Billing\Application\DTOs\BillableJob; use App\Modules\Billing\Application\DTOs\HourlyRate; use App\Modules\Billing\Application\DTOs\JobHours; use App\Modules\Billing\Domain\Contracts\BillingExportRepository; +use App\Modules\Billing\Domain\Enums\BillingMode; use App\Modules\Billing\Domain\Enums\NotBillableReason; +use App\Modules\Billing\Domain\ValueObjects\BillingMonths; +use App\Modules\Billing\Domain\ValueObjects\DraftJob; +use App\Modules\Billing\Domain\ValueObjects\InvoiceLine; /** * What the given jobs have to bill right now, read once for a page or a * use case: the jobs, their unbilled hours and expenses, whose fixed price - * is already billed, the hourly rates and the VAT rate. + * and which monthly fees are already billed, the hourly rates, the VAT + * rate and the material's month. */ final class BillingSnapshot { @@ -39,6 +44,11 @@ final class BillingSnapshot public int $vatBasisPoints = 0; + /** @var array> */ + public array $billedMonths = []; + + public string $period = ''; + public function __construct( private BillingJobs $billingJobs, private BillingHours $billingHours, @@ -49,12 +59,14 @@ final class BillingSnapshot ) {} /** + * @param string $period Y-m: the material's month. * @param list $jobIds - * @param list $knownJobs Jobs already read, e.g. the done ones. + * @param list $knownJobs Jobs already read, e.g. the candidates. */ - public function load(array $jobIds, array $knownJobs = []): self + public function load(string $period, array $jobIds, array $knownJobs = []): self { $snapshot = clone $this; + $snapshot->period = $period; foreach ($knownJobs as $job) { $snapshot->jobs[$job->id] = $job; @@ -67,6 +79,7 @@ final class BillingSnapshot $snapshot->hours = $this->billingHours->forJobs($ids); $snapshot->expenses = $this->billingExpenses->forJobs($ids); $snapshot->fixedPriceBilled = array_fill_keys($this->exports->fixedPriceBilledJobIds($ids), true); + $snapshot->billedMonths = $this->exports->billedMonths($ids); $snapshot->rates = $this->prices->hourlyRates(); $snapshot->vatBasisPoints = $this->prices->defaultVatBasisPoints(); @@ -93,7 +106,34 @@ final class BillingSnapshot 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 $this->rules->reasonNotBillable($job, $this->hoursOf($job->id), $this->expensesOf($job->id), $this->isFixedPriceBilled($job->id), $this->rates, $this->unbilledMonthsOf($job)); + } + + /** + * The months (Y-m) a monthly fee job still has to bill up to the material's month. + * + * @return list + */ + public function unbilledMonthsOf(BillableJob $job): array + { + if ($job->mode !== BillingMode::MonthlyFee || $job->billingStartsOn === '') { + return []; + } + + return BillingMonths::unbilled($job->billingStartsOn, $job->billingEndsOn, $this->period, $this->billedMonths[$job->id] ?? []); + } + + /** + * The job's lines with the given hours and expenses (those just marked + * billed when the material is created). + * + * @param array $approvedByWorkType + * @param list $expenses + * @return list + */ + public function linesOf(BillableJob $job, DraftJob $draftJob, array $approvedByWorkType, array $expenses): array + { + return $this->rules->lines($job, $draftJob, $approvedByWorkType, $expenses, $this->isFixedPriceBilled($job->id), $this->rates, $this->vatBasisPoints, $this->unbilledMonthsOf($job)); } /** diff --git a/app/Modules/Billing/Application/Services/ExportViews.php b/app/Modules/Billing/Application/Services/ExportViews.php index 2244e82..20ca2c4 100644 --- a/app/Modules/Billing/Application/Services/ExportViews.php +++ b/app/Modules/Billing/Application/Services/ExportViews.php @@ -42,8 +42,8 @@ final class ExportViews return null; } - $done = $export->isDraft() ? $this->jobs->done() : []; - $snapshot = $this->snapshots->load($export->jobIds(), $done); + $candidates = $export->isDraft() ? $this->jobs->candidates() : []; + $snapshot = $this->snapshots->load($export->period(), $export->jobIds(), $candidates); $onDraft = array_flip($export->jobIds()); $invoices = []; @@ -52,7 +52,7 @@ final class ExportViews } $available = []; - foreach ($done as $job) { + foreach ($candidates as $job) { if (! isset($onDraft[$job->id])) { $hours = $snapshot->hoursOf($job->id); $available[] = new AvailableJob( @@ -71,6 +71,7 @@ final class ExportViews return new ExportView( (int) $export->id(), $export->status(), + $export->period(), $export->createdAt(), $names[$export->createdBy()] ?? '', $export->finalizedAt(), @@ -121,7 +122,7 @@ final class ExportViews } $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); + $lines = $snapshot->linesOf($job, $draftJob, $hours->approvedByWorkType, $snapshot->expensesOf($job->id)); $rows = []; foreach ($snapshot->rules->sortedByName($hours->approvedByWorkType, $snapshot->rates) as $workTypeId => $approved) { diff --git a/app/Modules/Billing/Application/UseCases/AddJobToDraft.php b/app/Modules/Billing/Application/UseCases/AddJobToDraft.php index a72e2c1..45d9b33 100644 --- a/app/Modules/Billing/Application/UseCases/AddJobToDraft.php +++ b/app/Modules/Billing/Application/UseCases/AddJobToDraft.php @@ -15,7 +15,8 @@ use App\Modules\Billing\Domain\Exceptions\JobNotBillable; use App\Modules\Shared\Application\Contracts\TransactionManager; /** - * Adds a done job to the draft as an invoice of its own, if it has + * Adds a done job (or a running monthly fee job) to the draft as an + * invoice of its own, if it has * something to bill and nothing stops it from being billed. */ final class AddJobToDraft @@ -40,7 +41,7 @@ final class AddJobToDraft public function execute(int $exportId, int $jobId): void { $this->changeDraft($exportId, function (BillingExport $export) use ($jobId): void { - $snapshot = $this->snapshots->load([$jobId]); + $snapshot = $this->snapshots->load($export->period(), [$jobId]); $job = $snapshot->jobs[$jobId] ?? throw new JobNotBillable($jobId, NotBillableReason::WrongStatus); $reason = $snapshot->reasonNotBillable($job); diff --git a/app/Modules/Billing/Application/UseCases/FinalizeBillingExport.php b/app/Modules/Billing/Application/UseCases/FinalizeBillingExport.php index aa26fc4..d5f48a9 100644 --- a/app/Modules/Billing/Application/UseCases/FinalizeBillingExport.php +++ b/app/Modules/Billing/Application/UseCases/FinalizeBillingExport.php @@ -10,6 +10,7 @@ use App\Modules\Billing\Application\Contracts\BillingJobs; use App\Modules\Billing\Application\DTOs\BillableExpense; use App\Modules\Billing\Application\Services\BillingSnapshot; use App\Modules\Billing\Domain\Contracts\BillingExportRepository; +use App\Modules\Billing\Domain\Enums\BillingMode; use App\Modules\Billing\Domain\Enums\NotBillableReason; use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound; use App\Modules\Billing\Domain\Exceptions\ExportEmpty; @@ -22,7 +23,8 @@ use App\Modules\Users\Application\Contracts\Clock; * Creates the billing material from its draft (spec 12), all or nothing: * checks every job again, marks the approved hours and billable expenses * billed, forms the invoice lines from what was marked with the current - * prices, and moves the jobs to "Lasku luotu". + * prices, and moves the jobs to "Lasku luotu". Monthly fee jobs keep + * running, so their status stays. */ final class FinalizeBillingExport { @@ -50,7 +52,7 @@ final class FinalizeBillingExport $export = $this->exports->findById($exportId, lock: true) ?? throw new BillingExportNotFound($exportId); $export->ensureDraft(); - $snapshot = $this->snapshots->load($export->jobIds()); + $snapshot = $this->snapshots->load($export->period(), $export->jobIds()); foreach ($export->jobIds() as $jobId) { $job = $snapshot->jobs[$jobId] ?? throw new JobNotBillable($jobId, NotBillableReason::WrongStatus); @@ -72,8 +74,11 @@ final class FinalizeBillingExport 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); + $linesByJob[$job->id] = $snapshot->linesOf($job, $draftJob, $billedHours, $billedExpenses); + + if ($job->mode !== BillingMode::MonthlyFee) { + $this->jobs->markInvoiced($job->id, $actorUserId); + } } $export->finalize($linesByJob, $actorUserId, $this->clock->now()); diff --git a/app/Modules/Billing/Application/UseCases/OpenBillingDraft.php b/app/Modules/Billing/Application/UseCases/OpenBillingDraft.php index 170d957..e97a74f 100644 --- a/app/Modules/Billing/Application/UseCases/OpenBillingDraft.php +++ b/app/Modules/Billing/Application/UseCases/OpenBillingDraft.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace App\Modules\Billing\Application\UseCases; +use App\Modules\Billing\Application\Contracts\BillingJobs; +use App\Modules\Billing\Application\Services\BillingSnapshot; use App\Modules\Billing\Domain\Contracts\BillingExportRepository; use App\Modules\Billing\Domain\Entities\BillingExport; use App\Modules\Billing\Domain\Exceptions\DraftAlreadyOpen; @@ -11,13 +13,17 @@ use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Users\Application\Contracts\Clock; /** - * Opens a new billing material draft. There is one draft at a time, so - * two people never bill the same jobs on separate drafts. + * Opens a new billing material draft for the current month, with every + * monthly fee job that has something to bill already on it (spec 5.5), + * each an invoice of its own. There is one draft at a time, so two people + * never bill the same jobs on separate drafts. */ final class OpenBillingDraft { public function __construct( private BillingExportRepository $exports, + private BillingJobs $jobs, + private BillingSnapshot $snapshots, private TransactionManager $transactions, private Clock $clock, ) {} @@ -34,7 +40,17 @@ final class OpenBillingDraft throw new DraftAlreadyOpen; } - return (int) $this->exports->save(BillingExport::startDraft($actorUserId, $this->clock->now()))->id(); + $export = BillingExport::startDraft($actorUserId, $this->clock->today()); + $monthly = $this->jobs->monthly(); + $snapshot = $this->snapshots->load($export->period(), [], $monthly); + + foreach ($monthly as $job) { + if ($snapshot->reasonNotBillable($job) === null) { + $export->addJob($job->toDraftJob()); + } + } + + return (int) $this->exports->save($export)->id(); }); } } diff --git a/app/Modules/Billing/Application/UseCases/SetBillingPeriod.php b/app/Modules/Billing/Application/UseCases/SetBillingPeriod.php new file mode 100644 index 0000000..35a8377 --- /dev/null +++ b/app/Modules/Billing/Application/UseCases/SetBillingPeriod.php @@ -0,0 +1,38 @@ +exports = $exports; + $this->transactions = $transactions; + } + + /** + * @throws BillingExportNotFound + * @throws ExportNotDraft + * @throws InvalidBillingPeriod + */ + public function execute(int $exportId, string $period): void + { + $this->changeDraft($exportId, function (BillingExport $export) use ($period): void { + $export->changePeriod($period); + }); + } +} diff --git a/app/Modules/Billing/Domain/Contracts/BillingExportRepository.php b/app/Modules/Billing/Domain/Contracts/BillingExportRepository.php index 6459eda..a683349 100644 --- a/app/Modules/Billing/Domain/Contracts/BillingExportRepository.php +++ b/app/Modules/Billing/Domain/Contracts/BillingExportRepository.php @@ -33,4 +33,12 @@ interface BillingExportRepository * @return list */ public function fixedPriceBilledJobIds(array $jobIds): array; + + /** + * The months (Y-m) whose monthly fee is on a created material, by job. + * + * @param list $jobIds + * @return array> + */ + public function billedMonths(array $jobIds): array; } diff --git a/app/Modules/Billing/Domain/Entities/BillingExport.php b/app/Modules/Billing/Domain/Entities/BillingExport.php index 65957ac..b7f9f1d 100644 --- a/app/Modules/Billing/Domain/Entities/BillingExport.php +++ b/app/Modules/Billing/Domain/Entities/BillingExport.php @@ -8,9 +8,11 @@ use App\Modules\Billing\Domain\Enums\ExportStatus; use App\Modules\Billing\Domain\Exceptions\ExportEmpty; use App\Modules\Billing\Domain\Exceptions\ExportNotDraft; use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours; +use App\Modules\Billing\Domain\Exceptions\InvalidBillingPeriod; use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge; use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft; use App\Modules\Billing\Domain\Exceptions\JobNotInDraft; +use App\Modules\Billing\Domain\ValueObjects\BillingMonths; use App\Modules\Billing\Domain\ValueObjects\DraftJob; use App\Modules\Billing\Domain\ValueObjects\InvoiceLine; use DateTimeImmutable; @@ -29,6 +31,7 @@ final class BillingExport private function __construct( private ?int $id, private ExportStatus $status, + private string $period, private int $createdBy, private DateTimeImmutable $createdAt, private ?int $finalizedBy, @@ -36,17 +39,37 @@ final class BillingExport private array $invoices, ) {} + /** + * A new draft billing monthly fees up to the current month. + */ public static function startDraft(int $createdBy, DateTimeImmutable $now): self { - return new self(null, ExportStatus::Draft, $createdBy, $now, null, null, []); + return new self(null, ExportStatus::Draft, $now->format('Y-m'), $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 + public static function reconstitute(int $id, ExportStatus $status, string $period, int $createdBy, DateTimeImmutable $createdAt, ?int $finalizedBy, ?DateTimeImmutable $finalizedAt, array $invoices): self { - return new self($id, $status, $createdBy, $createdAt, $finalizedBy, $finalizedAt, $invoices); + return new self($id, $status, $period, $createdBy, $createdAt, $finalizedBy, $finalizedAt, $invoices); + } + + /** + * Sets the month (Y-m) up to which monthly fees are billed. + * + * @throws ExportNotDraft + * @throws InvalidBillingPeriod + */ + public function changePeriod(string $period): void + { + $this->ensureDraft(); + $this->period = BillingMonths::ensureValid($period); + } + + public function period(): string + { + return $this->period; } /** diff --git a/app/Modules/Billing/Domain/Entities/BillingInvoice.php b/app/Modules/Billing/Domain/Entities/BillingInvoice.php index 7c2b8fd..d237baf 100644 --- a/app/Modules/Billing/Domain/Entities/BillingInvoice.php +++ b/app/Modules/Billing/Domain/Entities/BillingInvoice.php @@ -50,6 +50,10 @@ final class BillingInvoice continue; } + if ($other->ownInvoice || $job->ownInvoice) { + return MergeRefusal::MonthlyFeeAlone; + } + if ($other->customerId !== $job->customerId) { return MergeRefusal::DifferentCustomer; } diff --git a/app/Modules/Billing/Domain/Enums/BillingMode.php b/app/Modules/Billing/Domain/Enums/BillingMode.php index d9a4ebf..f77ac57 100644 --- a/app/Modules/Billing/Domain/Enums/BillingMode.php +++ b/app/Modules/Billing/Domain/Enums/BillingMode.php @@ -5,11 +5,13 @@ declare(strict_types=1); namespace App\Modules\Billing\Domain\Enums; /** - * How a job is billed: its hours per work type at the hourly rates, or its - * quoted fixed price as one line. Expenses are billed separately either way. + * How a job is billed: its hours per work type at the hourly rates, its + * quoted fixed price as one line, or its monthly fee for every month. + * Expenses are billed separately in every case. */ enum BillingMode: string { case Hours = 'hours'; case FixedPrice = 'fixed_price'; + case MonthlyFee = 'monthly_fee'; } diff --git a/app/Modules/Billing/Domain/Enums/LineKind.php b/app/Modules/Billing/Domain/Enums/LineKind.php index 5301c7a..1a0b950 100644 --- a/app/Modules/Billing/Domain/Enums/LineKind.php +++ b/app/Modules/Billing/Domain/Enums/LineKind.php @@ -12,4 +12,5 @@ enum LineKind: string case Hours = 'hours'; case FixedPrice = 'fixed_price'; case Expense = 'expense'; + case MonthlyFee = 'monthly_fee'; } diff --git a/app/Modules/Billing/Domain/Enums/MergeRefusal.php b/app/Modules/Billing/Domain/Enums/MergeRefusal.php index ad5f492..c671a0a 100644 --- a/app/Modules/Billing/Domain/Enums/MergeRefusal.php +++ b/app/Modules/Billing/Domain/Enums/MergeRefusal.php @@ -12,4 +12,7 @@ enum MergeRefusal: string case DifferentCustomer = 'different_customer'; case DifferentBillingUnit = 'different_billing_unit'; case DifferentReference = 'different_reference'; + + /** Monthly fee contracts are billed on invoices of their own (K22). */ + case MonthlyFeeAlone = 'monthly_fee_alone'; } diff --git a/app/Modules/Billing/Domain/Enums/NotBillableReason.php b/app/Modules/Billing/Domain/Enums/NotBillableReason.php index a43ecb0..7636205 100644 --- a/app/Modules/Billing/Domain/Enums/NotBillableReason.php +++ b/app/Modules/Billing/Domain/Enums/NotBillableReason.php @@ -9,10 +9,10 @@ namespace App\Modules\Billing\Domain\Enums; */ enum NotBillableReason: string { - /** The job is not done. */ + /** The job is not done (or for a monthly fee, not running). */ case WrongStatus = 'wrong_status'; - /** Not billable, billed monthly, or the internal customer. */ + /** Not billable, or the internal customer. */ case NotBillableBasis = 'not_billable_basis'; /** A consumer customer without a personal identity code. */ @@ -24,6 +24,9 @@ enum NotBillableReason: string /** A fixed price job without a quoted amount. */ case MissingQuotedAmount = 'missing_quoted_amount'; - /** No approved hours, expenses or fixed price left to bill. */ + /** A monthly fee job without a monthly fee. */ + case MissingMonthlyFee = 'missing_monthly_fee'; + + /** No approved hours, expenses, fixed price or months left to bill. */ case NothingToBill = 'nothing_to_bill'; } diff --git a/app/Modules/Billing/Domain/Exceptions/InvalidBillingPeriod.php b/app/Modules/Billing/Domain/Exceptions/InvalidBillingPeriod.php new file mode 100644 index 0000000..8f60707 --- /dev/null +++ b/app/Modules/Billing/Domain/Exceptions/InvalidBillingPeriod.php @@ -0,0 +1,15 @@ + $billed Months billed before, as Y-m. + * @return list + */ + public static function unbilled(string $startsOn, ?string $endsOn, string $period, array $billed): array + { + $end = $endsOn === null ? $period : min($period, substr($endsOn, 0, 7)); + $billedMonths = array_flip($billed); + $months = []; + + for ($month = substr($startsOn, 0, 7); $month <= $end; $month = self::next($month)) { + if (! isset($billedMonths[$month])) { + $months[] = $month; + } + } + + return $months; + } + + /** + * @throws InvalidBillingPeriod + */ + public static function ensureValid(string $period): string + { + if (preg_match('/^(\d{4})-(0[1-9]|1[0-2])$/', $period) !== 1) { + throw new InvalidBillingPeriod; + } + + return $period; + } + + /** + * "11/2026" for "2026-11". + */ + public static function label(string $month): string + { + return ((int) substr($month, 5, 2)).'/'.substr($month, 0, 4); + } + + private static function next(string $month): string + { + $year = (int) substr($month, 0, 4); + $number = (int) substr($month, 5, 2) + 1; + + if ($number > 12) { + $year++; + $number = 1; + } + + return sprintf('%04d-%02d', $year, $number); + } +} diff --git a/app/Modules/Billing/Domain/ValueObjects/DraftJob.php b/app/Modules/Billing/Domain/ValueObjects/DraftJob.php index 4d29fe4..03edc63 100644 --- a/app/Modules/Billing/Domain/ValueObjects/DraftJob.php +++ b/app/Modules/Billing/Domain/ValueObjects/DraftJob.php @@ -10,6 +10,7 @@ use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours; * A job on a draft invoice: who it bills (customer, billing unit, the * customer's reference) and management's billable hours per work type. * A work type without its own billable hours bills its approved hours. + * A monthly fee job is always an invoice of its own. */ final readonly class DraftJob { @@ -25,6 +26,7 @@ final readonly class DraftJob public ?int $billingUnitId, public ?string $reference, public array $billableQuarters = [], + public bool $ownInvoice = false, ) {} /** @@ -42,7 +44,7 @@ final readonly class DraftJob $billable[$workTypeId] = $quarters; } - return new self($this->jobId, $this->customerId, $this->billingUnitId, $this->reference, $billable); + return new self($this->jobId, $this->customerId, $this->billingUnitId, $this->reference, $billable, $this->ownInvoice); } /** diff --git a/app/Modules/Billing/Domain/ValueObjects/InvoiceLine.php b/app/Modules/Billing/Domain/ValueObjects/InvoiceLine.php index d66ba45..3e0ba8c 100644 --- a/app/Modules/Billing/Domain/ValueObjects/InvoiceLine.php +++ b/app/Modules/Billing/Domain/ValueObjects/InvoiceLine.php @@ -8,7 +8,7 @@ use App\Modules\Billing\Domain\Enums\LineKind; /** * A line of an invoice, without VAT: a work type's billable hours at its - * hourly rate, a job's fixed price, or an expense. Prices and descriptions + * hourly rate, a job's fixed price, a month's fee, or an expense. Prices and descriptions * are snapshots taken when the material is formed. */ final readonly class InvoiceLine @@ -24,6 +24,7 @@ final readonly class InvoiceLine public int $unitPriceCents, public int $vatBasisPoints, public int $netCents, + public ?string $period = null, ) {} /** @@ -51,6 +52,14 @@ final readonly class InvoiceLine return new self($jobId, LineKind::FixedPrice, null, null, $description, null, null, $amountCents, $vatBasisPoints, $amountCents); } + /** + * The fee of one month (Y-m). + */ + public static function monthlyFee(int $jobId, string $period, string $description, int $amountCents, int $vatBasisPoints): self + { + return new self($jobId, LineKind::MonthlyFee, null, null, $description, null, null, $amountCents, $vatBasisPoints, $amountCents, $period); + } + public static function expense(int $jobId, int $expenseId, string $description, int $amountCents, int $vatBasisPoints): self { return new self($jobId, LineKind::Expense, null, $expenseId, $description, null, null, $amountCents, $vatBasisPoints, $amountCents); diff --git a/app/Modules/Billing/Infrastructure/JobsForBilling.php b/app/Modules/Billing/Infrastructure/JobsForBilling.php index a43f799..8b59d94 100644 --- a/app/Modules/Billing/Infrastructure/JobsForBilling.php +++ b/app/Modules/Billing/Infrastructure/JobsForBilling.php @@ -21,15 +21,30 @@ use App\Modules\Jobs\Domain\Enums\PaymentBasis; */ class JobsForBilling implements BillingJobs { + /** Statuses in which a monthly fee job is billed: running or done. */ + private const array MONTHLY_STATUSES = [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done]; + public function __construct( private CustomerJobQueries $jobs, private CustomerQueries $customers, private ChangeJobStatus $changeStatus, ) {} - public function done(): array + public function candidates(): array { - return $this->toBillable($this->jobs->billingInfoWithStatus(JobStatus::Done)); + $jobs = []; + foreach ([...$this->jobs->billingInfoWithStatus(JobStatus::Done), ...$this->jobs->billingInfoMonthly()] as $job) { + $jobs[$job->id] = $job; + } + + uasort($jobs, fn (JobBillingInfo $a, JobBillingInfo $b): int => strcmp($a->number, $b->number)); + + return $this->toBillable(array_values($jobs)); + } + + public function monthly(): array + { + return $this->toBillable($this->jobs->billingInfoMonthly()); } public function find(array $jobIds): array @@ -65,6 +80,13 @@ class JobsForBilling implements BillingJobs return array_map(function (JobBillingInfo $job) use ($customers): BillableJob { $customer = $customers[$job->customerId] ?? null; + $mode = match ($job->paymentBasis) { + PaymentBasis::FixedQuote => BillingMode::FixedPrice, + PaymentBasis::MonthlyFee => BillingMode::MonthlyFee, + PaymentBasis::NotBillable => null, + default => BillingMode::Hours, + }; + $ends = array_filter([$job->dueOn, $job->completedOn]); return new BillableJob( $job->id, @@ -78,13 +100,12 @@ class JobsForBilling implements BillingJobs $job->billingUnitId, $job->billingUnitName, $job->customerReference, - match ($job->paymentBasis) { - PaymentBasis::FixedQuote => BillingMode::FixedPrice, - PaymentBasis::NotBillable, PaymentBasis::MonthlyFee => null, - default => BillingMode::Hours, - }, + $mode, $job->quotedAmountCents, - $job->status === JobStatus::Done, + $mode === BillingMode::MonthlyFee ? in_array($job->status, self::MONTHLY_STATUSES, true) : $job->status === JobStatus::Done, + $job->monthlyFeeCents, + $job->startsOn ?? $job->createdOn, + $ends === [] ? null : min($ends), ); }, $jobs); } diff --git a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingExportModel.php b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingExportModel.php index b501eb7..359e3f8 100644 --- a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingExportModel.php +++ b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingExportModel.php @@ -14,13 +14,14 @@ use Illuminate\Support\Carbon; * * @property int $id * @property ExportStatus $status + * @property string|null $period Y-m * @property int $created_by * @property int|null $finalized_by * @property Carbon|null $finalized_at * @property Carbon $created_at */ #[Table('billing_exports')] -#[Fillable(['status', 'created_by', 'finalized_by', 'finalized_at'])] +#[Fillable(['status', 'period', 'created_by', 'finalized_by', 'finalized_at'])] class BillingExportModel extends Model { /** diff --git a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceJobModel.php b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceJobModel.php index 187be73..75302ec 100644 --- a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceJobModel.php +++ b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingInvoiceJobModel.php @@ -18,10 +18,11 @@ use Illuminate\Database\Eloquent\Relations\HasMany; * @property int $customer_id * @property int|null $billing_unit_id * @property string|null $customer_reference + * @property bool $own_invoice * @property int $sort_order */ #[Table('billing_invoice_jobs')] -#[Fillable(['billing_invoice_id', 'customer_job_id', 'customer_id', 'billing_unit_id', 'customer_reference', 'sort_order'])] +#[Fillable(['billing_invoice_id', 'customer_job_id', 'customer_id', 'billing_unit_id', 'customer_reference', 'own_invoice', 'sort_order'])] class BillingInvoiceJobModel extends Model { public $timestamps = false; @@ -44,6 +45,7 @@ class BillingInvoiceJobModel extends Model 'customer_job_id' => 'integer', 'customer_id' => 'integer', 'billing_unit_id' => 'integer', + 'own_invoice' => 'boolean', 'sort_order' => 'integer', ]; } diff --git a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingLineModel.php b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingLineModel.php index 58fd28d..a9c6710 100644 --- a/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingLineModel.php +++ b/app/Modules/Billing/Infrastructure/Persistence/Eloquent/BillingLineModel.php @@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Model; * @property LineKind $kind * @property int|null $work_type_id * @property int|null $expense_id + * @property string|null $period Y-m * @property string $description * @property int|null $recorded_quarters * @property int|null $quantity_quarters @@ -26,7 +27,7 @@ use Illuminate\Database\Eloquent\Model; */ #[Table('billing_lines')] #[Fillable([ - 'billing_invoice_id', 'customer_job_id', 'kind', 'work_type_id', 'expense_id', 'description', + 'billing_invoice_id', 'customer_job_id', 'kind', 'work_type_id', 'expense_id', 'period', 'description', 'recorded_quarters', 'quantity_quarters', 'unit_price_cents', 'vat_basis_points', 'net_cents', 'sort_order', ])] class BillingLineModel extends Model diff --git a/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingExportRepository.php b/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingExportRepository.php index 08bfff4..d94677d 100644 --- a/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingExportRepository.php +++ b/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingExportRepository.php @@ -46,6 +46,7 @@ class EloquentBillingExportRepository implements BillingExportRepository $model->fill([ 'status' => $export->status(), + 'period' => $export->period(), 'created_by' => $export->createdBy(), 'finalized_by' => $export->finalizedBy(), 'finalized_at' => $export->finalizedAt()?->format('Y-m-d H:i:s'), @@ -75,6 +76,7 @@ class EloquentBillingExportRepository implements BillingExportRepository 'customer_id' => $job->customerId, 'billing_unit_id' => $job->billingUnitId, 'customer_reference' => $job->reference, + 'own_invoice' => $job->ownInvoice, 'sort_order' => $jobOrder, ]); @@ -94,6 +96,7 @@ class EloquentBillingExportRepository implements BillingExportRepository 'kind' => $line->kind, 'work_type_id' => $line->workTypeId, 'expense_id' => $line->expenseId, + 'period' => $line->period, 'description' => mb_substr($line->description, 0, 255), 'recorded_quarters' => $line->recordedQuarters, 'quantity_quarters' => $line->quantityQuarters, @@ -129,6 +132,21 @@ class EloquentBillingExportRepository implements BillingExportRepository ->all(); } + public function billedMonths(array $jobIds): array + { + if ($jobIds === []) { + return []; + } + + $months = []; + + foreach (BillingLineModel::query()->whereIn('customer_job_id', $jobIds)->where('kind', LineKind::MonthlyFee)->whereNotNull('period')->get(['customer_job_id', 'period']) as $line) { + $months[$line->customer_job_id][] = (string) $line->period; + } + + return $months; + } + private function toEntity(BillingExportModel $model): BillingExport { $invoices = $model->invoices->map(fn (BillingInvoiceModel $invoice): BillingInvoice => BillingInvoice::reconstitute( @@ -138,6 +156,7 @@ class EloquentBillingExportRepository implements BillingExportRepository $job->billing_unit_id, $job->customer_reference, $job->hours->mapWithKeys(fn (BillingJobHoursModel $hours): array => [$hours->work_type_id => $hours->billable_quarters])->all(), + $job->own_invoice, ))->values()->all(), $invoice->lines->map(fn (BillingLineModel $line): InvoiceLine => new InvoiceLine( $line->customer_job_id, @@ -150,12 +169,14 @@ class EloquentBillingExportRepository implements BillingExportRepository $line->unit_price_cents, $line->vat_basis_points, $line->net_cents, + $line->period, ))->values()->all(), ))->values()->all(); return BillingExport::reconstitute( $model->id, $model->status, + $model->period ?? $model->created_at->format('Y-m'), $model->created_by, DateTimeImmutable::createFromInterface($model->created_at), $model->finalized_by, diff --git a/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php b/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php index 708d31a..871b9ab 100644 --- a/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php +++ b/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php @@ -10,12 +10,15 @@ use App\Modules\Billing\Application\UseCases\MoveJobToInvoice; use App\Modules\Billing\Application\UseCases\RemoveJobFromDraft; use App\Modules\Billing\Application\UseCases\SeparateJob; use App\Modules\Billing\Application\UseCases\SetBillableHours; +use App\Modules\Billing\Application\UseCases\SetBillingPeriod; use App\Modules\Billing\Domain\Enums\BillingMode; use App\Modules\Billing\Domain\Enums\LineKind; use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound; use App\Modules\Billing\Domain\Exceptions\ExportEmpty; use App\Modules\Billing\Domain\Exceptions\ExportNotDraft; use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours; +use App\Modules\Billing\Domain\Exceptions\InvalidBillingPeriod; +use App\Modules\Billing\Domain\ValueObjects\BillingMonths; use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge; use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft; use App\Modules\Billing\Domain\Exceptions\JobNotBillable; @@ -120,6 +123,26 @@ new class extends Component unset($this->export); } + public function savePeriod(string $value, SetBillingPeriod $setBillingPeriod): void + { + $this->authorize('billing.manage'); + $this->resetErrorBag('period'); + $this->statusMessage = ''; + $this->errorMessage = ''; + + try { + $setBillingPeriod->execute($this->exportId, mb_substr(trim($value), 0, 7)); + unset($this->export); + $this->statusMessage = __('billing.export.period_saved', ['month' => BillingMonths::label($this->export->period)]); + } catch (InvalidBillingPeriod) { + $this->addError('period', __('billing.errors.period')); + } catch (ExportNotDraft|BillingExportNotFound $exception) { + $this->errorMessage = $this->errorText($exception, ''); + } + + unset($this->export); + } + public function confirmFinalize(): void { $this->authorize('billing.manage'); @@ -304,6 +327,23 @@ new class extends Component @if ($export->isDraft()) +
+ + +

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

+ @error('period') +

{{ $message }}

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

@endif - @if ($export->isDraft() && $job->unapprovedQuarters > 0) + @if ($export->isDraft() && $job->unapprovedQuarters > 0 && $job->mode !== BillingMode::MonthlyFee)

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

+ @else + + + + + + + + + + @foreach ($months as $line) + + + + + @endforeach + +
{{ __('billing.jobs.months_caption', ['job' => $job->label()]) }}
{{ __('billing.jobs.month') }}{{ __('billing.jobs.amount') }}
{{ BillingMonths::label((string) $line->period) }}{{ $this->money($line->netCents) }}
+ @endif + @php($approved = array_sum(array_map(fn ($row) => $row->approvedQuarters, $job->hours))) + @if ($approved > 0) +

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

+ @endif + @elseif ($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)]) }} diff --git a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php index 91727f0..d9a4e9e 100644 --- a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php +++ b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php @@ -50,6 +50,14 @@ interface CustomerJobQueries */ public function billingInfoWithStatus(JobStatus $status): array; + /** + * Billing details of the jobs billed by a monthly fee that may be + * billed now (ordered, in production, on hold or done), by job number. + * + * @return list + */ + public function billingInfoMonthly(): array; + /** * Billing details of the given jobs, keyed by id; unknown ids are left out. * diff --git a/app/Modules/Jobs/Application/DTOs/CustomerJobData.php b/app/Modules/Jobs/Application/DTOs/CustomerJobData.php index 5043ce9..3551a44 100644 --- a/app/Modules/Jobs/Application/DTOs/CustomerJobData.php +++ b/app/Modules/Jobs/Application/DTOs/CustomerJobData.php @@ -42,5 +42,6 @@ final readonly class CustomerJobData public array $links = [], public ?string $quotedAmount = null, public bool $setsQuotedAmount = false, + public ?string $monthlyFee = null, ) {} } diff --git a/app/Modules/Jobs/Application/DTOs/CustomerJobDetails.php b/app/Modules/Jobs/Application/DTOs/CustomerJobDetails.php index 668c0c3..78f586d 100644 --- a/app/Modules/Jobs/Application/DTOs/CustomerJobDetails.php +++ b/app/Modules/Jobs/Application/DTOs/CustomerJobDetails.php @@ -49,6 +49,7 @@ final readonly class CustomerJobDetails public string $createdAt, public string $createdByName, public ?int $quotedAmountCents = null, + public ?int $monthlyFeeCents = null, public ?string $completedAt = null, ) {} diff --git a/app/Modules/Jobs/Application/DTOs/JobBillingInfo.php b/app/Modules/Jobs/Application/DTOs/JobBillingInfo.php index 8f2c6ea..f3d486a 100644 --- a/app/Modules/Jobs/Application/DTOs/JobBillingInfo.php +++ b/app/Modules/Jobs/Application/DTOs/JobBillingInfo.php @@ -9,7 +9,8 @@ use App\Modules\Jobs\Domain\Enums\PaymentBasis; /** * A customer job as billing sees it: who is billed, under which billing - * unit and reference, and how (payment basis, quoted amount without VAT). + * unit and reference, and how (payment basis, quoted amount and monthly + * fee without VAT), and for monthly fees the months it runs. */ final readonly class JobBillingInfo { @@ -25,5 +26,10 @@ final readonly class JobBillingInfo public ?string $customerReference, public ?int $billingUnitId, public ?string $billingUnitName, + public ?int $monthlyFeeCents = null, + public ?string $startsOn = null, + public ?string $dueOn = null, + public ?string $completedOn = null, + public string $createdOn = '', ) {} } diff --git a/app/Modules/Jobs/Application/Services/JobDetailsFactory.php b/app/Modules/Jobs/Application/Services/JobDetailsFactory.php index ebc7410..94581e6 100644 --- a/app/Modules/Jobs/Application/Services/JobDetailsFactory.php +++ b/app/Modules/Jobs/Application/Services/JobDetailsFactory.php @@ -12,6 +12,7 @@ use App\Modules\Jobs\Domain\Enums\JobStatus; use App\Modules\Jobs\Domain\Enums\PaymentBasis; use App\Modules\Jobs\Domain\Enums\Priority; use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference; +use App\Modules\Jobs\Domain\Exceptions\InvalidMonthlyFee; use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours; use App\Modules\Jobs\Domain\ValueObjects\JobDetails; use App\Modules\Jobs\Domain\ValueObjects\JobLink; @@ -73,9 +74,22 @@ final class JobDetailsFactory tags: array_map(fn (string $tag): Tag => new Tag($tag), $data->tags), links: array_map(fn (array $link): JobLink => new JobLink($link['title'], $link['url']), $data->links), quotedAmount: $data->setsQuotedAmount ? Money::parse((string) $data->quotedAmount) : $current?->quotedAmount, + monthlyFee: $data->setsQuotedAmount ? self::monthlyFee($data->monthlyFee) : $current?->monthlyFee, ); } + /** + * @throws InvalidMonthlyFee + */ + private static function monthlyFee(?string $value): ?Money + { + try { + return Money::parse((string) $value); + } catch (InvalidMoneyAmount) { + throw new InvalidMonthlyFee; + } + } + private function checkReferences(CustomerJobData $data, ?JobDetails $current): void { if ($this->customers->findSummary($data->customerId) === null) { diff --git a/app/Modules/Jobs/Domain/Exceptions/InvalidMonthlyFee.php b/app/Modules/Jobs/Domain/Exceptions/InvalidMonthlyFee.php new file mode 100644 index 0000000..efa273a --- /dev/null +++ b/app/Modules/Jobs/Domain/Exceptions/InvalidMonthlyFee.php @@ -0,0 +1,15 @@ +kind, $status, $this->priority, $this->paymentBasis, $this->estimatedHours, $this->customerReference, $this->instructions, $this->responsibleUserId, $this->contactUserId, $this->customerContactId, $this->billerUserId, $this->billingUnitId, $this->memberUserIds, - $this->tags, $this->links, $this->quotedAmount, + $this->tags, $this->links, $this->quotedAmount, $this->monthlyFee, ); } @@ -109,7 +110,7 @@ final readonly class JobDetails $this->kind, $this->status, $this->priority, $this->paymentBasis, $this->estimatedHours, $this->customerReference, $this->instructions, $this->responsibleUserId, $this->contactUserId, $this->customerContactId, $this->billerUserId, $this->billingUnitId, $this->memberUserIds, - $this->tags, $this->links, $this->quotedAmount, + $this->tags, $this->links, $this->quotedAmount, $this->monthlyFee, ); } @@ -152,6 +153,7 @@ final readonly class JobDetails 'payment_basis' => $this->paymentBasis?->value, 'estimated_hours' => $this->estimatedHours?->format(), 'quoted_amount' => $this->quotedAmount === null ? null : (string) $this->quotedAmount->cents, + 'monthly_fee' => $this->monthlyFee === null ? null : (string) $this->monthlyFee->cents, 'customer_reference' => $this->customerReference, 'instructions' => $this->instructions, 'responsible_user' => (string) $this->responsibleUserId, diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php index 6e8dc8a..5d8becf 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php @@ -42,6 +42,7 @@ use Illuminate\Database\Eloquent\Model; * @property int|null $billing_unit_id * @property int $created_by * @property int|null $quoted_amount_cents + * @property int|null $monthly_fee_cents * @property CarbonImmutable|null $completed_at * @property int|null $quick_sale_year * @property CarbonImmutable $created_at @@ -49,7 +50,7 @@ use Illuminate\Database\Eloquent\Model; #[Table('customer_jobs')] #[Fillable([ 'number', 'name', 'description', 'customer_id', 'starts_on', 'due_on', 'planned_from', 'planned_to', - 'kind', 'status', 'priority', 'payment_basis', 'estimated_hours', 'quoted_amount_cents', 'customer_reference', 'instructions', + 'kind', 'status', 'priority', 'payment_basis', 'estimated_hours', 'quoted_amount_cents', 'monthly_fee_cents', 'customer_reference', 'instructions', 'responsible_user_id', 'contact_user_id', 'customer_contact_id', 'biller_user_id', 'billing_unit_id', 'created_by', 'completed_at', ])] #[UseFactory(CustomerJobFactory::class)] @@ -66,6 +67,7 @@ class CustomerJobModel extends Model return [ 'customer_id' => 'integer', 'quoted_amount_cents' => 'integer', + 'monthly_fee_cents' => 'integer', 'quick_sale_year' => 'integer', 'completed_at' => 'immutable_datetime', 'starts_on' => 'immutable_date', diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php index 6bdde77..fd47ce7 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php @@ -12,6 +12,7 @@ use App\Modules\Jobs\Application\DTOs\JobChangeEntry; use App\Modules\Jobs\Application\DTOs\JobListFilter; use App\Modules\Jobs\Application\DTOs\NamedId; use App\Modules\Jobs\Domain\Enums\JobStatus; +use App\Modules\Jobs\Domain\Enums\PaymentBasis; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel; use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement; use App\Modules\Users\Application\Contracts\UserAccountQueries; @@ -181,6 +182,7 @@ class EloquentCustomerJobQueries implements CustomerJobQueries createdAt: $model->created_at->format('Y-m-d H:i'), createdByName: $userNames[$model->created_by] ?? '', quotedAmountCents: $model->quoted_amount_cents, + monthlyFeeCents: $model->monthly_fee_cents, completedAt: $model->completed_at?->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'), ); } @@ -190,6 +192,15 @@ class EloquentCustomerJobQueries implements CustomerJobQueries return array_values($this->billingInfo(CustomerJobModel::query()->where('status', $status)->orderBy('number')->get())); } + public function billingInfoMonthly(): array + { + return array_values($this->billingInfo(CustomerJobModel::query() + ->where('payment_basis', PaymentBasis::MonthlyFee) + ->whereIn('status', [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done]) + ->orderBy('number') + ->get())); + } + public function billingInfoOf(array $ids): array { return $ids === [] ? [] : $this->billingInfo(CustomerJobModel::query()->whereIn('id', $ids)->orderBy('number')->get()); @@ -204,6 +215,7 @@ class EloquentCustomerJobQueries implements CustomerJobQueries $customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all()); $billingUnitNames = []; $result = []; + $timezone = (string) config('app.business_timezone'); foreach ($models as $model) { if ($model->billing_unit_id !== null && ! isset($billingUnitNames[$model->customer_id])) { @@ -225,6 +237,11 @@ class EloquentCustomerJobQueries implements CustomerJobQueries $model->customer_reference, $model->billing_unit_id, $model->billing_unit_id === null ? null : ($billingUnitNames[$model->customer_id][$model->billing_unit_id] ?? null), + $model->monthly_fee_cents, + $model->starts_on?->format('Y-m-d'), + $model->due_on?->format('Y-m-d'), + $model->completed_at?->setTimezone($timezone)->format('Y-m-d'), + $model->created_at->setTimezone($timezone)->format('Y-m-d'), ); } diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php index 28b5a0d..1608c6f 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php @@ -44,6 +44,7 @@ class EloquentCustomerJobRepository implements CustomerJobRepository 'payment_basis' => $details->paymentBasis, 'estimated_hours' => $details->estimatedHours?->value, 'quoted_amount_cents' => $details->quotedAmount?->cents, + 'monthly_fee_cents' => $details->monthlyFee?->cents, 'completed_at' => $job->completedAt()?->format('Y-m-d H:i:s'), 'customer_reference' => $details->customerReference, 'instructions' => $details->instructions, @@ -163,6 +164,7 @@ class EloquentCustomerJobRepository implements CustomerJobRepository ->map(fn ($row): JobLink => new JobLink((string) $row->title, (string) $row->url)) ->all(), quotedAmount: $model->quoted_amount_cents === null ? null : Money::fromCents($model->quoted_amount_cents), + monthlyFee: $model->monthly_fee_cents === null ? null : Money::fromCents($model->monthly_fee_cents), ); return CustomerJob::reconstitute( diff --git a/app/Modules/Jobs/Presentation/Livewire/Forms/JobForm.php b/app/Modules/Jobs/Presentation/Livewire/Forms/JobForm.php index aed4abe..f219af9 100644 --- a/app/Modules/Jobs/Presentation/Livewire/Forms/JobForm.php +++ b/app/Modules/Jobs/Presentation/Livewire/Forms/JobForm.php @@ -14,6 +14,7 @@ use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours; use App\Modules\Jobs\Domain\Exceptions\InvalidJobLink; use App\Modules\Jobs\Domain\Exceptions\InvalidJobName; use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference; +use App\Modules\Jobs\Domain\Exceptions\InvalidMonthlyFee; use App\Modules\Jobs\Domain\Exceptions\InvalidTag; use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart; use App\Modules\Jobs\Domain\Exceptions\ServiceUnitRequired; @@ -62,6 +63,8 @@ class JobForm extends Form */ public string $quoted_amount = ''; + public string $monthly_fee = ''; + public string $customer_reference = ''; public string $instructions = ''; @@ -101,6 +104,7 @@ class JobForm extends Form $this->payment_basis = $job->paymentBasis->value ?? ''; $this->estimated_hours = $job->estimatedHours ?? ''; $this->quoted_amount = $job->quotedAmountCents === null || ! Gate::allows('money.quotes') ? '' : Money::fromCents($job->quotedAmountCents)->inputValue(); + $this->monthly_fee = $job->monthlyFeeCents === null || ! Gate::allows('money.quotes') ? '' : Money::fromCents($job->monthlyFeeCents)->inputValue(); $this->customer_reference = $job->customerReference ?? ''; $this->instructions = $job->instructions ?? ''; $this->responsible_user_id = (string) $job->responsible->id; @@ -146,6 +150,7 @@ class JobForm extends Form links: array_values(array_filter($this->links, fn (array $link): bool => trim($link['title']) !== '' || trim($link['url']) !== '')), quotedAmount: $text($this->quoted_amount), setsQuotedAmount: Gate::allows('money.quotes'), + monthlyFee: $this->payment_basis === PaymentBasis::MonthlyFee->value ? $text($this->monthly_fee) : null, ); } @@ -161,6 +166,7 @@ class JobForm extends Form $exception instanceof PlanEndsBeforeStart => ['planned_to', 'jobs.errors.plan_ends_before_start'], $exception instanceof InvalidEstimatedHours => ['estimated_hours', 'jobs.errors.invalid_hours'], $exception instanceof InvalidMoneyAmount => ['quoted_amount', 'jobs.errors.invalid_amount'], + $exception instanceof InvalidMonthlyFee => ['monthly_fee', 'jobs.errors.invalid_amount'], $exception instanceof InvalidTag => ['tags', 'jobs.errors.invalid_tag'], $exception instanceof InvalidJobLink => ['links', 'jobs.errors.invalid_link'], $exception instanceof InvalidJobReference => [self::referenceField($exception->field), 'jobs.errors.invalid_reference'], @@ -201,6 +207,7 @@ class JobForm extends Form 'payment_basis' => ['nullable', Rule::enum(PaymentBasis::class)], 'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'], 'quoted_amount' => ['nullable', 'string', 'max:20'], + 'monthly_fee' => ['nullable', 'string', 'max:20'], 'customer_reference' => ['nullable', 'string', 'max:255'], 'instructions' => ['nullable', 'string', 'max:10000'], 'responsible_user_id' => ['required', 'integer'], @@ -240,6 +247,7 @@ class JobForm extends Form 'estimated_hours.min' => __('jobs.errors.invalid_hours'), 'estimated_hours.max' => __('jobs.errors.invalid_hours'), 'quoted_amount.max' => __('jobs.errors.invalid_amount'), + 'monthly_fee.max' => __('jobs.errors.invalid_amount'), 'customer_reference.max' => __('jobs.errors.too_long', ['max' => 255]), 'instructions.max' => __('jobs.errors.too_long', ['max' => 10000]), 'responsible_user_id.required' => __('jobs.errors.responsible_required'), diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php index 3d33c49..c8cfc56 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php @@ -342,7 +342,7 @@ new class extends Component @endforeach - + @foreach (PaymentBasis::cases() as $basis) @@ -367,6 +367,16 @@ new class extends Component :label="__('jobs.fields.quoted_amount_input')" :hint="__('jobs.fields.quoted_amount_description')" /> + + @if ($form->payment_basis === 'monthly_fee') + + @endif @endcan diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index 24b316e..d5af184 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -67,7 +67,7 @@ new class extends Component // Changes of the quoted amount are shown only to those who may see quotes (spec 5.7). return Gate::allows('money.quotes') ? $changes - : array_values(array_filter($changes, fn (JobChangeEntry $change): bool => $change->field !== 'quoted_amount')); + : array_values(array_filter($changes, fn (JobChangeEntry $change): bool => ! in_array($change->field, ['quoted_amount', 'monthly_fee'], true))); } /** @@ -171,7 +171,7 @@ new class extends Component return match ($field) { 'starts_on', 'due_on', 'planned_from', 'planned_to' => $this->formatDate($value), - 'quoted_amount' => Money::fromCents((int) $value)->format(), + 'quoted_amount', 'monthly_fee' => Money::fromCents((int) $value)->format(), 'kind' => __('jobs.kinds.'.$value), 'status' => __('jobs.statuses.'.$value), 'priority' => __('jobs.priorities.'.$value), @@ -245,6 +245,11 @@ new class extends Component @can('money.quotes')

{{ __('jobs.fields.quoted_amount') }}
{{ $job->quotedAmountCents === null ? __('jobs.not_set') : Money::fromCents($job->quotedAmountCents)->format().' '.__('jobs.vat_excluded') }}
+ + @if ($job->paymentBasis?->value === 'monthly_fee' || $job->monthlyFeeCents !== null) +
{{ __('jobs.fields.monthly_fee') }}
+
{{ $job->monthlyFeeCents === null ? __('jobs.not_set') : Money::fromCents($job->monthlyFeeCents)->format().' '.__('jobs.vat_excluded') }}
+ @endif @endcan
{{ __('jobs.fields.customer_reference') }}
diff --git a/database/migrations/2026_11_24_111257_add_monthly_billing.php b/database/migrations/2026_11_24_111257_add_monthly_billing.php new file mode 100644 index 0000000..19015e6 --- /dev/null +++ b/database/migrations/2026_11_24_111257_add_monthly_billing.php @@ -0,0 +1,54 @@ +unsignedInteger('monthly_fee_cents')->nullable()->after('quoted_amount_cents'); + }); + + Schema::table('billing_exports', function (Blueprint $table) { + $table->char('period', 7)->nullable()->after('status'); + }); + + Schema::table('billing_invoice_jobs', function (Blueprint $table) { + $table->boolean('own_invoice')->default(false)->after('customer_reference'); + }); + + Schema::table('billing_lines', function (Blueprint $table) { + $table->char('period', 7)->nullable()->after('expense_id'); + + $table->index(['customer_job_id', 'kind', 'period']); + }); + } + + public function down(): void + { + Schema::table('billing_lines', function (Blueprint $table) { + $table->dropIndex(['customer_job_id', 'kind', 'period']); + $table->dropColumn('period'); + }); + + Schema::table('billing_invoice_jobs', function (Blueprint $table) { + $table->dropColumn('own_invoice'); + }); + + Schema::table('billing_exports', function (Blueprint $table) { + $table->dropColumn('period'); + }); + + Schema::table('customer_jobs', function (Blueprint $table) { + $table->dropColumn('monthly_fee_cents'); + }); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index d6cd784..067729b 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -120,6 +120,7 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli | Maksuperuste | `payment_basis` | ks. 5.5 | | Arvioidut tunnit | `estimated_hours` | *(K24)* | | Budjetti / tarjoussumma | `quoted_amount_cents` | Rahamäärä ALV 0; näkyy ja muokattavissa vain Tarjoukset-oikeudella (2.3), muiden tallennus säilyttää sen *(K24, valmis)* | +| Kuukausihinta | `monthly_fee_cents` | Rahamäärä ALV 0 kk-laskutuksen työlle; lomakkeella vain, kun maksuperuste on kiinteä kk-laskutus; näkyvyys ja muokkaus kuten tarjoussummalla *(K22, valmis)* | | Asiakkaan viite (PO) | `customer_reference` | *(K24)* | | Tagit | `tags` | Haku listasta tai uuden lisäys, joka tallentuu listaan *(K25)* | | Linkit | `links` | Linkit tiedostoihin (Drive, Dropbox ym.), otsikko + URL *(K26)* | @@ -184,6 +185,10 @@ Väri ei koskaan yksin kerro tietoa: prioriteetti näytetään aina myös teksti Toistaiseksi jatkuvalle työlle, jonka maksuperuste on kiinteä kk-laskutus, syntyy laskuaineistoon automaattisesti rivi joka kuukausi. Ylläpidon kuukausisopimuslaskut laskutetaan omina laskuinaan *(K22)*. +- Uusi laskuaineiston luonnos lisää automaattisesti jokaisen laskutettavan kk-laskutuksen työn (tila tilattu, tuotannossa, odottaa tai valmis), kukin omaksi laskukseen; niitä ei voi yhdistää muiden töiden kanssa *(valmis)*. +- Laskulle tulee kuukausihinnan rivi jokaisesta laskuttamattomasta kuukaudesta työn aloituskuukaudesta (tai luontikuukaudesta) aineiston laskutuskuukauteen asti, mutta ei päättymispäivän tai valmistumisen jälkeen. Väliin jääneet kuukaudet tulevat mukaan, eikä mitään kuukautta laskuteta kahdesti *(valmis)*. +- Laskutettavat kulut tulevat samalle laskulle eriteltyinä. Tunnit kuuluvat kuukausihintaan: ne merkitään laskutetuiksi mutta eivät tule riveille. Työn tila ei muutu muodostuksessa, koska työ jatkuu *(valmis)*. + ### 5.6 Jäsenet | Kenttä | Koodissa | Kuka | @@ -317,7 +322,7 @@ Hierarkiaa muokataan pohjatietojen hallinnasta. - 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)*. +- Laskuttamatta jätetään työt, joiden maksuperuste on "ei laskuteta", 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)* @@ -348,7 +353,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, työajanseuranta päällä) **Jobs** (asiakastyöt) -- `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by` *(olemassa)*; `quoted_amount_cents`, `completed_at` (asetetaan, kun työ saavuttaa lukitsevan tilan; tyhjennetään, kun lukitus avataan), `quick_sale_year` (uniikki; merkitsee vuoden pikamyyntityön) *(V2, olemassa)* +- `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by` *(olemassa)*; `quoted_amount_cents`, `monthly_fee_cents`, `completed_at` (asetetaan, kun työ saavuttaa lukitsevan tilan; tyhjennetään, kun lukitus avataan), `quick_sale_year` (uniikki; merkitsee vuoden pikamyyntityön) *(V2, olemassa)* - `job_number_sequences`: `year`, `last_number` - `customer_job_service_unit`: `customer_job_id`, `service_unit_id` - `customer_job_members`: `customer_job_id`, `user_id` @@ -377,11 +382,11 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `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, olemassa)* -- `billing_exports`: `status` (`draft`/`created`; luonnoksia yksi kerrallaan), `created_by`, `finalized_by`, `finalized_at` (vientitiedosto lisätään Fennoa-viennin osassa) +- `billing_exports`: `status` (`draft`/`created`; luonnoksia yksi kerrallaan), `period` (laskutuskuukausi `Y-m`), `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_invoice_jobs`: `billing_invoice_id`, `customer_job_id`, työn `customer_id`, `billing_unit_id` ja `customer_reference` lisäyshetkellä, `own_invoice` (kk-laskutuksen työ on aina oma laskunsa), `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` +- `billing_lines` (muodostuksessa): `billing_invoice_id`, `customer_job_id`, `kind` (`hours`/`fixed_price`/`monthly_fee`/`expense`), `work_type_id`, `expense_id`, `period` (kuukausirivin kuukausi), `description`, `recorded_quarters` (hyväksytyt tunnit), `quantity_quarters` (laskutettu määrä), `unit_price_cents`, `vat_basis_points`, `net_cents`, `sort_order` ## 15. Vaiheistus @@ -482,11 +487,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)* +### 17.7 Laskuaineisto *(valmis, Fennoa-vienti 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. +- Luonnoksella on laskutuskuukausi (oletuksena kuluva kuukausi), johon asti kk-laskutuksen työt laskutetaan; kuukauden vaihto laskee esikatselun uudelleen (5.5). +- Tulossa: CSV/Excel-vienti Fennoan tuontimuotoon (avoin kysymys 4). ## 18. Avoimet kysymykset diff --git a/lang/fi/billing.php b/lang/fi/billing.php index 3f982b6..e53d690 100644 --- a/lang/fi/billing.php +++ b/lang/fi/billing.php @@ -11,28 +11,32 @@ return [ 'modes' => [ 'hours' => 'Tuntityö', 'fixed_price' => 'Kiinteä hinta', - 'none' => 'Ei laskuteta näin', + 'monthly_fee' => 'Kuukausihinta', + 'none' => 'Ei laskuteta aineistolla', ], 'kinds' => [ 'hours' => 'Tunnit', 'fixed_price' => 'Kiinteä hinta', 'expense' => 'Kulu', + 'monthly_fee' => 'Kuukausihinta', ], 'reasons' => [ 'wrong_status' => 'Työ ei ole valmis.', - 'not_billable_basis' => 'Työtä ei laskuteta aineistolla (ei laskuteta, kuukausilaskutus tai sisäinen asiakas).', + 'not_billable_basis' => 'Työtä ei laskuteta aineistolla (ei laskutettava tai sisäinen asiakas).', + 'missing_monthly_fee' => 'Kuukausilaskutuksen työltä puuttuu kuukausihinta.', '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.', + 'nothing_to_bill' => 'Ei laskutettavaa: ei hyväksyttyjä tunteja, laskuttamattomia kuukausia 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.', + 'monthly_fee_alone' => 'Kuukausilaskutuksen työ laskutetaan omalla laskullaan.', ], 'index' => [ @@ -69,6 +73,9 @@ return [ '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.', + 'period' => 'Laskutuskuukausi', + 'period_help' => 'Kuukausilaskutuksen työt laskutetaan tähän kuukauteen asti, myös väliin jääneet kuukaudet.', + 'period_saved' => 'Laskutuskuukausi on nyt :month.', ], 'invoices' => [ @@ -104,6 +111,10 @@ return [ '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.', + 'monthly_hours' => 'Hyväksytyt tunnit :hours h kuuluvat kuukausihintaan, ja ne merkitään laskutetuiksi.', + 'months_caption' => 'Laskutettavat kuukaudet: :job', + 'month' => 'Kuukausi', + 'no_months' => 'Ei laskuttamattomia kuukausia.', 'no_hours' => 'Ei hyväksyttyjä laskuttamattomia tunteja.', 'expenses_caption' => 'Kulut: :job', 'expense' => 'Kulu', @@ -132,9 +143,9 @@ return [ ], '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ä.', + 'title' => 'Laskutettavat työt', + 'intro' => 'Valmiit työt ja kuukausilaskutuksen työt, joita ei ole luonnoksessa. Jokainen lisätty työ on aluksi oma laskunsa.', + 'none' => 'Ei muita laskutettavia töitä.', 'columns' => [ 'job' => 'Työ', 'customer' => 'Asiakas', @@ -159,5 +170,6 @@ return [ '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.', + 'period' => 'Valitse kuukausi.', ], ]; diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index a4ed2cb..79d41b7 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -129,6 +129,9 @@ return [ 'quoted_amount' => 'Budjetti / tarjoussumma', 'quoted_amount_input' => 'Budjetti / tarjoussumma (€, ALV 0)', 'quoted_amount_description' => 'Veroton summa, esim. 4500. Näkyy vain niille, joilla on oikeus tarjouksiin.', + 'monthly_fee' => 'Kuukausihinta', + 'monthly_fee_input' => 'Kuukausihinta (€, ALV 0)', + 'monthly_fee_description' => 'Laskutetaan laskuaineistolla joka kuukausi työn aloituskuukaudesta alkaen. Näkyy vain niille, joilla on oikeus tarjouksiin.', 'completed_at' => 'Valmistunut', 'customer_reference' => 'Asiakkaan viite (PO)', 'instructions' => 'Ohjeistus', diff --git a/tests/Browser/BillingAccessibilityTest.php b/tests/Browser/BillingAccessibilityTest.php index 028ef18..b50676f 100644 --- a/tests/Browser/BillingAccessibilityTest.php +++ b/tests/Browser/BillingAccessibilityTest.php @@ -1,7 +1,7 @@ create(['customer_job_id' => $this->jobs[0]->id, 'description' => 'Paperi']); - $this->exportId = BillingExportModel::query()->create(['status' => 'draft', 'created_by' => $this->manager->id])->id; + CustomerJobModel::factory()->create([ + 'name' => 'Ylläpito', + 'customer_id' => $customer->id, + 'status' => JobStatus::InProduction, + 'payment_basis' => 'monthly_fee', + 'monthly_fee_cents' => 9900, + 'starts_on' => now()->subMonths(2)->toDateString(), + ]); + + // Opening the draft adds the monthly fee job. + $this->exportId = app(OpenBillingDraft::class)->execute($this->manager->id); }); it('has no accessibility issues on the billing pages', function (string $page, string $device, string $colorScheme) { @@ -59,18 +69,19 @@ it('adds and combines jobs and creates the material', function () { $page->click('[wire\\:click="add('.$first->id.')"]') ->assertSee('lisätty aineistoon') ->click('[wire\\:click="add('.$second->id.')"]') - ->assertSee('Lasku 2: Asiakas Oy') + ->assertSee('Lasku 3: Asiakas Oy') + ->assertSee('Laskutettavat kuukaudet') ->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') + ->assertDontSee('Lasku 3: Asiakas Oy') ->click('Muodosta aineisto') ->assertSee('Muodostetaanko laskuaineisto?') ->assertNoAccessibilityIssues(level: 2) ->click('#finalize-dialog button:last-child') - ->assertSee('Laskuaineisto muodostettu: 1 laskua.') + ->assertSee('Laskuaineisto muodostettu: 2 laskua.') ->assertSee('Laskutetut h') ->assertNoAccessibilityIssues(level: 2); diff --git a/tests/Feature/Modules/Billing/BillingExportTest.php b/tests/Feature/Modules/Billing/BillingExportTest.php index d4f8c8a..eda8676 100644 --- a/tests/Feature/Modules/Billing/BillingExportTest.php +++ b/tests/Feature/Modules/Billing/BillingExportTest.php @@ -225,3 +225,73 @@ it('keeps everyone but management out', function (string $role) { $this->get(route('billing.index'))->assertForbidden(); })->with(['employee', 'intern', 'subcontractor']); + +it('bills every unbilled month of a monthly fee job on an invoice of its own and keeps the job running', function () { + $this->travelTo(now()->setDate(2026, 11, 20)->setTime(12, 0)); + + $maintenance = doneJob([ + 'name' => 'Ylläpito', + 'status' => JobStatus::InProduction, + 'payment_basis' => 'monthly_fee', + 'monthly_fee_cents' => 9900, + 'starts_on' => '2026-09-10', + ], [$this->layout->id => 2]); + ExpenseModel::factory()->create(['customer_job_id' => $maintenance->id, 'description' => 'Lisenssi', 'billed_amount_cents' => 1500]); + $other = doneJob([], [$this->layout->id => 1]); + + $exportId = openDraft(); + + $page = Livewire::test('billing::export', ['export' => $exportId]) + ->assertSee('9/2026') + ->assertSee('Hyväksytyt tunnit 2 h kuuluvat kuukausihintaan') + ->call('savePeriod', '2026-10') + ->assertSet('statusMessage', 'Laskutuskuukausi on nyt 10/2026.') + ->assertDontSee('11/2026') + ->call('savePeriod', '2026-13') + ->assertHasErrors(['period']) + ->call('savePeriod', '2026-11') + ->call('add', $other->id) + ->set("moveTargets.{$other->id}", (string) $maintenance->id) + ->call('move', $other->id) + ->assertSet('errorMessage', 'Kuukausilaskutuksen työ laskutetaan omalla laskullaan.'); + + expect($page->get('export')->invoices)->toHaveCount(2) + ->and($page->get('export')->invoices[0]->mergeTargets[$maintenance->id])->toBe([]); + + $page->call('finalize')->assertSet('errorMessage', ''); + + $monthly = BillingLineModel::query()->where('customer_job_id', $maintenance->id)->orderBy('sort_order')->get(); + expect($monthly->map->only(['kind', 'period', 'net_cents'])->all())->toBe([ + ['kind' => LineKind::MonthlyFee, 'period' => '2026-09', 'net_cents' => 9900], + ['kind' => LineKind::MonthlyFee, 'period' => '2026-10', 'net_cents' => 9900], + ['kind' => LineKind::MonthlyFee, 'period' => '2026-11', 'net_cents' => 9900], + ['kind' => LineKind::Expense, 'period' => null, 'net_cents' => 1500], + ]) + ->and($maintenance->refresh()->status)->toBe(JobStatus::InProduction) + ->and($other->refresh()->status)->toBe(JobStatus::Invoiced) + ->and(TimeEntryModel::query()->where('customer_job_id', $maintenance->id)->value('billing_export_id'))->toBe($exportId); + + // The same month again bills nothing; the next month bills one row. + $next = openDraft(); + expect(DB::table('billing_invoice_jobs')->count())->toBe(2); + + $this->travelTo(now()->setDate(2026, 12, 5)); + Livewire::test('billing::export', ['export' => $next]) + ->assertSee('Ei laskutettavaa') + ->call('savePeriod', '2026-12') + ->call('add', $maintenance->id) + ->assertSet('errorMessage', '') + ->call('finalize'); + + expect(BillingLineModel::query()->where('customer_job_id', $maintenance->id)->where('kind', LineKind::MonthlyFee)->pluck('period')->all()) + ->toBe(['2026-09', '2026-10', '2026-11', '2026-12']); +}); + +it('does not bill a monthly fee job without a monthly fee', function () { + $job = doneJob(['status' => JobStatus::InProduction, 'payment_basis' => 'monthly_fee']); + + Livewire::test('billing::export', ['export' => openDraft()]) + ->assertSee('Kuukausilaskutuksen työltä puuttuu kuukausihinta.') + ->call('add', $job->id) + ->assertSet('errorMessage', fn (string $message) => str_contains($message, 'kuukausihinta')); +}); diff --git a/tests/Feature/Modules/Jobs/JobMoneyFieldsTest.php b/tests/Feature/Modules/Jobs/JobMoneyFieldsTest.php index 218195c..0d96fd2 100644 --- a/tests/Feature/Modules/Jobs/JobMoneyFieldsTest.php +++ b/tests/Feature/Modules/Jobs/JobMoneyFieldsTest.php @@ -91,3 +91,32 @@ it('records when a job is done and clears it when management opens the lock', fu Livewire::test('jobs::board')->set('mine', false)->call('moveJob', $this->job->id, 'in_production'); expect($this->job->refresh()->completed_at)->toBeNull(); }); + +it('keeps the monthly fee of a monthly fee job with its history, behind the quotes permission', function () { + $this->actingAs(User::factory()->management()->create()); + + Livewire::test('jobs::form', ['job' => $this->job->id]) + ->assertDontSee('Kuukausihinta (€, ALV 0)') + ->set('form.payment_basis', 'monthly_fee') + ->assertSee('Kuukausihinta (€, ALV 0)') + ->set('form.monthly_fee', '12,345') + ->call('save') + ->assertHasErrors(['form.monthly_fee' => [__('jobs.errors.invalid_amount')]]) + ->set('form.monthly_fee', '99,90') + ->call('save') + ->assertHasNoErrors(); + + expect($this->job->refresh()->monthly_fee_cents)->toBe(9990); + + $this->get(route('jobs.show', $this->job->id)) + ->assertSee('Kuukausihinta') + ->assertSee("99,90\u{00A0}€", false); + + $this->actingAs(User::factory()->employee()->create()); + + $this->get(route('jobs.show', $this->job->id))->assertDontSee('Kuukausihinta'); + + Livewire::test('jobs::form', ['job' => $this->job->id])->set('form.name', 'Ylläpito')->call('save')->assertHasNoErrors(); + + expect($this->job->refresh()->monthly_fee_cents)->toBe(9990); +}); diff --git a/tests/Unit/Modules/Billing/BillingDraftTest.php b/tests/Unit/Modules/Billing/BillingDraftTest.php index 5037b8d..88ce92c 100644 --- a/tests/Unit/Modules/Billing/BillingDraftTest.php +++ b/tests/Unit/Modules/Billing/BillingDraftTest.php @@ -16,6 +16,7 @@ use App\Modules\Billing\Domain\Exceptions\ExportNotDraft; use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours; use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge; use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft; +use App\Modules\Billing\Domain\ValueObjects\BillingMonths; use App\Modules\Billing\Domain\ValueObjects\DraftJob; use App\Modules\Billing\Domain\ValueObjects\InvoiceLine; use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals; @@ -41,7 +42,10 @@ function billableJob(int $id, BillingMode $mode = BillingMode::Hours, array $ove 'customerReference' => null, 'mode' => $mode, 'quotedAmountCents' => null, - 'isDone' => true, + 'inBillableStatus' => true, + 'monthlyFeeCents' => null, + 'billingStartsOn' => '2026-09-15', + 'billingEndsOn' => null, ], $overrides); return new BillableJob(...$values); @@ -150,7 +154,7 @@ it('tells why a job cannot be billed', function (BillableJob $job, JobHours $hou 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], + 'not done' => [billableJob(1, overrides: ['inBillableStatus' => 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], @@ -163,6 +167,55 @@ it('tells why a job cannot be billed', function (BillableJob $job, JobHours $hou 'fixed price billed before' => [billableJob(1, BillingMode::FixedPrice, ['quotedAmountCents' => 100000]), new JobHours(1, [1 => 4]), [], true, NotBillableReason::NothingToBill], ]); +it('tells why a monthly fee job cannot be billed', function (array $overrides, array $months, array $expenses, ?NotBillableReason $reason) { + $job = billableJob(1, BillingMode::MonthlyFee, $overrides); + + expect((new BillingRules)->reasonNotBillable($job, new JobHours(1, [2 => 8]), $expenses, false, [], $months))->toBe($reason); +})->with([ + 'months to bill' => [['monthlyFeeCents' => 9900], ['2026-11'], [], null], + 'no monthly fee' => [[], ['2026-11'], [], NotBillableReason::MissingMonthlyFee], + 'every month billed' => [['monthlyFeeCents' => 9900], [], [], NotBillableReason::NothingToBill], + 'only expenses' => [['monthlyFeeCents' => 9900], [], [new BillableExpense(5, 1, 'Paperi', 500)], null], + 'not running' => [['monthlyFeeCents' => 9900, 'inBillableStatus' => false], ['2026-11'], [], NotBillableReason::WrongStatus], +]); + +it('bills every unbilled month of a monthly fee job and its expenses, not its hours', function () { + $job = billableJob(1, BillingMode::MonthlyFee, ['name' => 'Ylläpito', 'monthlyFeeCents' => 9900]); + + $lines = (new BillingRules)->lines($job, $job->toDraftJob(), [1 => 8], [new BillableExpense(5, 1, 'Paperi', 500)], false, [1 => new HourlyRate(1, 'Taitto', 8000)], 2550, ['2026-10', '2026-11']); + + expect(array_map(fn (InvoiceLine $line): array => [$line->kind, $line->period, $line->description, $line->netCents], $lines))->toBe([ + [LineKind::MonthlyFee, '2026-10', '10/2026 2026-0001 Ylläpito', 9900], + [LineKind::MonthlyFee, '2026-11', '11/2026 2026-0001 Ylläpito', 9900], + [LineKind::Expense, null, 'Paperi', 500], + ]); +}); + +it('counts the months from the start to the material, the last day or completion, leaving out billed ones', function (?string $endsOn, string $period, array $billed, array $months) { + expect(BillingMonths::unbilled('2026-09-15', $endsOn, $period, $billed))->toBe($months); +})->with([ + 'up to the material' => [null, '2026-11', [], ['2026-09', '2026-10', '2026-11']], + 'billed months left out' => [null, '2026-11', ['2026-09', '2026-10'], ['2026-11']], + 'ends before the material' => ['2026-10-31', '2026-12', [], ['2026-09', '2026-10']], + 'over the year end' => [null, '2027-01', ['2026-09', '2026-10'], ['2026-11', '2026-12', '2027-01']], + 'material before the start' => [null, '2026-08', [], []], +]); + +it('keeps a monthly fee job on an invoice of its own', function () { + $export = draft(); + $export->addJob(new DraftJob(1, 10, null, null)); + $export->addJob(new DraftJob(2, 10, null, null, [], ownInvoice: true)); + + try { + $export->moveJob(2, 1); + $this->fail('The jobs were combined.'); + } catch (InvoicesCannotMerge $exception) { + expect($exception->refusal)->toBe(MergeRefusal::MonthlyFeeAlone); + } + + $export->moveJob(1, 2); +})->throws(InvoicesCannotMerge::class); + 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);