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 <[email protected]>
This commit is contained in:
2026-11-24 13:23:46 +02:00
co-authored by Claude Opus 5.5
parent 97bd23bed5
commit 5f9423a3c3
49 changed files with 799 additions and 82 deletions
@@ -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<JobBillingInfo>
*/
public function billingInfoMonthly(): array;
/**
* Billing details of the given jobs, keyed by id; unknown ids are left out.
*
@@ -42,5 +42,6 @@ final readonly class CustomerJobData
public array $links = [],
public ?string $quotedAmount = null,
public bool $setsQuotedAmount = false,
public ?string $monthlyFee = null,
) {}
}
@@ -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,
) {}
@@ -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 = '',
) {}
}
@@ -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) {
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidMonthlyFee extends DomainException
{
public function __construct()
{
parent::__construct('The monthly fee is not a valid amount.');
}
}
@@ -60,6 +60,7 @@ final readonly class JobDetails
array $tags,
public array $links,
public ?Money $quotedAmount = null,
public ?Money $monthlyFee = null,
) {
$serviceUnitIds = array_values(array_unique($serviceUnitIds));
@@ -97,7 +98,7 @@ final readonly class JobDetails
$this->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,
@@ -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',
@@ -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'),
);
}
@@ -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(
@@ -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'),
@@ -342,7 +342,7 @@ new class extends Component
@endforeach
</x-select.native>
<x-select.native wire:model="form.payment_basis" :label="__('jobs.fields.payment_basis')" :aria-label="__('jobs.fields.payment_basis')">
<x-select.native wire:model.live="form.payment_basis" :label="__('jobs.fields.payment_basis')" :aria-label="__('jobs.fields.payment_basis')">
<option value="">{{ __('jobs.fields.no_payment_basis') }}</option>
@foreach (PaymentBasis::cases() as $basis)
<option value="{{ $basis->value }}">{{ __('jobs.payment_bases.'.$basis->value) }}</option>
@@ -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')
<x-input
wire:model="form.monthly_fee"
inputmode="decimal"
autocomplete="off"
:label="__('jobs.fields.monthly_fee_input')"
:hint="__('jobs.fields.monthly_fee_description')"
/>
@endif
@endcan
</div>
</fieldset>
@@ -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')
<dt class="font-medium">{{ __('jobs.fields.quoted_amount') }}</dt>
<dd>{{ $job->quotedAmountCents === null ? __('jobs.not_set') : Money::fromCents($job->quotedAmountCents)->format().' '.__('jobs.vat_excluded') }}</dd>
@if ($job->paymentBasis?->value === 'monthly_fee' || $job->monthlyFeeCents !== null)
<dt class="font-medium">{{ __('jobs.fields.monthly_fee') }}</dt>
<dd>{{ $job->monthlyFeeCents === null ? __('jobs.not_set') : Money::fromCents($job->monthlyFeeCents)->format().' '.__('jobs.vat_excluded') }}</dd>
@endif
@endcan
<dt class="font-medium">{{ __('jobs.fields.customer_reference') }}</dt>