From bc3dbf16a4bcb39d9f002acaec4abfee09121f0c Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Wed, 25 Nov 2026 15:56:15 +0200 Subject: [PATCH] Show a monthly fee job's billed periods on a page of its own The new billing::job-months page lists the months that created billing materials have billed for a monthly fee job, with links to the materials and the total, and the months still to bill up to the current month, counted the same way as a new material counts them. The job page links to it next to the payment basis for those who manage billing. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 2 +- .../Application/Contracts/BillingQueries.php | 8 + .../Billing/Application/DTOs/BilledMonth.php | 24 +++ .../Application/DTOs/MonthlyBillingView.php | 30 ++++ .../Services/MonthlyBillingViews.php | 48 ++++++ .../Repositories/EloquentBillingQueries.php | 31 ++++ .../Livewire/⚡job-months.blade.php | 157 ++++++++++++++++++ .../Billing/Presentation/Routes/web.php | 1 + .../Presentation/Livewire/⚡show.blade.php | 9 +- docs/maarittely.md | 1 + lang/en/billing.php | 29 ++++ lang/en/jobs.php | 1 + lang/fi/billing.php | 29 ++++ lang/fi/jobs.php | 1 + tests/Browser/BillingAccessibilityTest.php | 22 ++- .../Billing/MonthlyBillingPeriodsTest.php | 80 +++++++++ 16 files changed, 470 insertions(+), 3 deletions(-) create mode 100644 app/Modules/Billing/Application/DTOs/BilledMonth.php create mode 100644 app/Modules/Billing/Application/DTOs/MonthlyBillingView.php create mode 100644 app/Modules/Billing/Application/Services/MonthlyBillingViews.php create mode 100644 app/Modules/Billing/Presentation/Livewire/⚡job-months.blade.php create mode 100644 tests/Feature/Modules/Billing/MonthlyBillingPeriodsTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 3b9abfd..b0bd554 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; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); 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 with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, task comments (`jobs::task-comments`: anyone with `jobs.update-task-status` comments, authors edit and remove their own, `jobs.remove-any-task-comment` removes anyone's), task images (`jobs::task-images`, same rules with `jobs.remove-any-task-image`; `GdTaskImageFiles` stores an upright, at most 2560 px JPEG without EXIF and a 400 px thumbnail under `task-images/` on the private `local` disk, served only through `ShowTaskImage` after `jobs.view-job`; `RemoveTask` also deletes the files), and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, filling the working days in order up to the daily maximum (9 h → 7.5 h + 1.5 h) with the rest moved past the period's end; the daily maximum is `shared.daily_capacity_hours` (Shared's `DailyCapacity`, set on the company details page, 7.5 h when empty)) `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 (its running number `billing_exports.number` is reserved only when it is created, so discarded drafts leave no gaps, and a draft has none): 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, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); 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`) and `Reports` (management's reports behind `reports.view`: hours by person, unbilled hours, profitability by job and service unit, quick sales and expense reimbursements, each a `reports::` page with a period in the URL (`ReportPage` trait, `alku`/`loppu`), tables, a `` (TallStackUI's server-side `` as one image) and a CSV from `DownloadReport`; it reads the other modules only through its ports `ReportHours`, `ReportJobs`, `ReportCatalog`, `ReportPeople`, `ReportSales`, `ReportExpenses` and `ReportRevenue`, whose adapters call those modules' report queries (`TimeReportQueries`, `CustomerJobQueries::reportInfoOf`, `QuickSaleReportQueries`, `ExpenseReportQueries`, `BilledRevenueQueries`); hours are costed at the one internal hourly cost `catalog.internal_hourly_cost_cents`, set on the Hinnasto maintenance page)); `/` (route `home`) is the home page of the `Dashboard` module (`dashboard::home`: the user's open tasks on an agenda (late, today and tomorrow, this week), their open jobs, this week's hours and quick links; for admin and management also `dashboard::management`, loaded with `lazy="on-load"` behind `dashboard.management`: things to do, the month so far against the same days of the previous month through the Reports use cases, jobs by status and late work, and everyone's workload from the task calendar against the daily capacity × working days; it reads the other modules through its ports `DashboardWork`, `DashboardTime`, `DashboardAdmin` and `DashboardFigures`, Jobs' `JobOverviewQueries` among them). The layout `resources/views/layouts/app.blade.php` 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; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); 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 with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, task comments (`jobs::task-comments`: anyone with `jobs.update-task-status` comments, authors edit and remove their own, `jobs.remove-any-task-comment` removes anyone's), task images (`jobs::task-images`, same rules with `jobs.remove-any-task-image`; `GdTaskImageFiles` stores an upright, at most 2560 px JPEG without EXIF and a 400 px thumbnail under `task-images/` on the private `local` disk, served only through `ShowTaskImage` after `jobs.view-job`; `RemoveTask` also deletes the files), and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, filling the working days in order up to the daily maximum (9 h → 7.5 h + 1.5 h) with the rest moved past the period's end; the daily maximum is `shared.daily_capacity_hours` (Shared's `DailyCapacity`, set on the company details page, 7.5 h when empty)) `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 (its running number `billing_exports.number` is reserved only when it is created, so discarded drafts leave no gaps, and a draft has none): 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, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); a monthly fee job's billed periods (its `monthly_fee` billing lines on created materials, with the months still to bill up to now through `MonthlyBillingViews`) on `billing::job-months`, linked from the job page's payment basis for `billing.manage`; 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`) and `Reports` (management's reports behind `reports.view`: hours by person, unbilled hours, profitability by job and service unit, quick sales and expense reimbursements, each a `reports::` page with a period in the URL (`ReportPage` trait, `alku`/`loppu`), tables, a `` (TallStackUI's server-side `` as one image) and a CSV from `DownloadReport`; it reads the other modules only through its ports `ReportHours`, `ReportJobs`, `ReportCatalog`, `ReportPeople`, `ReportSales`, `ReportExpenses` and `ReportRevenue`, whose adapters call those modules' report queries (`TimeReportQueries`, `CustomerJobQueries::reportInfoOf`, `QuickSaleReportQueries`, `ExpenseReportQueries`, `BilledRevenueQueries`); hours are costed at the one internal hourly cost `catalog.internal_hourly_cost_cents`, set on the Hinnasto maintenance page)); `/` (route `home`) is the home page of the `Dashboard` module (`dashboard::home`: the user's open tasks on an agenda (late, today and tomorrow, this week), their open jobs, this week's hours and quick links; for admin and management also `dashboard::management`, loaded with `lazy="on-load"` behind `dashboard.management`: things to do, the month so far against the same days of the previous month through the Reports use cases, jobs by status and late work, and everyone's workload from the task calendar against the daily capacity × working days; it reads the other modules through its ports `DashboardWork`, `DashboardTime`, `DashboardAdmin` and `DashboardFigures`, Jobs' `JobOverviewQueries` among them). The layout `resources/views/layouts/app.blade.php` 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 is in Finnish. The UI is in Finnish (default) and English: every UI string lives in `lang/fi/*.php` **and** `lang/en/*.php` with the same keys and placeholders (`tests/Unit/TranslationFilesTest.php` fails otherwise). Number, money and date formats stay Finnish in both languages; the quick sale receipt is always Finnish. diff --git a/app/Modules/Billing/Application/Contracts/BillingQueries.php b/app/Modules/Billing/Application/Contracts/BillingQueries.php index 956906d..28b6130 100644 --- a/app/Modules/Billing/Application/Contracts/BillingQueries.php +++ b/app/Modules/Billing/Application/Contracts/BillingQueries.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Modules\Billing\Application\Contracts; +use App\Modules\Billing\Application\DTOs\BilledMonth; use App\Modules\Billing\Application\DTOs\ExportSummary; /** @@ -17,4 +18,11 @@ interface BillingQueries * @return list */ public function exports(): array; + + /** + * The monthly fee months of a job billed on created materials, oldest first. + * + * @return list + */ + public function billedMonthsOf(int $jobId): array; } diff --git a/app/Modules/Billing/Application/DTOs/BilledMonth.php b/app/Modules/Billing/Application/DTOs/BilledMonth.php new file mode 100644 index 0000000..95d2ce5 --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/BilledMonth.php @@ -0,0 +1,24 @@ + $billed Oldest first. + * @param list $unbilled Y-m, oldest first, up to the current month. + * @param string|null $billingEndsOn Y-m-d: the job's last day or completion day, after which nothing is billed. + */ + public function __construct( + public BillableJob $job, + public array $billed, + public array $unbilled, + public string $currentMonth, + public ?string $billingEndsOn, + ) {} + + public function billedNetCents(): int + { + return array_sum(array_map(fn (BilledMonth $month): int => $month->netCents, $this->billed)); + } +} diff --git a/app/Modules/Billing/Application/Services/MonthlyBillingViews.php b/app/Modules/Billing/Application/Services/MonthlyBillingViews.php new file mode 100644 index 0000000..e2d6a41 --- /dev/null +++ b/app/Modules/Billing/Application/Services/MonthlyBillingViews.php @@ -0,0 +1,48 @@ +jobs->find([$jobId])[$jobId] ?? null; + + if ($job === null || $job->mode !== BillingMode::MonthlyFee) { + return null; + } + + $billed = $this->queries->billedMonthsOf($jobId); + $currentMonth = $this->clock->today()->format('Y-m'); + $unbilled = $job->billingStartsOn === '' + ? [] + : BillingMonths::unbilled($job->billingStartsOn, $job->billingEndsOn, $currentMonth, array_map(fn (BilledMonth $month): string => $month->month, $billed)); + + return new MonthlyBillingView($job, $billed, $unbilled, $currentMonth, $job->billingEndsOn); + } +} diff --git a/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingQueries.php b/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingQueries.php index 53d27fa..0bc55c5 100644 --- a/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingQueries.php +++ b/app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBillingQueries.php @@ -3,13 +3,16 @@ namespace App\Modules\Billing\Infrastructure\Persistence\Repositories; use App\Modules\Billing\Application\Contracts\BillingQueries; +use App\Modules\Billing\Application\DTOs\BilledMonth; use App\Modules\Billing\Application\DTOs\ExportSummary; use App\Modules\Billing\Domain\Enums\ExportStatus; +use App\Modules\Billing\Domain\Enums\LineKind; use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel; use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingInvoiceJobModel; use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingLineModel; use App\Modules\Users\Application\Contracts\UserAccountQueries; use DateTimeImmutable; +use DateTimeZone; class EloquentBillingQueries implements BillingQueries { @@ -54,4 +57,32 @@ class EloquentBillingQueries implements BillingQueries $model->status === ExportStatus::Created ? (int) ($netSums[$model->id] ?? 0) : null, ))->values()->all(); } + + public function billedMonthsOf(int $jobId): array + { + return BillingLineModel::query() + ->join('billing_invoices', 'billing_invoices.id', '=', 'billing_lines.billing_invoice_id') + ->join('billing_exports', 'billing_exports.id', '=', 'billing_invoices.billing_export_id') + ->where('billing_lines.customer_job_id', $jobId) + ->where('billing_lines.kind', LineKind::MonthlyFee) + ->whereNotNull('billing_lines.period') + ->where('billing_exports.status', ExportStatus::Created) + ->orderBy('billing_lines.period') + ->get([ + 'billing_lines.period', + 'billing_lines.net_cents', + 'billing_exports.id as export_id', + 'billing_exports.number as export_number', + 'billing_exports.finalized_at', + ]) + ->map(fn (BillingLineModel $line): BilledMonth => new BilledMonth( + (string) $line->getAttribute('period'), + (int) $line->getAttribute('export_id'), + (int) $line->getAttribute('export_number'), + $line->getAttribute('finalized_at') === null ? null : new DateTimeImmutable((string) $line->getAttribute('finalized_at'), new DateTimeZone('UTC')), + $line->net_cents, + )) + ->values() + ->all(); + } } diff --git a/app/Modules/Billing/Presentation/Livewire/⚡job-months.blade.php b/app/Modules/Billing/Presentation/Livewire/⚡job-months.blade.php new file mode 100644 index 0000000..0820ead --- /dev/null +++ b/app/Modules/Billing/Presentation/Livewire/⚡job-months.blade.php @@ -0,0 +1,157 @@ +authorize('billing.manage'); + $this->jobId = $job; + + if (app(MonthlyBillingViews::class)->forJob($job) === null) { + abort(404); + } + } + + #[Computed] + public function billing(): MonthlyBillingView + { + return app(MonthlyBillingViews::class)->forJob($this->jobId) ?? abort(404); + } + + public function monthLabel(string $month): string + { + return BillingMonths::label($month); + } + + public function dayLabel(string $date): string + { + return (new DateTimeImmutable($date))->format('j.n.Y'); + } + + public function heading(): string + { + return __('billing.job_months.title', ['job' => $this->billing->job->number.' '.$this->billing->job->name]); + } + + /** + * @return list + */ + public function headers(): array + { + return [ + ['index' => 'month', 'label' => __('billing.job_months.columns.month'), 'sortable' => false], + ['index' => 'export', 'label' => __('billing.job_months.columns.export'), 'sortable' => false], + ['index' => 'finalized', 'label' => __('billing.job_months.columns.finalized'), 'sortable' => false], + ['index' => 'net', 'label' => __('billing.job_months.columns.net'), 'sortable' => false, 'align' => 'right'], + ]; + } + + public function render(): mixed + { + return $this->view()->title($this->heading()); + } +}; +?> + +@php($billing = $this->billing) +@php($job = $billing->job) + +
+
+

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

