Add expenses on customer jobs

- New Expenses module: purchases (materials, other) with a description
  and cost, and mileage priced with the price list's mileage rate.
- Who paid and whether the expense is billed are separate: an employee's
  own payments are reimbursed elsewhere. A billed expense has a markup
  and a billed amount, cost plus markup unless given.
- A job's expenses page lists, adds, edits and removes them; amounts of
  others' expenses need the expenses permission, own ones always show.
  Done jobs lock their expenses.
- The Kulut menu shows the user's own expenses by month. Management
  records subcontractors' expenses, which they see but cannot change.
- The price list gets a default markup for new purchases.
- Number fields that update a calculation now use wire:model.live.blur:
  in Livewire 4 plain .blur no longer sends the value to the server,
  which also fixes the product form's VAT calculation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 08:11:27 +02:00
co-authored by Claude Opus 5.5
parent bdd8d446d8
commit 54d98d9d2f
64 changed files with 3092 additions and 9 deletions
@@ -0,0 +1,62 @@
<?php
namespace App\Modules\Expenses\Presentation\Livewire\Concerns;
use App\Modules\Expenses\Application\DTOs\ExpenseSummary;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\ValueObjects\Kilometers;
use App\Modules\Shared\Domain\ValueObjects\Money;
use Carbon\CarbonImmutable;
/**
* Formatting shared by the expense lists: labels, dates and amounts, which
* are shown only to those who may see them.
*/
trait ShowsExpenses
{
public function canSeeAmount(ExpenseSummary $expense): bool
{
return auth()->user()?->can('expenses.see-amount', [$expense->userId, $expense->recordedBy]) ?? false;
}
public function canChange(ExpenseSummary $expense): bool
{
return ! $expense->job->isLocked
&& (auth()->user()?->can('expenses.change', [$expense->userId, $expense->recordedBy]) ?? false);
}
public function amount(ExpenseSummary $expense, ?int $cents): string
{
if (! $this->canSeeAmount($expense)) {
return __('expenses.hidden_amount');
}
return $cents === null ? __('expenses.not_billed') : Money::fromCents($cents)->format();
}
public function money(int $cents): string
{
return Money::fromCents($cents)->format();
}
/**
* What the expense is: the description, or for kilometres "40 km, Tampere (Asiakastapaaminen)".
*/
public function summaryText(ExpenseSummary $expense): string
{
if ($expense->category !== ExpenseCategory::Mileage || $expense->kilometerTenths === null) {
return (string) $expense->description;
}
return __('expenses.mileage_summary', [
'km' => (new Kilometers($expense->kilometerTenths))->format(),
'destination' => $expense->destination,
'purpose' => $expense->purpose,
]);
}
public function dayLabel(string $day): string
{
return CarbonImmutable::parse($day)->format('j.n.Y');
}
}
@@ -0,0 +1,186 @@
<?php
namespace App\Modules\Expenses\Presentation\Livewire\Forms;
use App\Modules\Expenses\Application\DTOs\ExpenseData;
use App\Modules\Expenses\Application\DTOs\ExpenseSummary;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
use App\Modules\Expenses\Domain\Exceptions\ExpenseCostRequired;
use App\Modules\Expenses\Domain\Exceptions\ExpenseDescriptionRequired;
use App\Modules\Expenses\Domain\Exceptions\InvalidKilometers;
use App\Modules\Expenses\Domain\Exceptions\InvalidMarkup;
use App\Modules\Expenses\Domain\Exceptions\MileageDetailsRequired;
use App\Modules\Expenses\Domain\Exceptions\MileageRateMissing;
use App\Modules\Expenses\Domain\ValueObjects\Kilometers;
use App\Modules\Expenses\Domain\ValueObjects\MarkupPercentage;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use Illuminate\Validation\Rule;
use Livewire\Form;
/**
* Fields of an expense as typed. Amounts, kilometres and markup are parsed
* by the use case; this form checks only their shape.
*/
class ExpenseForm extends Form
{
public string $user_id = '';
public string $category = 'materials';
public string $paid_by = 'company';
public string $spent_on = '';
public string $description = '';
public string $cost = '';
public string $kilometers = '';
public string $destination = '';
public string $purpose = '';
public bool $is_billable = true;
public string $markup = '';
public string $billed_amount = '';
public function isMileage(): bool
{
return $this->category === ExpenseCategory::Mileage->value;
}
public function fillFrom(ExpenseSummary $expense): void
{
$this->user_id = (string) $expense->userId;
$this->category = $expense->category->value;
$this->paid_by = $expense->paidBy->value;
$this->spent_on = $expense->spentOn;
$this->description = $expense->description ?? '';
$this->cost = $expense->category === ExpenseCategory::Mileage ? '' : Money::fromCents($expense->costCents)->inputValue();
$this->kilometers = $expense->kilometerTenths === null ? '' : (new Kilometers($expense->kilometerTenths))->format();
$this->destination = $expense->destination ?? '';
$this->purpose = $expense->purpose ?? '';
$this->is_billable = $expense->isBillable;
$this->markup = $expense->markupBasisPoints === null ? '' : (new MarkupPercentage($expense->markupBasisPoints))->inputValue();
$this->billed_amount = $expense->billedAmountCents === null ? '' : Money::fromCents($expense->billedAmountCents)->inputValue();
}
public function toData(): ExpenseData
{
$this->validate();
$mileage = $this->isMileage();
return new ExpenseData(
userId: (int) $this->user_id,
category: ExpenseCategory::from($this->category),
paidBy: ExpensePayer::from($this->paid_by),
spentOn: $this->spent_on,
description: $this->description,
cost: $mileage ? '' : $this->cost,
kilometers: $mileage ? $this->kilometers : '',
destination: $mileage ? $this->destination : '',
purpose: $mileage ? $this->purpose : '',
isBillable: $this->is_billable,
markup: $this->is_billable ? $this->markup : '',
billedAmount: $this->is_billable ? $this->billed_amount : '',
);
}
/**
* Shows a broken business rule as an error on the field it concerns.
*/
public function showDomainError(DomainException $exception): void
{
[$field, $key] = match ($exception::class) {
ExpenseDescriptionRequired::class => ['description', 'expenses.errors.description_required'],
ExpenseCostRequired::class => ['cost', 'expenses.errors.cost_required'],
InvalidMoneyAmount::class => [$this->invalidAmountField(), 'expenses.errors.invalid_amount'],
InvalidKilometers::class => ['kilometers', 'expenses.errors.invalid_kilometers'],
MileageDetailsRequired::class => [$this->firstMissingMileageField(), 'expenses.errors.mileage_details_required'],
MileageRateMissing::class => ['kilometers', 'expenses.errors.mileage_rate_missing'],
InvalidMarkup::class => ['markup', 'expenses.errors.invalid_markup'],
default => throw $exception,
};
$this->addError($field, __($key));
}
/**
* @return array<string, array<int, mixed>>
*/
protected function rules(): array
{
return [
'user_id' => ['required', 'integer'],
'category' => ['required', Rule::enum(ExpenseCategory::class)],
'paid_by' => ['required', Rule::enum(ExpensePayer::class)],
'spent_on' => ['required', 'date_format:Y-m-d'],
'description' => ['nullable', 'string', 'max:255'],
'cost' => ['nullable', 'string', 'max:20'],
'kilometers' => ['nullable', 'string', 'max:12'],
'destination' => ['nullable', 'string', 'max:255'],
'purpose' => ['nullable', 'string', 'max:255'],
'is_billable' => ['boolean'],
'markup' => ['nullable', 'string', 'max:10'],
'billed_amount' => ['nullable', 'string', 'max:20'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'user_id.required' => __('expenses.errors.user_required'),
'user_id.integer' => __('expenses.errors.user_required'),
'category.*' => __('expenses.errors.category_required'),
'paid_by.*' => __('expenses.errors.payer_required'),
'spent_on.required' => __('expenses.errors.date_required'),
'spent_on.date_format' => __('expenses.errors.invalid_date'),
'description.max' => __('expenses.errors.text_too_long'),
'destination.max' => __('expenses.errors.text_too_long'),
'purpose.max' => __('expenses.errors.text_too_long'),
'cost.max' => __('expenses.errors.invalid_amount'),
'billed_amount.max' => __('expenses.errors.invalid_amount'),
'kilometers.max' => __('expenses.errors.invalid_kilometers'),
'markup.max' => __('expenses.errors.invalid_markup'),
];
}
/**
* Which of the two amount fields holds the amount that does not parse.
*/
private function invalidAmountField(): string
{
if ($this->isMileage()) {
return 'billed_amount';
}
try {
Money::parse($this->cost);
} catch (InvalidMoneyAmount) {
return 'cost';
}
return 'billed_amount';
}
private function firstMissingMileageField(): string
{
foreach (['kilometers', 'destination', 'purpose'] as $field) {
if (trim($this->{$field}) === '') {
return $field;
}
}
return 'kilometers';
}
}
@@ -0,0 +1,310 @@
<?php
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Application\Contracts\ExpensePricing;
use App\Modules\Expenses\Application\Contracts\ExpenseQueries;
use App\Modules\Expenses\Application\DTOs\ExpenseJob;
use App\Modules\Expenses\Application\UseCases\RecordExpense;
use App\Modules\Expenses\Application\UseCases\UpdateExpense;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
use App\Modules\Expenses\Domain\Exceptions\ExpenseJobNotFound;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Expenses\Domain\Exceptions\ExpenseNotFound;
use App\Modules\Expenses\Domain\Exceptions\InvalidKilometers;
use App\Modules\Expenses\Domain\Exceptions\InvalidMarkup;
use App\Modules\Expenses\Domain\ValueObjects\Kilometers;
use App\Modules\Expenses\Domain\ValueObjects\MarkupPercentage;
use App\Modules\Expenses\Presentation\Livewire\Forms\ExpenseForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (with {job}) and edit page (with {expense}) of an expense. The
* fields follow the kind: a purchase has a description and cost, mileage
* has kilometres, destination and purpose. A billable expense gets a markup
* or a billed amount of its own.
*/
new class extends Component
{
#[Locked]
public int $jobId;
#[Locked]
public ?int $expenseId = null;
public ExpenseForm $form;
public function mount(ExpenseJobs $jobs, ExpenseQueries $expenses, ExpensePricing $pricing, Clock $clock, ?int $job = null, ?int $expense = null): void
{
$this->authorize('expenses.use');
if ($expense !== null) {
$summary = $expenses->find($expense);
abort_if($summary === null, 404);
$this->authorize('expenses.change', [$summary->userId, $summary->recordedBy]);
$this->expenseId = $summary->id;
$this->jobId = $summary->job->id;
$this->form->fillFrom($summary);
return;
}
$this->authorize('expenses.record');
abort_if($job === null || $jobs->find($job) === null, 404);
$this->authorize('jobs.view-job', $job);
$this->jobId = $job;
$this->form->user_id = (string) auth()->id();
$this->form->spent_on = $clock->today()->format('Y-m-d');
$this->form->markup = $this->defaultMarkup($pricing);
}
#[Computed]
public function job(): ExpenseJob
{
return app(ExpenseJobs::class)->find($this->jobId) ?? abort(404);
}
#[Computed]
public function canRecordForOthers(): bool
{
return auth()->user()?->can('expenses.record-for-others') ?? false;
}
/**
* @return list<UserOption>
*/
#[Computed]
public function userOptions(): array
{
return $this->canRecordForOthers ? app(UserAccountQueries::class)->activeUserOptions() : [];
}
/**
* Kilometres get no markup by default; purchases get the default markup.
*/
public function updatedFormCategory(): void
{
if ($this->form->isMileage()) {
$this->form->markup = '';
} elseif ($this->form->markup === '') {
$this->form->markup = $this->defaultMarkup(app(ExpensePricing::class));
}
$this->resetErrorBag();
}
/**
* The cost of the kilometres typed, e.g. "40 km × 0,59 € = 23,60 €"; empty while it cannot be worked out.
*/
public function mileageCost(): string
{
$rate = app(ExpensePricing::class)->mileageRateCents();
if ($rate === null) {
return __('expenses.errors.mileage_rate_missing');
}
try {
$kilometers = Kilometers::parse($this->form->kilometers);
} catch (InvalidKilometers) {
return '';
}
if ($kilometers === null) {
return __('expenses.form.mileage_rate', ['rate' => Money::fromCents($rate)->format()]);
}
return __('expenses.form.mileage_cost', [
'km' => $kilometers->format(),
'rate' => Money::fromCents($rate)->format(),
'cost' => $kilometers->priceAt(Money::fromCents($rate))->format(),
]);
}
/**
* The amount billed when the billed amount is left empty: cost plus markup.
*/
public function suggestedBilledAmount(): string
{
try {
$cost = $this->form->isMileage()
? $this->mileageCostMoney()
: Money::parse($this->form->cost);
$markup = MarkupPercentage::parse($this->form->markup);
} catch (InvalidMoneyAmount|InvalidKilometers|InvalidMarkup) {
return '';
}
if ($cost === null) {
return '';
}
return __('expenses.form.suggested_billed', ['amount' => $cost->addPercent($markup->basisPoints ?? 0)->format()]);
}
public function save(RecordExpense $recordExpense, UpdateExpense $updateExpense): void
{
$this->authorize('expenses.use');
if (! $this->canRecordForOthers) {
$this->form->user_id = (string) ($this->expenseId === null ? auth()->id() : $this->form->user_id);
}
$data = $this->form->toData();
if ($this->canRecordForOthers && ! collect($this->userOptions)->contains('id', $data->userId)) {
$this->form->addError('user_id', __('expenses.errors.user_required'));
return;
}
try {
if ($this->expenseId === null) {
$this->authorize('expenses.record');
$recordExpense->execute($this->jobId, $data, (int) auth()->id());
session()->flash('status', __('expenses.saved'));
} else {
$stored = app(ExpenseQueries::class)->find($this->expenseId) ?? abort(404);
$this->authorize('expenses.change', [$stored->userId, $stored->recordedBy]);
$updateExpense->execute($this->expenseId, $data);
session()->flash('status', __('expenses.updated'));
}
} catch (ExpenseLocked) {
$this->addError('form.spent_on', __('expenses.errors.locked'));
return;
} catch (ExpenseNotFound|ExpenseJobNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute(auth()->user()?->can('expenses.record') ? 'expenses.job' : 'expenses.mine', auth()->user()?->can('expenses.record') ? ['job' => $this->jobId] : [], navigate: true);
}
public function heading(): string
{
return __($this->expenseId === null ? 'expenses.form.create_title' : 'expenses.form.edit_title');
}
public function render(): mixed
{
return $this->view()->title($this->heading().' – '.$this->job->label());
}
private function mileageCostMoney(): ?Money
{
$rate = app(ExpensePricing::class)->mileageRateCents();
$kilometers = Kilometers::parse($this->form->kilometers);
return $rate === null || $kilometers === null ? null : $kilometers->priceAt(Money::fromCents($rate));
}
private function defaultMarkup(ExpensePricing $pricing): string
{
$basisPoints = $pricing->defaultMarkupBasisPoints();
return $basisPoints === 0 ? '' : (new MarkupPercentage($basisPoints))->inputValue();
}
};
?>
@php($job = $this->job)
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('expenses.fields.job') }}: {{ $job->label() }}</p>
</div>
@if ($job->isLocked)
<p class="flex items-start gap-2 rounded-lg border border-zinc-300 p-3 text-sm dark:border-zinc-600">
<x-icon name="lock-closed" class="size-5 shrink-0" aria-hidden="true" />
{{ __('expenses.locked') }}
</p>
@else
<form wire:submit="save" class="space-y-6" novalidate>
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model.live="form.category" :label="__('expenses.fields.category')" :aria-label="__('expenses.fields.category')">
@foreach (ExpenseCategory::cases() as $category)
<option wire:key="category-{{ $category->value }}" value="{{ $category->value }}">{{ __('expenses.categories.'.$category->value) }}</option>
@endforeach
</x-select.native>
<div class="grid gap-6 sm:grid-cols-2">
<x-input wire:model="form.spent_on" type="date" :label="__('expenses.fields.spent_on')" required />
<x-select.native wire:model="form.paid_by" :label="__('expenses.fields.paid_by')" :aria-label="__('expenses.fields.paid_by')">
@foreach (ExpensePayer::cases() as $payer)
<option wire:key="payer-{{ $payer->value }}" value="{{ $payer->value }}">{{ __('expenses.payers.'.$payer->value) }}</option>
@endforeach
</x-select.native>
</div>
@if ($this->canRecordForOthers)
<x-select.native
wire:model="form.user_id"
:label="__('expenses.fields.user')"
:aria-label="__('expenses.fields.user')"
:hint="__('expenses.form.user_help')"
>
@foreach ($this->userOptions as $option)
<option wire:key="user-{{ $option->id }}" value="{{ $option->id }}">{{ $option->name }}</option>
@endforeach
</x-select.native>
@endif
@if ($form->isMileage())
<div class="space-y-1">
<x-input wire:model.live.blur="form.kilometers" inputmode="decimal" :label="__('expenses.fields.kilometers')" :hint="__('expenses.form.kilometers_help')" autocomplete="off" required />
<p aria-live="polite" class="min-h-5 text-sm">{{ $this->mileageCost() }}</p>
</div>
<x-input wire:model="form.destination" :label="__('expenses.fields.destination')" autocomplete="off" required />
<x-input wire:model="form.purpose" :label="__('expenses.fields.purpose')" autocomplete="off" required />
<x-input wire:model="form.description" :label="__('expenses.fields.note')" autocomplete="off" />
@else
<x-input wire:model="form.description" :label="__('expenses.fields.description')" :hint="__('expenses.form.description_help')" autocomplete="off" required />
<x-input wire:model.live.blur="form.cost" inputmode="decimal" :label="__('expenses.fields.cost')" :hint="__('expenses.form.cost_help')" autocomplete="off" required />
@endif
<fieldset class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
<legend class="px-1 font-medium">{{ __('expenses.form.billing') }}</legend>
<x-checkbox id="expense-billable" wire:model.live="form.is_billable" :label="__('expenses.fields.is_billable')" />
@if ($form->is_billable)
<div class="grid gap-6 sm:grid-cols-2">
<x-input wire:model.live.blur="form.markup" inputmode="decimal" :label="__('expenses.fields.markup')" :hint="__('expenses.form.markup_help')" autocomplete="off" />
<x-input wire:model.live.blur="form.billed_amount" inputmode="decimal" :label="__('expenses.fields.billed_amount')" :hint="__('expenses.form.billed_amount_help')" autocomplete="off" />
</div>
<p aria-live="polite" class="min-h-5 text-sm">{{ $form->billed_amount === '' ? $this->suggestedBilledAmount() : '' }}</p>
@endif
</fieldset>
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('expenses.save')" />
<x-button
:href="auth()->user()?->can('expenses.record') ? route('expenses.job', $job->id) : route('expenses.mine')"
wire:navigate
subtle
color="black"
:text="__('expenses.cancel')"
/>
</div>
</form>
@endif
</div>
@@ -0,0 +1,244 @@
<?php
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Application\Contracts\ExpenseQueries;
use App\Modules\Expenses\Application\DTOs\ExpenseJob;
use App\Modules\Expenses\Application\DTOs\ExpenseSummary;
use App\Modules\Expenses\Application\UseCases\RemoveExpense;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Expenses\Domain\Exceptions\ExpenseNotFound;
use App\Modules\Expenses\Presentation\Livewire\Concerns\ShowsExpenses;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* The expenses of one customer job. Amounts of others' expenses are shown
* only with the expenses permission; everyone sees their own.
*/
new class extends Component
{
use ShowsExpenses;
#[Locked]
public int $jobId;
#[Locked]
public ?int $removalExpenseId = null;
public string $statusMessage = '';
public function mount(ExpenseJobs $jobs, int $job): void
{
$this->authorize('expenses.record');
$this->authorize('jobs.view-job', $job);
abort_if($jobs->find($job) === null, 404);
$this->jobId = $job;
}
#[Computed]
public function job(): ExpenseJob
{
return app(ExpenseJobs::class)->find($this->jobId) ?? abort(404);
}
/**
* @return list<ExpenseSummary>
*/
#[Computed]
public function expenses(): array
{
return app(ExpenseQueries::class)->forJob($this->jobId);
}
#[Computed]
public function canSeeTotals(): bool
{
return auth()->user()?->can('money.expenses') ?? false;
}
/**
* @return array{cost: int, billed: int}
*/
#[Computed]
public function totals(): array
{
return [
'cost' => array_sum(array_map(fn (ExpenseSummary $expense): int => $expense->costCents, $this->expenses)),
'billed' => array_sum(array_map(fn (ExpenseSummary $expense): int => $expense->billedAmountCents ?? 0, $this->expenses)),
];
}
public function confirmRemoval(int $expenseId): void
{
$expense = $this->expense($expenseId);
if ($expense === null || ! $this->canChange($expense)) {
return;
}
$this->removalExpenseId = $expenseId;
$this->js("document.getElementById('remove-expense-dialog').showModal()");
}
public function removeExpense(RemoveExpense $removeExpense): void
{
$expense = $this->expense((int) $this->removalExpenseId);
if ($expense !== null) {
$this->authorize('expenses.change', [$expense->userId, $expense->recordedBy]);
try {
$removeExpense->execute($expense->id);
$this->statusMessage = __('expenses.removed', ['expense' => $this->summaryText($expense)]);
} catch (ExpenseLocked) {
$this->statusMessage = __('expenses.errors.locked');
} catch (ExpenseNotFound) {
$this->statusMessage = __('expenses.errors.not_found');
}
}
$this->reset('removalExpenseId');
unset($this->expenses, $this->totals);
$this->js("document.getElementById('remove-expense-dialog').close(); document.getElementById('expenses-heading').focus()");
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function headers(): array
{
return [
['index' => 'spentOn', 'label' => __('expenses.fields.spent_on'), 'sortable' => false],
['index' => 'what', 'label' => __('expenses.fields.what'), 'sortable' => false],
['index' => 'user', 'label' => __('expenses.fields.user'), 'sortable' => false],
['index' => 'cost', 'label' => __('expenses.fields.cost_column'), 'sortable' => false, 'align' => 'right'],
['index' => 'billed', 'label' => __('expenses.fields.billed_column'), 'sortable' => false, 'align' => 'right'],
['index' => 'actions', 'label' => __('expenses.actions'), 'sortable' => false],
];
}
public function render(): mixed
{
return $this->view()->title(__('expenses.job_page.title', ['job' => $this->job->label()]));
}
private function expense(int $expenseId): ?ExpenseSummary
{
return collect($this->expenses)->firstWhere('id', $expenseId);
}
};
?>
@php($job = $this->job)
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold break-words">{{ __('expenses.job_page.title', ['job' => $job->label()]) }}</h1>
<x-link :href="route('jobs.show', $job->id)" navigate class="text-sm">{{ __('expenses.job_page.back_to_job') }}</x-link>
</div>
<p role="status" aria-live="polite" class="min-h-5 text-sm">{{ $statusMessage }}</p>
@if (session('status'))
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@endif
@if ($job->isLocked)
<p class="flex items-start gap-2 rounded-lg border border-zinc-300 p-3 text-sm dark:border-zinc-600">
<x-icon name="lock-closed" class="size-5 shrink-0" aria-hidden="true" />
{{ __('expenses.locked') }}
</p>
@else
<x-button :href="route('expenses.create', $job->id)" wire:navigate icon="plus" :text="__('expenses.add')" />
@endif
<section aria-labelledby="expenses-heading" class="space-y-3">
<h2 id="expenses-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">{{ __('expenses.job_page.list') }}</h2>
@unless ($this->canSeeTotals)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('expenses.amounts_hidden_help') }}</p>
@endunless
@if ($this->expenses === [])
<p class="text-sm">{{ __('expenses.none') }}</p>
@else
<x-table :headers="$this->headers()" :rows="$this->expenses">
@interact('column_spentOn', $expense)
<span class="whitespace-nowrap">{{ $this->dayLabel($expense->spentOn) }}</span>
@endinteract
@interact('column_what', $expense)
<span class="block font-medium break-words whitespace-normal">{{ $this->summaryText($expense) }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300">
{{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }}
</span>
@endinteract
@interact('column_user', $expense)
{{ $expense->userName }}
@endinteract
@interact('column_cost', $expense)
<span class="whitespace-nowrap">{{ $this->amount($expense, $expense->costCents) }}</span>
@endinteract
@interact('column_billed', $expense)
<span class="whitespace-nowrap">{{ $this->amount($expense, $expense->billedAmountCents) }}</span>
@endinteract
@interact('column_actions', $expense)
@if ($this->canChange($expense))
<div class="flex flex-wrap gap-2">
<x-button
:href="route('expenses.edit', $expense->id)"
wire:navigate
subtle
color="black"
sm
icon="pencil"
:text="__('expenses.edit')"
:aria-label="__('expenses.edit_named', ['expense' => $this->summaryText($expense), 'day' => $this->dayLabel($expense->spentOn)])"
/>
<x-button
wire:click="confirmRemoval({{ $expense->id }})"
subtle
color="black"
sm
icon="trash"
:text="__('expenses.remove')"
:aria-label="__('expenses.remove_named', ['expense' => $this->summaryText($expense), 'day' => $this->dayLabel($expense->spentOn)])"
/>
</div>
@endif
@endinteract
</x-table>
@if ($this->canSeeTotals)
<dl class="grid gap-x-6 gap-y-1 text-sm sm:grid-cols-[max-content_1fr]">
<dt class="font-medium">{{ __('expenses.totals.cost') }}</dt>
<dd>{{ $this->money($this->totals['cost']) }}</dd>
<dt class="font-medium">{{ __('expenses.totals.billed') }}</dt>
<dd>{{ $this->money($this->totals['billed']) }}</dd>
</dl>
@endif
@endif
</section>
<x-confirm-dialog id="remove-expense-dialog" :title="__('expenses.removal_title')">
<p>
@php($removal = collect($this->expenses)->firstWhere('id', $removalExpenseId))
@if ($removal !== null)
{{ __('expenses.remove_question', ['expense' => $this->summaryText($removal), 'day' => $this->dayLabel($removal->spentOn)]) }}
@endif
</p>
<x-slot:actions>
<x-button wire:click="removeExpense" color="red" icon="trash" :text="__('expenses.remove')" />
</x-slot:actions>
</x-confirm-dialog>
</div>
@@ -0,0 +1,170 @@
<?php
use App\Modules\Expenses\Application\Contracts\ExpenseQueries;
use App\Modules\Expenses\Application\DTOs\ExpenseSummary;
use App\Modules\Expenses\Presentation\Livewire\Concerns\ShowsExpenses;
use App\Modules\Users\Application\Contracts\Clock;
use Carbon\CarbonImmutable;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* The signed-in user's own expenses month by month, with their amounts.
* Subcontractors see the expenses management recorded for them.
*/
new class extends Component
{
use ShowsExpenses;
/**
* The month shown (Y-m). Read from the URL on mount and then changed
* only by showMonth(), so the browser cannot set it.
*/
#[Locked]
#[Url(as: 'kuukausi', except: '')]
public string $month = '';
public function mount(Clock $clock): void
{
$this->authorize('expenses.use');
$this->month = $this->monthStart($this->month)?->format('Y-m') ?? $clock->today()->format('Y-m');
}
/**
* @return list<ExpenseSummary>
*/
#[Computed]
public function expenses(): array
{
return app(ExpenseQueries::class)->forUserInMonth((int) auth()->id(), $this->month);
}
#[Computed]
public function total(): int
{
return array_sum(array_map(fn (ExpenseSummary $expense): int => $expense->costCents, $this->expenses));
}
public function showMonth(string $which, Clock $clock): void
{
$current = $this->monthStart($this->month) ?? CarbonImmutable::instance($clock->today());
$this->month = match ($which) {
'previous' => $current->subMonthNoOverflow()->format('Y-m'),
'next' => $current->addMonthNoOverflow()->format('Y-m'),
default => $clock->today()->format('Y-m'),
};
unset($this->expenses, $this->total);
}
public function monthLabel(): string
{
$date = $this->monthStart($this->month);
return $date === null ? $this->month : __('expenses.months')[$date->month - 1].' '.$date->year;
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function headers(): array
{
return [
['index' => 'spentOn', 'label' => __('expenses.fields.spent_on'), 'sortable' => false],
['index' => 'job', 'label' => __('expenses.fields.job'), 'sortable' => false],
['index' => 'what', 'label' => __('expenses.fields.what'), 'sortable' => false],
['index' => 'cost', 'label' => __('expenses.fields.cost_column'), 'sortable' => false, 'align' => 'right'],
['index' => 'actions', 'label' => __('expenses.actions'), 'sortable' => false],
];
}
public function render(): mixed
{
return $this->view()->title(__('expenses.mine.title'));
}
/**
* The first day of a Y-m month, or null when the value is not one.
*/
private function monthStart(string $month): ?CarbonImmutable
{
return preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) === 1
? CarbonImmutable::createFromFormat('!Y-m', $month)
: null;
}
};
?>
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('expenses.mine.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
{{ __(auth()->user()?->can('expenses.record') ? 'expenses.mine.help' : 'expenses.mine.help_subcontractor') }}
</p>
</div>
<nav aria-label="{{ __('expenses.mine.month_navigation') }}" class="flex flex-wrap items-center gap-2">
<x-button wire:click="showMonth('previous')" subtle color="black" sm icon="chevron-left" :text="__('expenses.mine.previous')" />
<x-button wire:click="showMonth('current')" subtle color="black" sm :text="__('expenses.mine.current')" />
<x-button wire:click="showMonth('next')" subtle color="black" sm icon="chevron-right" position="right" :text="__('expenses.mine.next')" />
</nav>
<section aria-labelledby="month-heading" class="space-y-3">
<h2 id="month-heading" class="text-xl font-semibold" aria-live="polite">{{ $this->monthLabel() }}</h2>
@if ($this->expenses === [])
<p class="text-sm">{{ __('expenses.none') }}</p>
@else
<x-table :headers="$this->headers()" :rows="$this->expenses">
@interact('column_spentOn', $expense)
<span class="whitespace-nowrap">{{ $this->dayLabel($expense->spentOn) }}</span>
@endinteract
@interact('column_job', $expense)
@can('expenses.record')
<x-link :href="route('expenses.job', $expense->job->id)" navigate class="whitespace-normal">{{ $expense->job->label() }}</x-link>
@else
<span class="whitespace-normal">{{ $expense->job->label() }}</span>
@endcan
@if ($expense->job->isLocked)
<span class="mt-1 flex items-center gap-1 text-xs">
<x-icon name="lock-closed" class="size-4" aria-hidden="true" /> {{ __('expenses.locked_short') }}
</span>
@endif
@endinteract
@interact('column_what', $expense)
<span class="block break-words whitespace-normal">{{ $this->summaryText($expense) }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300">
{{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }}
</span>
@endinteract
@interact('column_cost', $expense)
<span class="whitespace-nowrap">{{ $this->amount($expense, $expense->costCents) }}</span>
@endinteract
@interact('column_actions', $expense)
@if ($this->canChange($expense))
<x-button
:href="route('expenses.edit', $expense->id)"
wire:navigate
subtle
color="black"
sm
icon="pencil"
:text="__('expenses.edit')"
:aria-label="__('expenses.edit_named', ['expense' => $this->summaryText($expense), 'day' => $this->dayLabel($expense->spentOn)])"
/>
@endif
@endinteract
</x-table>
<p class="text-sm font-medium">{{ __('expenses.mine.total', ['total' => $this->money($this->total)]) }}</p>
@endif
</section>
</div>
@@ -0,0 +1,13 @@
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:expenses.use'])
->prefix('expenses')
->name('expenses.')
->group(function () {
Route::livewire('/', 'expenses::mine')->name('mine');
Route::livewire('/jobs/{job}', 'expenses::job')->whereNumber('job')->name('job');
Route::livewire('/jobs/{job}/create', 'expenses::form')->whereNumber('job')->name('create');
Route::livewire('/{expense}/edit', 'expenses::form')->whereNumber('expense')->name('edit');
});