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,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\Contracts;
use App\Modules\Expenses\Application\DTOs\ExpenseJob;
/**
* The customer jobs expenses are recorded on. Implemented with the Jobs
* module's queries.
*/
interface ExpenseJobs
{
public function find(int $jobId): ?ExpenseJob;
/**
* @param list<int> $jobIds
* @return array<int, ExpenseJob> Keyed by job id.
*/
public function findMany(array $jobIds): array;
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\Contracts;
/**
* Prices expenses need from the price list. Implemented with the Catalog
* module's queries.
*/
interface ExpensePricing
{
/**
* Price of a driven kilometre in cents (VAT 0), null when not set.
*/
public function mileageRateCents(): ?int;
/**
* Markup suggested for new purchases, in hundredths of a percent.
*/
public function defaultMarkupBasisPoints(): int;
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\Contracts;
use App\Modules\Expenses\Application\DTOs\ExpenseSummary;
/**
* Read side of expenses, newest first.
*/
interface ExpenseQueries
{
/**
* @return list<ExpenseSummary>
*/
public function forJob(int $jobId): array;
/**
* A user's own expenses in a month.
*
* @param string $month As Y-m.
* @return list<ExpenseSummary>
*/
public function forUserInMonth(int $userId, string $month): array;
public function find(int $id): ?ExpenseSummary;
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\DTOs;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
/**
* An expense's fields as the user typed them: amounts "12,50", kilometres
* "12,5", markup "15". An empty billed amount means cost plus markup.
*/
final readonly class ExpenseData
{
/**
* @param string $spentOn Date as Y-m-d.
*/
public function __construct(
public int $userId,
public ExpenseCategory $category,
public ExpensePayer $paidBy,
public string $spentOn,
public string $description = '',
public string $cost = '',
public string $kilometers = '',
public string $destination = '',
public string $purpose = '',
public bool $isBillable = true,
public string $markup = '',
public string $billedAmount = '',
) {}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\DTOs;
/**
* A customer job as expenses see it: its number and name, and whether it is
* done, which locks its expenses.
*/
final readonly class ExpenseJob
{
public function __construct(
public int $id,
public string $number,
public string $name,
public bool $isLocked,
) {}
/**
* E.g. "2026-0005 Messuvideo".
*/
public function label(): string
{
return $this->number.' '.$this->name;
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\DTOs;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
/**
* An expense for lists and forms. Amounts are in cents without VAT; pages
* decide per row whether the viewer may see them.
*/
final readonly class ExpenseSummary
{
/**
* @param string $spentOn Date as Y-m-d.
*/
public function __construct(
public int $id,
public ExpenseJob $job,
public int $userId,
public string $userName,
public int $recordedBy,
public string $recordedByName,
public ExpenseCategory $category,
public ExpensePayer $paidBy,
public string $spentOn,
public ?string $description,
public int $costCents,
public ?int $kilometerTenths,
public ?string $destination,
public ?string $purpose,
public bool $isBillable,
public ?int $markupBasisPoints,
public ?int $billedAmountCents,
) {}
}
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\UseCases;
use App\Modules\Expenses\Application\Contracts\ExpensePricing;
use App\Modules\Expenses\Application\DTOs\ExpenseData;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
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\ExpenseDetails;
use App\Modules\Expenses\Domain\ValueObjects\Kilometers;
use App\Modules\Expenses\Domain\ValueObjects\MarkupPercentage;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use DateTimeImmutable;
use InvalidArgumentException;
/**
* Turns typed expense fields into ExpenseDetails, pricing kilometres with
* the current mileage rate. Shared by RecordExpense and UpdateExpense.
*/
final class ExpenseDetailsFactory
{
public function __construct(private ExpensePricing $pricing) {}
/**
* @throws ExpenseCostRequired
* @throws ExpenseDescriptionRequired
* @throws InvalidKilometers
* @throws InvalidMarkup
* @throws InvalidMoneyAmount
* @throws MileageDetailsRequired
* @throws MileageRateMissing
*/
public function build(ExpenseData $data): ExpenseDetails
{
$spentOn = self::day($data->spentOn);
$markup = $data->isBillable ? MarkupPercentage::parse($data->markup) : null;
$billedAmount = $data->isBillable ? Money::parse($data->billedAmount) : null;
if ($data->category !== ExpenseCategory::Mileage) {
return ExpenseDetails::purchase(
$data->category,
$data->paidBy,
$spentOn,
$data->description,
Money::parse($data->cost),
$data->isBillable,
$markup,
$billedAmount,
);
}
$kilometers = Kilometers::parse($data->kilometers);
$rate = $this->pricing->mileageRateCents() ?? throw new MileageRateMissing;
return ExpenseDetails::mileage(
$data->paidBy,
$spentOn,
$kilometers,
$data->destination,
$data->purpose,
Money::fromCents($rate),
$data->isBillable,
$markup,
$billedAmount,
$data->description,
);
}
private static function day(string $value): DateTimeImmutable
{
$day = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if ($day === false || $day->format('Y-m-d') !== $value) {
throw new InvalidArgumentException("Not a Y-m-d date: {$value}");
}
return $day;
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\UseCases;
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Application\DTOs\ExpenseData;
use App\Modules\Expenses\Domain\Contracts\ExpenseRepository;
use App\Modules\Expenses\Domain\Entities\Expense;
use App\Modules\Expenses\Domain\Exceptions\ExpenseJobNotFound;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* Records an expense on a job that is not done yet.
*/
final class RecordExpense
{
public function __construct(
private ExpenseRepository $expenses,
private ExpenseJobs $jobs,
private ExpenseDetailsFactory $detailsFactory,
private TransactionManager $transactions,
) {}
/**
* @return int The new expense's id.
*
* @throws ExpenseJobNotFound
* @throws ExpenseLocked
* @throws DomainException When the fields break an expense rule.
*/
public function execute(int $jobId, ExpenseData $data, int $recordedBy): int
{
$details = $this->detailsFactory->build($data);
return $this->transactions->run(function () use ($jobId, $data, $details, $recordedBy): int {
$job = $this->jobs->find($jobId) ?? throw new ExpenseJobNotFound($jobId);
if ($job->isLocked) {
throw new ExpenseLocked;
}
return (int) $this->expenses->save(Expense::record($jobId, $data->userId, $recordedBy, $details))->id();
});
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\UseCases;
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Domain\Contracts\ExpenseRepository;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Expenses\Domain\Exceptions\ExpenseNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Removes an expense of a job that is not done yet.
*/
final class RemoveExpense
{
public function __construct(
private ExpenseRepository $expenses,
private ExpenseJobs $jobs,
private TransactionManager $transactions,
) {}
/**
* @throws ExpenseLocked
* @throws ExpenseNotFound
*/
public function execute(int $expenseId): void
{
$this->transactions->run(function () use ($expenseId): void {
$expense = $this->expenses->findById($expenseId) ?? throw new ExpenseNotFound($expenseId);
if ($this->jobs->find($expense->jobId())->isLocked ?? true) {
throw new ExpenseLocked;
}
$this->expenses->delete($expense);
});
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Application\UseCases;
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Application\DTOs\ExpenseData;
use App\Modules\Expenses\Domain\Contracts\ExpenseRepository;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Expenses\Domain\Exceptions\ExpenseNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* Changes an expense of a job that is not done yet. The job stays the same.
*/
final class UpdateExpense
{
public function __construct(
private ExpenseRepository $expenses,
private ExpenseJobs $jobs,
private ExpenseDetailsFactory $detailsFactory,
private TransactionManager $transactions,
) {}
/**
* @throws ExpenseLocked
* @throws ExpenseNotFound
* @throws DomainException When the fields break an expense rule.
*/
public function execute(int $expenseId, ExpenseData $data): void
{
$details = $this->detailsFactory->build($data);
$this->transactions->run(function () use ($expenseId, $data, $details): void {
$expense = $this->expenses->findById($expenseId) ?? throw new ExpenseNotFound($expenseId);
if ($this->jobs->find($expense->jobId())->isLocked ?? true) {
throw new ExpenseLocked;
}
$expense->change($data->userId, $details);
$this->expenses->save($expense);
});
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Contracts;
use App\Modules\Expenses\Domain\Entities\Expense;
interface ExpenseRepository
{
public function findById(int $id): ?Expense;
/**
* Inserts a new expense or updates a stored one, and returns the stored expense.
*/
public function save(Expense $expense): Expense;
public function delete(Expense $expense): void;
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Entities;
use App\Modules\Expenses\Domain\ValueObjects\ExpenseDetails;
/**
* An expense on a customer job: whose it is, who recorded it (management
* records subcontractors' expenses) and what it is.
*/
final class Expense
{
private function __construct(
private ?int $id,
private int $jobId,
private int $userId,
private int $recordedBy,
private ExpenseDetails $details,
) {}
public static function record(int $jobId, int $userId, int $recordedBy, ExpenseDetails $details): self
{
return new self(null, $jobId, $userId, $recordedBy, $details);
}
public static function reconstitute(int $id, int $jobId, int $userId, int $recordedBy, ExpenseDetails $details): self
{
return new self($id, $jobId, $userId, $recordedBy, $details);
}
public function change(int $userId, ExpenseDetails $details): void
{
$this->userId = $userId;
$this->details = $details;
}
public function id(): ?int
{
return $this->id;
}
public function jobId(): int
{
return $this->jobId;
}
public function userId(): int
{
return $this->userId;
}
public function recordedBy(): int
{
return $this->recordedBy;
}
public function details(): ExpenseDetails
{
return $this->details;
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Enums;
/**
* Kind of expense (kululaji). Finnish labels are in `expenses.categories`.
*/
enum ExpenseCategory: string
{
/** Products, supplies and materials. */
case Materials = 'materials';
/** Driven kilometres, priced with the mileage rate. */
case Mileage = 'mileage';
/** Other purchases and tools. */
case Other = 'other';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Enums;
/**
* Who paid the expense. An employee's own payments are reimbursed through
* another system; this one only records them.
*/
enum ExpensePayer: string
{
case Company = 'company';
case Employee = 'employee';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ExpenseCostRequired extends DomainException
{
public function __construct()
{
parent::__construct('A materials or other expense needs a cost.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ExpenseDescriptionRequired extends DomainException
{
public function __construct()
{
parent::__construct('A materials or other expense needs a description.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ExpenseJobNotFound extends DomainException
{
public function __construct(public readonly int $jobId)
{
parent::__construct("Customer job {$jobId} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ExpenseLocked extends DomainException
{
public function __construct()
{
parent::__construct('The job is done, so its expenses are locked.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ExpenseNotFound extends DomainException
{
public function __construct(public readonly int $expenseId)
{
parent::__construct("Expense {$expenseId} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidKilometers extends DomainException
{
public function __construct()
{
parent::__construct('Kilometres must be 0.1–10 000 to one decimal.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidMarkup extends DomainException
{
public function __construct()
{
parent::__construct('A markup must be 0–1000 % with at most two decimals.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class MileageDetailsRequired extends DomainException
{
public function __construct()
{
parent::__construct('A mileage expense needs kilometres, a destination and a purpose.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class MileageRateMissing extends DomainException
{
public function __construct()
{
parent::__construct('The mileage rate is not set in the price list.');
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\ValueObjects;
use App\Modules\Shared\Domain\ValueObjects\Money;
/**
* How a billable expense is billed to the customer: the amount (VAT 0) and
* the markup it came from. The amount is the one given, or else the cost
* plus the markup.
*/
final readonly class ExpenseBilling
{
private function __construct(
public Money $amount,
public ?MarkupPercentage $markup,
) {}
public static function for(Money $cost, ?MarkupPercentage $markup, ?Money $amount): self
{
return new self($amount ?? $cost->addPercent($markup->basisPoints ?? 0), $markup);
}
}
@@ -0,0 +1,131 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\ValueObjects;
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\MileageDetailsRequired;
use App\Modules\Shared\Domain\ValueObjects\Money;
use DateTimeImmutable;
/**
* What an expense is: a purchase (materials or other) with a description
* and cost, or driven kilometres priced with the mileage rate. Amounts are
* without VAT. $billing is null when the expense is not billed to the customer.
*/
final readonly class ExpenseDetails
{
private function __construct(
public ExpenseCategory $category,
public ExpensePayer $paidBy,
public DateTimeImmutable $spentOn,
public ?string $description,
public Money $cost,
public ?Kilometers $kilometers,
public ?string $destination,
public ?string $purpose,
public ?ExpenseBilling $billing,
) {}
/**
* @throws ExpenseCostRequired
* @throws ExpenseDescriptionRequired
*/
public static function purchase(
ExpenseCategory $category,
ExpensePayer $paidBy,
DateTimeImmutable $spentOn,
?string $description,
?Money $cost,
bool $billable,
?MarkupPercentage $markup = null,
?Money $billedAmount = null,
): self {
$description = self::text($description);
if ($category === ExpenseCategory::Mileage || $description === null) {
throw new ExpenseDescriptionRequired;
}
if ($cost === null) {
throw new ExpenseCostRequired;
}
return new self($category, $paidBy, $spentOn, $description, $cost, null, null, null, self::billing($billable, $cost, $markup, $billedAmount));
}
/**
* @throws MileageDetailsRequired
*/
public static function mileage(
ExpensePayer $paidBy,
DateTimeImmutable $spentOn,
?Kilometers $kilometers,
?string $destination,
?string $purpose,
Money $ratePerKilometer,
bool $billable,
?MarkupPercentage $markup = null,
?Money $billedAmount = null,
?string $description = null,
): self {
$destination = self::text($destination);
$purpose = self::text($purpose);
if ($kilometers === null || $destination === null || $purpose === null) {
throw new MileageDetailsRequired;
}
$cost = $kilometers->priceAt($ratePerKilometer);
return new self(
ExpenseCategory::Mileage,
$paidBy,
$spentOn,
self::text($description),
$cost,
$kilometers,
$destination,
$purpose,
self::billing($billable, $cost, $markup, $billedAmount),
);
}
/**
* Rebuilds stored details without re-checking them. Used only by repositories.
*/
public static function reconstitute(
ExpenseCategory $category,
ExpensePayer $paidBy,
DateTimeImmutable $spentOn,
?string $description,
Money $cost,
?Kilometers $kilometers,
?string $destination,
?string $purpose,
?ExpenseBilling $billing,
): self {
return new self($category, $paidBy, $spentOn, $description, $cost, $kilometers, $destination, $purpose, $billing);
}
public function isBillable(): bool
{
return $this->billing !== null;
}
private static function billing(bool $billable, Money $cost, ?MarkupPercentage $markup, ?Money $billedAmount): ?ExpenseBilling
{
return $billable ? ExpenseBilling::for($cost, $markup, $billedAmount) : null;
}
private static function text(?string $value): ?string
{
$value = trim((string) $value);
return $value === '' ? null : $value;
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\ValueObjects;
use App\Modules\Expenses\Domain\Exceptions\InvalidKilometers;
use App\Modules\Shared\Domain\ValueObjects\Money;
/**
* Driven kilometres to one decimal, stored in tenths of a kilometre.
*/
final readonly class Kilometers
{
public const int MAX_TENTHS = 100_000;
public int $tenths;
public function __construct(int $tenths)
{
if ($tenths < 1 || $tenths > self::MAX_TENTHS) {
throw new InvalidKilometers;
}
$this->tenths = $tenths;
}
/**
* Parses "12", "12,5" or "12.5"; null for an empty value.
*
* @throws InvalidKilometers
*/
public static function parse(string $value): ?self
{
$value = str_replace(',', '.', preg_replace('/[\s\x{00A0}]+|km/u', '', $value) ?? '');
if ($value === '') {
return null;
}
if (preg_match('/^(\d{1,6})(?:\.(\d))?$/', $value, $matches) !== 1) {
throw new InvalidKilometers;
}
return new self((int) $matches[1] * 10 + (int) ($matches[2] ?? 0));
}
/**
* The price of these kilometres at a rate per kilometre, rounded half up to the cent.
*/
public function priceAt(Money $ratePerKilometer): Money
{
return Money::fromCents(intdiv($this->tenths * $ratePerKilometer->cents * 2 + 10, 20));
}
/**
* Finnish notation, e.g. "12,5" or "40".
*/
public function format(): string
{
return $this->tenths % 10 === 0
? (string) intdiv($this->tenths, 10)
: intdiv($this->tenths, 10).','.($this->tenths % 10);
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Modules\Expenses\Domain\ValueObjects;
use App\Modules\Expenses\Domain\Exceptions\InvalidMarkup;
/**
* Markup added to an expense's cost when it is billed, e.g. 15 %, stored
* in hundredths of a percent.
*/
final readonly class MarkupPercentage
{
public const int MAX_BASIS_POINTS = 100_000;
public int $basisPoints;
public function __construct(int $basisPoints)
{
if ($basisPoints < 0 || $basisPoints > self::MAX_BASIS_POINTS) {
throw new InvalidMarkup;
}
$this->basisPoints = $basisPoints;
}
/**
* Parses "15", "12,5" or "15 %"; null for an empty value.
*
* @throws InvalidMarkup
*/
public static function parse(string $value): ?self
{
$value = str_replace(',', '.', preg_replace('/[\s\x{00A0}%]+/u', '', $value) ?? '');
if ($value === '') {
return null;
}
if (preg_match('/^(\d{1,4})(?:\.(\d{1,2}))?$/', $value, $matches) !== 1) {
throw new InvalidMarkup;
}
return new self((int) $matches[1] * 100 + (int) str_pad($matches[2] ?? '', 2, '0'));
}
/**
* The percentage for an input field, e.g. "12,5".
*/
public function inputValue(): string
{
return str_replace('.', ',', rtrim(rtrim(number_format($this->basisPoints / 100, 2, '.', ''), '0'), '.'));
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Modules\Expenses\Infrastructure;
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Application\DTOs\ExpenseJob;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
/**
* Customer jobs for expenses, read through the Jobs module's queries.
*/
class JobsForExpenses implements ExpenseJobs
{
public function __construct(private CustomerJobQueries $jobs) {}
public function find(int $jobId): ?ExpenseJob
{
return $this->findMany([$jobId])[$jobId] ?? null;
}
public function findMany(array $jobIds): array
{
return array_map(
fn (CustomerJobSummary $job): ExpenseJob => new ExpenseJob($job->id, $job->number, $job->name, $job->status->locksTime()),
$this->jobs->summariesByIds($jobIds),
);
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Modules\Expenses\Infrastructure\Persistence\Eloquent;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
use Database\Factories\ExpenseFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* Persistence model, used only inside the Expenses Infrastructure layer.
*
* @property int $id
* @property int $customer_job_id
* @property int $user_id
* @property int $recorded_by
* @property ExpenseCategory $category
* @property ExpensePayer $paid_by
* @property Carbon $spent_on
* @property string|null $description
* @property int $cost_cents
* @property string|null $kilometers
* @property string|null $destination
* @property string|null $purpose
* @property bool $is_billable
* @property int|null $markup_basis_points
* @property int|null $billed_amount_cents
*/
#[Table('expenses')]
#[Fillable([
'customer_job_id', 'user_id', 'recorded_by', 'category', 'paid_by', 'spent_on', 'description', 'cost_cents',
'kilometers', 'destination', 'purpose', 'is_billable', 'markup_basis_points', 'billed_amount_cents',
])]
#[UseFactory(ExpenseFactory::class)]
class ExpenseModel extends Model
{
/** @use HasFactory<ExpenseFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'customer_job_id' => 'integer',
'user_id' => 'integer',
'recorded_by' => 'integer',
'category' => ExpenseCategory::class,
'paid_by' => ExpensePayer::class,
'spent_on' => 'date',
'cost_cents' => 'integer',
'kilometers' => 'decimal:1',
'is_billable' => 'boolean',
'markup_basis_points' => 'integer',
'billed_amount_cents' => 'integer',
];
}
}
@@ -0,0 +1,84 @@
<?php
namespace App\Modules\Expenses\Infrastructure\Persistence\Repositories;
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\Infrastructure\Persistence\Eloquent\ExpenseModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class EloquentExpenseQueries implements ExpenseQueries
{
public function __construct(
private ExpenseJobs $jobs,
private UserAccountQueries $users,
) {}
public function forJob(int $jobId): array
{
return $this->summaries(ExpenseModel::query()->where('customer_job_id', $jobId));
}
public function forUserInMonth(int $userId, string $month): array
{
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
return [];
}
$start = Carbon::createFromFormat('!Y-m', $month);
return $this->summaries(ExpenseModel::query()
->where('user_id', $userId)
->whereBetween('spent_on', [$start->toDateString(), $start->copy()->endOfMonth()->toDateString()]));
}
public function find(int $id): ?ExpenseSummary
{
return $this->summaries(ExpenseModel::query()->whereKey($id))[0] ?? null;
}
/**
* @param Builder<ExpenseModel> $query
* @return list<ExpenseSummary>
*/
private function summaries(Builder $query): array
{
/** @var Collection<int, ExpenseModel> $models */
$models = $query->orderByDesc('spent_on')->orderByDesc('id')->get();
if ($models->isEmpty()) {
return [];
}
$jobs = $this->jobs->findMany($models->pluck('customer_job_id')->unique()->values()->all());
$names = $this->users->namesByIds($models->pluck('user_id')->merge($models->pluck('recorded_by'))->unique()->values()->all());
return $models
->map(fn (ExpenseModel $model): ExpenseSummary => new ExpenseSummary(
$model->id,
$jobs[$model->customer_job_id] ?? new ExpenseJob($model->customer_job_id, '', '', true),
$model->user_id,
$names[$model->user_id] ?? '',
$model->recorded_by,
$names[$model->recorded_by] ?? '',
$model->category,
$model->paid_by,
$model->spent_on->toDateString(),
$model->description,
$model->cost_cents,
$model->kilometers === null ? null : (int) round((float) $model->kilometers * 10),
$model->destination,
$model->purpose,
$model->is_billable,
$model->markup_basis_points,
$model->billed_amount_cents,
))
->values()
->all();
}
}
@@ -0,0 +1,82 @@
<?php
namespace App\Modules\Expenses\Infrastructure\Persistence\Repositories;
use App\Modules\Expenses\Domain\Contracts\ExpenseRepository;
use App\Modules\Expenses\Domain\Entities\Expense;
use App\Modules\Expenses\Domain\ValueObjects\ExpenseBilling;
use App\Modules\Expenses\Domain\ValueObjects\ExpenseDetails;
use App\Modules\Expenses\Domain\ValueObjects\Kilometers;
use App\Modules\Expenses\Domain\ValueObjects\MarkupPercentage;
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
use App\Modules\Shared\Domain\ValueObjects\Money;
use DateTimeImmutable;
class EloquentExpenseRepository implements ExpenseRepository
{
public function findById(int $id): ?Expense
{
$model = ExpenseModel::query()->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(Expense $expense): Expense
{
$model = $expense->id() === null ? new ExpenseModel : ExpenseModel::query()->findOrFail($expense->id());
$details = $expense->details();
$model->fill([
'customer_job_id' => $expense->jobId(),
'user_id' => $expense->userId(),
'recorded_by' => $expense->recordedBy(),
'category' => $details->category,
'paid_by' => $details->paidBy,
'spent_on' => $details->spentOn->format('Y-m-d'),
'description' => $details->description,
'cost_cents' => $details->cost->cents,
'kilometers' => $details->kilometers === null ? null : $details->kilometers->tenths / 10,
'destination' => $details->destination,
'purpose' => $details->purpose,
'is_billable' => $details->isBillable(),
'markup_basis_points' => $details->billing?->markup?->basisPoints,
'billed_amount_cents' => $details->billing?->amount->cents,
])->save();
return $this->toEntity($model->refresh());
}
public function delete(Expense $expense): void
{
ExpenseModel::query()->whereKey($expense->id())->delete();
}
private function toEntity(ExpenseModel $model): Expense
{
$billing = $model->is_billable && $model->billed_amount_cents !== null
? ExpenseBilling::for(
Money::fromCents($model->cost_cents),
$model->markup_basis_points === null ? null : new MarkupPercentage($model->markup_basis_points),
Money::fromCents($model->billed_amount_cents),
)
: null;
return Expense::reconstitute(
$model->id,
$model->customer_job_id,
$model->user_id,
$model->recorded_by,
ExpenseDetails::reconstitute(
$model->category,
$model->paid_by,
DateTimeImmutable::createFromInterface($model->spent_on),
$model->description,
Money::fromCents($model->cost_cents),
$model->kilometers === null ? null : new Kilometers((int) round((float) $model->kilometers * 10)),
$model->destination,
$model->purpose,
$billing,
),
);
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Modules\Expenses\Infrastructure;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Expenses\Application\Contracts\ExpensePricing;
/**
* Expense prices from the Catalog module's price list.
*/
class PriceListForExpenses implements ExpensePricing
{
public function __construct(private PriceListQueries $priceList) {}
public function mileageRateCents(): ?int
{
return $this->priceList->mileageRateCents();
}
public function defaultMarkupBasisPoints(): int
{
return $this->priceList->defaultExpenseMarkupBasisPoints();
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Modules\Expenses\Infrastructure\Providers;
use App\Models\User;
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\Domain\Contracts\ExpenseRepository;
use App\Modules\Expenses\Infrastructure\JobsForExpenses;
use App\Modules\Expenses\Infrastructure\Persistence\Repositories\EloquentExpenseQueries;
use App\Modules\Expenses\Infrastructure\Persistence\Repositories\EloquentExpenseRepository;
use App\Modules\Expenses\Infrastructure\PriceListForExpenses;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Expenses module (expenses on customer jobs) into Laravel:
* bindings, routes, the `expenses::` Livewire namespace and the
* `expenses.*` abilities.
*/
class ExpensesServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
ExpenseRepository::class => EloquentExpenseRepository::class,
ExpenseQueries::class => EloquentExpenseQueries::class,
ExpenseJobs::class => JobsForExpenses::class,
ExpensePricing::class => PriceListForExpenses::class,
];
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('expenses', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
// Everyone may list their own expenses; subcontractors' are recorded by management (spec 10).
Gate::define('expenses.use', fn (User $user): bool => true);
Gate::define('expenses.record', fn (User $user): bool => $user->role !== Role::Subcontractor);
// Admins and management record expenses for others, e.g. subcontractors.
Gate::define('expenses.record-for-others', fn (User $user): bool => $user->role->seesAllMoney());
Gate::define('expenses.change', fn (User $user, int $ownerId, int $recordedBy): bool => $user->role->seesAllMoney()
|| ($user->role !== Role::Subcontractor && in_array($user->id, [$ownerId, $recordedBy], true)));
// Everyone sees the amounts of their own expenses; others' need the expenses permission.
Gate::define('expenses.see-amount', fn (User $user, int $ownerId, int $recordedBy): bool => in_array($user->id, [$ownerId, $recordedBy], true)
|| $user->can('money.expenses'));
}
}
@@ -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');
});