+

{{ $this->heading() }}

+

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

+
+ +
+

{{ __('billing.job_months.summary') }}

+
+
{{ __('billing.job_months.customer') }}
+
{{ $job->customerName }}
+ +
{{ __('billing.job_months.monthly_fee') }}
+
{{ $job->monthlyFeeCents === null ? __('billing.job_months.no_fee') : $this->money($job->monthlyFeeCents).' '.__('billing.job_months.vat_excluded') }}
+ +
{{ __('billing.job_months.starts') }}
+
{{ $job->billingStartsOn === '' ? '–' : $this->monthLabel(substr($job->billingStartsOn, 0, 7)) }}
+ +
{{ __('billing.job_months.ends') }}
+
{{ $billing->billingEndsOn === null ? __('billing.job_months.no_end') : $this->dayLabel($billing->billingEndsOn) }}
+ +
{{ __('billing.job_months.billing_unit') }}
+
{{ $job->billingUnitName ?? __('billing.invoices.no_billing_unit') }}
+
+ + @if (! $job->inBillableStatus) +

+

+ @endif +
+ +
+

{{ __('billing.job_months.billed_title', ['count' => count($billing->billed)]) }}

+ + @if ($billing->billed === []) +

{{ __('billing.job_months.none_billed') }}

+ @else + + @interact('column_month', $month) + {{ $this->monthLabel($month->month) }} + @endinteract + + @interact('column_export', $month) + {{ __('billing.index.export_label', ['number' => $month->exportNumber]) }} + @endinteract + + @interact('column_finalized', $month) + {{ $month->finalizedAt === null ? '' : $this->timeLabel($month->finalizedAt) }} + @endinteract + + @interact('column_net', $month) + {{ $this->money($month->netCents) }} + @endinteract + + +

