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 <[email protected]>
This commit is contained in:
2026-11-25 15:56:15 +02:00
co-authored by Claude Sonnet 5.5
parent e817cca329
commit bc3dbf16a4
16 changed files with 470 additions and 3 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Modules\Billing\Application\Contracts; namespace App\Modules\Billing\Application\Contracts;
use App\Modules\Billing\Application\DTOs\BilledMonth;
use App\Modules\Billing\Application\DTOs\ExportSummary; use App\Modules\Billing\Application\DTOs\ExportSummary;
/** /**
@@ -17,4 +18,11 @@ interface BillingQueries
* @return list<ExportSummary> * @return list<ExportSummary>
*/ */
public function exports(): array; public function exports(): array;
/**
* The monthly fee months of a job billed on created materials, oldest first.
*
* @return list<BilledMonth>
*/
public function billedMonthsOf(int $jobId): array;
} }
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
use DateTimeImmutable;
/**
* One month of a monthly fee job billed on a created billing material.
*/
final readonly class BilledMonth
{
/**
* @param string $month Y-m.
*/
public function __construct(
public string $month,
public int $exportId,
public int $exportNumber,
public ?DateTimeImmutable $finalizedAt,
public int $netCents,
) {}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
/**
* The billing periods of a monthly fee job: the months billed on created
* materials and the months still to bill up to the current month.
*/
final readonly class MonthlyBillingView
{
/**
* @param list<BilledMonth> $billed Oldest first.
* @param list<string> $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));
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Services;
use App\Modules\Billing\Application\Contracts\BillingJobs;
use App\Modules\Billing\Application\Contracts\BillingQueries;
use App\Modules\Billing\Application\DTOs\BilledMonth;
use App\Modules\Billing\Application\DTOs\MonthlyBillingView;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Billing\Domain\ValueObjects\BillingMonths;
use App\Modules\Users\Application\Contracts\Clock;
/**
* The billing periods of a monthly fee job (spec 5.5): which months the
* created billing materials have billed, and which months from the job's
* start up to the current month are still to bill, the same way a new
* material counts them.
*/
final class MonthlyBillingViews
{
public function __construct(
private BillingJobs $jobs,
private BillingQueries $queries,
private Clock $clock,
) {}
/**
* Null when the job does not exist or is not billed by a monthly fee.
*/
public function forJob(int $jobId): ?MonthlyBillingView
{
$job = $this->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);
}
}
@@ -3,13 +3,16 @@
namespace App\Modules\Billing\Infrastructure\Persistence\Repositories; namespace App\Modules\Billing\Infrastructure\Persistence\Repositories;
use App\Modules\Billing\Application\Contracts\BillingQueries; 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\Application\DTOs\ExportSummary;
use App\Modules\Billing\Domain\Enums\ExportStatus; 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\BillingExportModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingInvoiceJobModel; use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingInvoiceJobModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingLineModel; use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingLineModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries; use App\Modules\Users\Application\Contracts\UserAccountQueries;
use DateTimeImmutable; use DateTimeImmutable;
use DateTimeZone;
class EloquentBillingQueries implements BillingQueries class EloquentBillingQueries implements BillingQueries
{ {
@@ -54,4 +57,32 @@ class EloquentBillingQueries implements BillingQueries
$model->status === ExportStatus::Created ? (int) ($netSums[$model->id] ?? 0) : null, $model->status === ExportStatus::Created ? (int) ($netSums[$model->id] ?? 0) : null,
))->values()->all(); ))->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();
}
} }
@@ -0,0 +1,157 @@
<?php
use App\Modules\Billing\Application\DTOs\MonthlyBillingView;
use App\Modules\Billing\Application\Services\MonthlyBillingViews;
use App\Modules\Billing\Domain\ValueObjects\BillingMonths;
use App\Modules\Billing\Presentation\Livewire\Concerns\FormatsBilling;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* The billing periods of a monthly fee job (spec 5.5): the months billed
* on created billing materials, with links to them, and the months from
* the job's start up to the current month that are still to bill.
* Management only.
*/
new class extends Component
{
use FormatsBilling;
#[Locked]
public int $jobId = 0;
public function mount(int $job): void
{
$this->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<array{index: string, label: string, sortable: bool, align?: string}>
*/
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)
<div class="mx-auto max-w-4xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<p><x-link :href="route('jobs.show', $job->id)" navigate>{{ __('billing.job_months.back') }}</x-link></p>
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="max-w-3xl text-sm">{{ __('billing.job_months.intro') }}</p>
</div>
<section aria-labelledby="summary-heading" class="space-y-2">
<h2 id="summary-heading" class="sr-only">{{ __('billing.job_months.summary') }}</h2>
<dl class="grid grid-cols-1 gap-x-6 gap-y-1 text-sm sm:grid-cols-[auto_1fr]">
<dt class="font-medium">{{ __('billing.job_months.customer') }}</dt>
<dd>{{ $job->customerName }}</dd>
<dt class="font-medium">{{ __('billing.job_months.monthly_fee') }}</dt>
<dd>{{ $job->monthlyFeeCents === null ? __('billing.job_months.no_fee') : $this->money($job->monthlyFeeCents).' '.__('billing.job_months.vat_excluded') }}</dd>
<dt class="font-medium">{{ __('billing.job_months.starts') }}</dt>
<dd>{{ $job->billingStartsOn === '' ? '–' : $this->monthLabel(substr($job->billingStartsOn, 0, 7)) }}</dd>
<dt class="font-medium">{{ __('billing.job_months.ends') }}</dt>
<dd>{{ $billing->billingEndsOn === null ? __('billing.job_months.no_end') : $this->dayLabel($billing->billingEndsOn) }}</dd>
<dt class="font-medium">{{ __('billing.job_months.billing_unit') }}</dt>
<dd>{{ $job->billingUnitName ?? __('billing.invoices.no_billing_unit') }}</dd>
</dl>
@if (! $job->inBillableStatus)
<p class="flex items-center gap-1 text-sm font-medium">
<x-icon name="information-circle" class="size-5 shrink-0" aria-hidden="true" />
{{ __('billing.job_months.not_running') }}
</p>
@endif
</section>
<section aria-labelledby="billed-heading" class="space-y-3">
<h2 id="billed-heading" class="text-xl font-semibold">{{ __('billing.job_months.billed_title', ['count' => count($billing->billed)]) }}</h2>
@if ($billing->billed === [])
<p class="text-sm">{{ __('billing.job_months.none_billed') }}</p>
@else
<x-table :headers="$this->headers()" :rows="$billing->billed">
@interact('column_month', $month)
<span class="whitespace-nowrap">{{ $this->monthLabel($month->month) }}</span>
@endinteract
@interact('column_export', $month)
<x-link :href="route('billing.export', $month->exportId)" navigate>{{ __('billing.index.export_label', ['number' => $month->exportNumber]) }}</x-link>
@endinteract
@interact('column_finalized', $month)
<span class="whitespace-nowrap">{{ $month->finalizedAt === null ? '' : $this->timeLabel($month->finalizedAt) }}</span>
@endinteract
@interact('column_net', $month)
<span class="whitespace-nowrap">{{ $this->money($month->netCents) }}</span>
@endinteract
</x-table>
<p class="text-sm font-medium">{{ __('billing.job_months.billed_total', ['net' => $this->money($billing->billedNetCents())]) }}</p>
@endif
</section>
<section aria-labelledby="unbilled-heading" class="space-y-3">
<h2 id="unbilled-heading" class="text-xl font-semibold">{{ __('billing.job_months.unbilled_title', ['month' => $this->monthLabel($billing->currentMonth)]) }}</h2>
@if ($billing->unbilled === [])
<p class="flex items-center gap-1 text-sm">
<x-icon name="check-circle" class="size-5 shrink-0" aria-hidden="true" />
{{ __('billing.job_months.none_unbilled') }}
</p>
@else
<ul class="flex flex-wrap gap-2" aria-label="{{ __('billing.job_months.unbilled_list') }}">
@foreach ($billing->unbilled as $month)
<li class="rounded-md border border-zinc-300 px-3 py-1 text-sm dark:border-zinc-600">{{ $this->monthLabel($month) }}</li>
@endforeach
</ul>
<p class="text-sm">{{ __('billing.job_months.unbilled_help') }}</p>
@endif
</section>
</div>
@@ -10,4 +10,5 @@ Route::middleware(['web', 'auth', 'can:billing.manage'])
Route::livewire('/', 'billing::index')->name('index'); Route::livewire('/', 'billing::index')->name('index');
Route::livewire('/{export}', 'billing::export')->whereNumber('export')->name('export'); Route::livewire('/{export}', 'billing::export')->whereNumber('export')->name('export');
Route::get('/{export}/csv', DownloadBillingCsv::class)->whereNumber('export')->name('csv'); Route::get('/{export}/csv', DownloadBillingCsv::class)->whereNumber('export')->name('csv');
Route::livewire('/jobs/{job}/months', 'billing::job-months')->whereNumber('job')->name('job-months');
}); });
@@ -248,7 +248,14 @@ new class extends Component
<dd>{{ __('jobs.kinds.'.$job->kind->value) }}</dd> <dd>{{ __('jobs.kinds.'.$job->kind->value) }}</dd>
<dt class="font-medium">{{ __('jobs.fields.payment_basis') }}</dt> <dt class="font-medium">{{ __('jobs.fields.payment_basis') }}</dt>
<dd>{{ $job->paymentBasis === null ? __('jobs.not_set') : __('jobs.payment_bases.'.$job->paymentBasis->value) }}</dd> <dd>
{{ $job->paymentBasis === null ? __('jobs.not_set') : __('jobs.payment_bases.'.$job->paymentBasis->value) }}
@if ($job->paymentBasis?->value === 'monthly_fee')
@can('billing.manage')
<x-link :href="route('billing.job-months', $job->id)" navigate class="ml-2">{{ __('jobs.monthly_billing_link') }}</x-link>
@endcan
@endif
</dd>
<dt class="font-medium">{{ __('jobs.fields.estimated_hours') }}</dt> <dt class="font-medium">{{ __('jobs.fields.estimated_hours') }}</dt>
<dd>{{ $job->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $job->estimatedHours).' h' }}</dd> <dd>{{ $job->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $job->estimatedHours).' h' }}</dd>
+1
View File
@@ -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)*. - 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)*. - 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)*. - 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 ### 5.6 Jäsenet
+29
View File
@@ -80,6 +80,35 @@ return [
'draft_label' => 'Draft', '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' => [ 'export' => [
'title' => 'Billing material :number', 'title' => 'Billing material :number',
'draft_title' => 'Billing material draft', 'draft_title' => 'Billing material draft',
+1
View File
@@ -11,6 +11,7 @@ return [
'cancel' => 'Cancel', 'cancel' => 'Cancel',
'created' => 'Customer job :number :name created.', 'created' => 'Customer job :number :name created.',
'updated' => 'Details of customer job :number saved.', 'updated' => 'Details of customer job :number saved.',
'monthly_billing_link' => 'Billed periods',
'not_set' => '–', 'not_set' => '–',
'late' => 'Late', 'late' => 'Late',
'opens_in_new_tab' => 'opens in a new tab', 'opens_in_new_tab' => 'opens in a new tab',
+29
View File
@@ -80,6 +80,35 @@ return [
'draft_label' => 'Luonnos', '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' => [ 'export' => [
'title' => 'Laskuaineisto :number', 'title' => 'Laskuaineisto :number',
'draft_title' => 'Laskuaineiston luonnos', 'draft_title' => 'Laskuaineiston luonnos',
+1
View File
@@ -11,6 +11,7 @@ return [
'cancel' => 'Peruuta', 'cancel' => 'Peruuta',
'created' => 'Asiakastyö :number :name luotu.', 'created' => 'Asiakastyö :number :name luotu.',
'updated' => 'Asiakastyön :number tiedot tallennettu.', 'updated' => 'Asiakastyön :number tiedot tallennettu.',
'monthly_billing_link' => 'Laskutetut kaudet',
'not_set' => '–', 'not_set' => '–',
'late' => 'Myöhässä', 'late' => 'Myöhässä',
'opens_in_new_tab' => 'avautuu uuteen välilehteen', 'opens_in_new_tab' => 'avautuu uuteen välilehteen',
+21 -1
View File
@@ -1,6 +1,7 @@
<?php <?php
use App\Models\User; use App\Models\User;
use App\Modules\Billing\Application\UseCases\FinalizeBillingExport;
use App\Modules\Billing\Application\UseCases\OpenBillingDraft; use App\Modules\Billing\Application\UseCases\OpenBillingDraft;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
@@ -31,7 +32,7 @@ beforeEach(function () {
ExpenseModel::factory()->create(['customer_job_id' => $this->jobs[0]->id, 'description' => 'Paperi']); ExpenseModel::factory()->create(['customer_job_id' => $this->jobs[0]->id, 'description' => 'Paperi']);
CustomerJobModel::factory()->create([ $this->monthly = CustomerJobModel::factory()->create([
'name' => 'Ylläpito', 'name' => 'Ylläpito',
'customer_id' => $customer->id, 'customer_id' => $customer->id,
'status' => JobStatus::InProduction, 'status' => JobStatus::InProduction,
@@ -61,6 +62,25 @@ it('has no accessibility issues on the billing pages', function (string $page, s
'mobile, dark' => ['mobile', 'dark'], '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 () { it('adds and combines jobs and creates the material', function () {
[$first, $second] = $this->jobs; [$first, $second] = $this->jobs;
@@ -0,0 +1,80 @@
<?php
use App\Models\User;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->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();
});