{{ __('billing.job_months.billed_total', ['net' => $this->money($billing->billedNetCents())]) }}

+ @endif +
+ +
+

{{ __('billing.job_months.unbilled_title', ['month' => $this->monthLabel($billing->currentMonth)]) }}

+ + @if ($billing->unbilled === []) +

+

+ @else +
    + @foreach ($billing->unbilled as $month) +
  • {{ $this->monthLabel($month) }}
  • + @endforeach +
+

{{ __('billing.job_months.unbilled_help') }}

+ @endif +
+
diff --git a/app/Modules/Billing/Presentation/Routes/web.php b/app/Modules/Billing/Presentation/Routes/web.php index ea3f743..dc408f8 100644 --- a/app/Modules/Billing/Presentation/Routes/web.php +++ b/app/Modules/Billing/Presentation/Routes/web.php @@ -10,4 +10,5 @@ Route::middleware(['web', 'auth', 'can:billing.manage']) Route::livewire('/', 'billing::index')->name('index'); Route::livewire('/{export}', 'billing::export')->whereNumber('export')->name('export'); Route::get('/{export}/csv', DownloadBillingCsv::class)->whereNumber('export')->name('csv'); + Route::livewire('/jobs/{job}/months', 'billing::job-months')->whereNumber('job')->name('job-months'); }); diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index 31a587e..ef16d65 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -248,7 +248,14 @@ new class extends Component
{{ __('jobs.kinds.'.$job->kind->value) }}
{{ __('jobs.fields.payment_basis') }}
-
{{ $job->paymentBasis === null ? __('jobs.not_set') : __('jobs.payment_bases.'.$job->paymentBasis->value) }}
+
+ {{ $job->paymentBasis === null ? __('jobs.not_set') : __('jobs.payment_bases.'.$job->paymentBasis->value) }} + @if ($job->paymentBasis?->value === 'monthly_fee') + @can('billing.manage') + {{ __('jobs.monthly_billing_link') }} + @endcan + @endif +
{{ __('jobs.fields.estimated_hours') }}
{{ $job->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $job->estimatedHours).' h' }}
diff --git a/docs/maarittely.md b/docs/maarittely.md index 5a6630f..50b6859 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -187,6 +187,7 @@ Toistaiseksi jatkuvalle työlle, jonka maksuperuste on kiinteä kk-laskutus, syn - 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)*. +- **Laskutetut kaudet** *(valmis)*: kk-laskutuksen työn sivulla on maksuperusteen vieressä linkki "Laskutetut kaudet" (pääkäyttäjä ja johto, `/billing/jobs/{työ}/months`). Sivulla näkyvät kuukausihinta, laskutuksen alku ja loppu, muodostettujen aineistojen laskuttamat kuukaudet (kausi, aineisto linkkinä, muodostusaika, veroton summa ja yhteissumma) sekä kuukaudet, jotka ovat vielä laskuttamatta kuluvaan kuukauteen mennessä. Laskutettu kuukausi tunnistetaan aineiston kuukausihintarivistä (`billing_lines.period`). - 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 diff --git a/lang/en/billing.php b/lang/en/billing.php index 4242c94..38dab48 100644 --- a/lang/en/billing.php +++ b/lang/en/billing.php @@ -80,6 +80,35 @@ return [ 'draft_label' => 'Draft', ], + 'job_months' => [ + 'title' => 'Billed periods: :job', + 'back' => 'Back to the customer job', + 'intro' => 'A monthly fee job is billed for every month from its start month. Created billing materials mark the months billed, and no month is billed twice.', + 'summary' => 'Monthly billing details', + 'customer' => 'Customer', + 'monthly_fee' => 'Monthly fee', + 'no_fee' => 'Not set: the job is not billed until a monthly fee is given.', + 'vat_excluded' => '(excl. VAT)', + 'starts' => 'Billing starts', + 'ends' => 'Billing ends', + 'no_end' => 'Until further notice', + 'billing_unit' => 'Billing unit', + 'not_running' => 'The job is not in Order, In production, On hold or Done, so new billing materials do not bill its months.', + 'billed_title' => 'Billed months (:count)', + 'none_billed' => 'No month has been billed yet.', + 'billed_total' => 'Billed in total :net (excl. VAT).', + 'columns' => [ + 'month' => 'Period', + 'export' => 'Billing material', + 'finalized' => 'Created', + 'net' => 'Net', + ], + 'unbilled_title' => 'Unbilled up to :month', + 'unbilled_list' => 'Unbilled months', + 'none_unbilled' => 'Every month up to this month has been billed.', + 'unbilled_help' => 'These months go on the next billing material whose billing month is at or after them.', + ], + 'export' => [ 'title' => 'Billing material :number', 'draft_title' => 'Billing material draft', diff --git a/lang/en/jobs.php b/lang/en/jobs.php index 637d747..527ae07 100644 --- a/lang/en/jobs.php +++ b/lang/en/jobs.php @@ -11,6 +11,7 @@ return [ 'cancel' => 'Cancel', 'created' => 'Customer job :number :name created.', 'updated' => 'Details of customer job :number saved.', + 'monthly_billing_link' => 'Billed periods', 'not_set' => '–', 'late' => 'Late', 'opens_in_new_tab' => 'opens in a new tab', diff --git a/lang/fi/billing.php b/lang/fi/billing.php index cfd2c68..c40092f 100644 --- a/lang/fi/billing.php +++ b/lang/fi/billing.php @@ -80,6 +80,35 @@ return [ 'draft_label' => 'Luonnos', ], + 'job_months' => [ + 'title' => 'Laskutetut kaudet: :job', + 'back' => 'Takaisin asiakastyöhön', + 'intro' => 'Kiinteän kk-laskutuksen työ laskutetaan jokaiselta kuukaudelta aloituskuukaudesta alkaen. Muodostetut laskuaineistot merkitsevät kuukaudet laskutetuiksi, eikä samaa kuukautta laskuteta kahdesti.', + 'summary' => 'Kuukausilaskutuksen tiedot', + 'customer' => 'Asiakas', + 'monthly_fee' => 'Kuukausihinta', + 'no_fee' => 'Ei asetettu: työtä ei laskuteta ennen kuin kuukausihinta on annettu.', + 'vat_excluded' => '(ALV 0)', + 'starts' => 'Laskutus alkaa', + 'ends' => 'Laskutus päättyy', + 'no_end' => 'Toistaiseksi', + 'billing_unit' => 'Laskutusyksikkö', + 'not_running' => 'Työ ei ole tilassa Tilaus, Tuotannossa, Keskeytetty tai Valmis, joten uusiin laskuaineistoihin ei tule sen kuukausia.', + 'billed_title' => 'Laskutetut kuukaudet (:count)', + 'none_billed' => 'Mitään kuukautta ei ole vielä laskutettu.', + 'billed_total' => 'Laskutettu yhteensä :net (ALV 0).', + 'columns' => [ + 'month' => 'Kausi', + 'export' => 'Laskuaineisto', + 'finalized' => 'Muodostettu', + 'net' => 'Veroton', + ], + 'unbilled_title' => 'Laskuttamatta kuukauteen :month mennessä', + 'unbilled_list' => 'Laskuttamattomat kuukaudet', + 'none_unbilled' => 'Kaikki kuukaudet tähän kuukauteen asti on laskutettu.', + 'unbilled_help' => 'Nämä kuukaudet tulevat seuraavaan laskuaineistoon, jonka laskutuskuukausi on niiden kohdalla tai myöhemmin.', + ], + 'export' => [ 'title' => 'Laskuaineisto :number', 'draft_title' => 'Laskuaineiston luonnos', diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index 913c6b0..5b0e2aa 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -11,6 +11,7 @@ return [ 'cancel' => 'Peruuta', 'created' => 'Asiakastyö :number :name luotu.', 'updated' => 'Asiakastyön :number tiedot tallennettu.', + 'monthly_billing_link' => 'Laskutetut kaudet', 'not_set' => '–', 'late' => 'Myöhässä', 'opens_in_new_tab' => 'avautuu uuteen välilehteen', diff --git a/tests/Browser/BillingAccessibilityTest.php b/tests/Browser/BillingAccessibilityTest.php index 3821f38..48d4395 100644 --- a/tests/Browser/BillingAccessibilityTest.php +++ b/tests/Browser/BillingAccessibilityTest.php @@ -1,6 +1,7 @@ create(['customer_job_id' => $this->jobs[0]->id, 'description' => 'Paperi']); - CustomerJobModel::factory()->create([ + $this->monthly = CustomerJobModel::factory()->create([ 'name' => 'Ylläpito', 'customer_id' => $customer->id, 'status' => JobStatus::InProduction, @@ -61,6 +62,25 @@ it('has no accessibility issues on the billing pages', function (string $page, s 'mobile, dark' => ['mobile', 'dark'], ]); +it('has no accessibility issues on the billed periods page', function (string $device, string $colorScheme) { + // The draft holds only the monthly fee job, so creating it bills the job's months up to now. + app(FinalizeBillingExport::class)->execute($this->exportId, $this->manager->id); + + $visit = visit(route('billing.job-months', $this->monthly->id)); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertSee('Laskutetut kuukaudet (3)') + ->assertSee('Aineisto 1') + ->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2); +})->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); + it('adds and combines jobs and creates the material', function () { [$first, $second] = $this->jobs; diff --git a/tests/Feature/Modules/Billing/MonthlyBillingPeriodsTest.php b/tests/Feature/Modules/Billing/MonthlyBillingPeriodsTest.php new file mode 100644 index 0000000..614cd1b --- /dev/null +++ b/tests/Feature/Modules/Billing/MonthlyBillingPeriodsTest.php @@ -0,0 +1,80 @@ +manager = User::factory()->management()->create(); + $this->actingAs($this->manager); + $this->travelTo(now()->setDate(2026, 11, 20)->setTime(12, 0)); + + $this->maintenance = CustomerJobModel::factory()->create([ + 'name' => 'Somen ylläpito', + 'customer_id' => CustomerModel::factory()->company()->create(['name' => 'Kahvila Oy'])->id, + 'status' => JobStatus::InProduction, + 'payment_basis' => 'monthly_fee', + 'monthly_fee_cents' => 39000, + 'starts_on' => '2026-09-10', + ]); +}); + +/** + * Creates a billing material whose billing month is the given month, with the monthly fee jobs on it. + */ +function createMonthlyMaterial(string $period): void +{ + Livewire::test('billing::index')->call('openDraftNow'); + $exportId = (int) BillingExportModel::query()->where('status', ExportStatus::Draft)->value('id'); + + Livewire::test('billing::export', ['export' => $exportId]) + ->call('savePeriod', $period) + ->call('finalize') + ->assertSet('errorMessage', ''); +} + +it('lists the billed months with their billing material and the months still to bill', function () { + createMonthlyMaterial('2026-10'); + $this->travelTo(now()->setDate(2026, 12, 5)); + + Livewire::test('billing::job-months', ['job' => $this->maintenance->id]) + ->assertSeeInOrder(['Laskutetut kuukaudet (2)', '9/2026', 'Aineisto 1', '390,00', '10/2026', 'Aineisto 1', 'Laskutettu yhteensä 780,00']) + ->assertSeeInOrder(['Laskuttamatta kuukauteen 12/2026 mennessä', '11/2026', '12/2026']); +}); + +it('shows a job with every month billed and one with none billed', function () { + Livewire::test('billing::job-months', ['job' => $this->maintenance->id]) + ->assertSee('Mitään kuukautta ei ole vielä laskutettu.') + ->assertSeeInOrder(['9/2026', '10/2026', '11/2026']); + + createMonthlyMaterial('2026-11'); + + Livewire::test('billing::job-months', ['job' => $this->maintenance->id]) + ->assertSee('Kaikki kuukaudet tähän kuukauteen asti on laskutettu.'); +}); + +it('links a monthly fee job to its billed periods for management only', function () { + $hourly = CustomerJobModel::factory()->create(['payment_basis' => 'hourly']); + $link = route('billing.job-months', $this->maintenance->id); + + $this->get(route('jobs.show', $this->maintenance))->assertSee($link, false)->assertSee('Laskutetut kaudet'); + $this->get(route('jobs.show', $hourly))->assertDontSee('Laskutetut kaudet'); + + $this->actingAs(User::factory()->employee()->create()); + $this->get(route('jobs.show', $this->maintenance))->assertOk()->assertDontSee($link, false); + $this->get($link)->assertForbidden(); +}); + +it('has no billed periods page for a job that is not billed by a monthly fee', function () { + $hourly = CustomerJobModel::factory()->create(['payment_basis' => 'hourly']); + + $this->get(route('billing.job-months', $hourly))->assertNotFound(); + $this->get(route('billing.job-months', 999999))->assertNotFound(); +});