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:
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
|
|
||||||
## Project
|
## Project
|
||||||
|
|
||||||
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) and `TimeTracking` (hours on tasks: weekly sheet and task booking page)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
|
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) and `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
|
||||||
|
|
||||||
- **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec.
|
- **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec.
|
||||||
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
|
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
|
||||||
@@ -22,7 +22,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
|
|||||||
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
|
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
|
||||||
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
|
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
|
||||||
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules.
|
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules.
|
||||||
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`, `catalog.view-prices`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
|
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
|
||||||
- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP.
|
- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP.
|
||||||
- **Security headers** (`X-Frame-Options`, `frame-ancestors`, `nosniff`, `Referrer-Policy`, HSTS over HTTPS) come from the global `Shared\Presentation\Http\Middleware\SetSecurityHeaders`, pushed in `SharedServiceProvider`. No full CSP: Alpine/Livewire need `unsafe-eval`.
|
- **Security headers** (`X-Frame-Options`, `frame-ancestors`, `nosniff`, `Referrer-Policy`, HSTS over HTTPS) come from the global `Shared\Presentation\Http\Middleware\SetSecurityHeaders`, pushed in `SharedServiceProvider`. No full CSP: Alpine/Livewire need `unsafe-eval`.
|
||||||
- Money is `Shared\Domain\ValueObjects\Money` (whole cents, `parse()` accepts "85,50", `format()` gives "85,50 €", `addVat()`/`removeVat()` with a `VatPercentage` round half up); store it in `*_cents` integer columns. Prices are without VAT except consumer product prices, which are stored with VAT. Show other than consumer prices only behind `money.prices` and keep amounts out of public Livewire properties. App-wide settings go through `Shared\Application\Contracts\Settings` (`settings` table) with keys prefixed by the owning module.
|
- Money is `Shared\Domain\ValueObjects\Money` (whole cents, `parse()` accepts "85,50", `format()` gives "85,50 €", `addVat()`/`removeVat()` with a `VatPercentage` round half up); store it in `*_cents` integer columns. Prices are without VAT except consumer product prices, which are stored with VAT. Show other than consumer prices only behind `money.prices` and keep amounts out of public Livewire properties. App-wide settings go through `Shared\Application\Contracts\Settings` (`settings` table) with keys prefixed by the owning module.
|
||||||
|
|||||||
@@ -44,6 +44,11 @@ interface PriceListQueries
|
|||||||
*/
|
*/
|
||||||
public function mileageRateCents(): ?int;
|
public function mileageRateCents(): ?int;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Markup suggested for new purchase expenses, in hundredths of a percent (0 when not set).
|
||||||
|
*/
|
||||||
|
public function defaultExpenseMarkupBasisPoints(): int;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return list<VatRateSummary>
|
* @return list<VatRateSummary>
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Modules\Catalog\Application\UseCases;
|
||||||
|
|
||||||
|
use App\Modules\Shared\Application\Contracts\Settings;
|
||||||
|
use App\Modules\Shared\Domain\Exceptions\InvalidVatPercentage;
|
||||||
|
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the markup suggested for new purchase expenses, e.g. "15" for 15 %;
|
||||||
|
* an empty value means no markup. Stored in hundredths of a percent.
|
||||||
|
*/
|
||||||
|
final class SetDefaultExpenseMarkup
|
||||||
|
{
|
||||||
|
public const string SETTING_KEY = 'catalog.expense_markup_basis_points';
|
||||||
|
|
||||||
|
public function __construct(private Settings $settings) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return int The stored markup in hundredths of a percent.
|
||||||
|
*
|
||||||
|
* @throws InvalidVatPercentage When the value is not 0–100 % with at most two decimals.
|
||||||
|
*/
|
||||||
|
public function execute(string $markup): int
|
||||||
|
{
|
||||||
|
$basisPoints = trim($markup) === '' ? 0 : VatPercentage::parse($markup)->basisPoints;
|
||||||
|
|
||||||
|
$this->settings->put(self::SETTING_KEY, $basisPoints === 0 ? null : (string) $basisPoints);
|
||||||
|
|
||||||
|
return $basisPoints;
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
@@ -10,6 +10,7 @@ use App\Modules\Catalog\Application\DTOs\ProductSummary;
|
|||||||
use App\Modules\Catalog\Application\DTOs\ServiceUnitNode;
|
use App\Modules\Catalog\Application\DTOs\ServiceUnitNode;
|
||||||
use App\Modules\Catalog\Application\DTOs\VatRateSummary;
|
use App\Modules\Catalog\Application\DTOs\VatRateSummary;
|
||||||
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
|
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
|
||||||
|
use App\Modules\Catalog\Application\UseCases\SetDefaultExpenseMarkup;
|
||||||
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
|
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
|
||||||
use App\Modules\Catalog\Domain\Enums\ProductUnit;
|
use App\Modules\Catalog\Domain\Enums\ProductUnit;
|
||||||
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
|
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
|
||||||
@@ -124,6 +125,11 @@ class EloquentPriceListQueries implements PriceListQueries
|
|||||||
return $value === null ? null : (int) $value;
|
return $value === null ? null : (int) $value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function defaultExpenseMarkupBasisPoints(): int
|
||||||
|
{
|
||||||
|
return (int) ($this->settings->get(SetDefaultExpenseMarkup::SETTING_KEY) ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
private function toVatRateSummary(VatRateModel $model): VatRateSummary
|
private function toVatRateSummary(VatRateModel $model): VatRateSummary
|
||||||
{
|
{
|
||||||
return new VatRateSummary($model->id, $model->name, $model->basis_points, $model->is_default, $model->is_active);
|
return new VatRateSummary($model->id, $model->name, $model->basis_points, $model->is_default, $model->is_active);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use App\Modules\Catalog\Application\DTOs\ProductSummary;
|
|||||||
use App\Modules\Catalog\Application\DTOs\VatRateSummary;
|
use App\Modules\Catalog\Application\DTOs\VatRateSummary;
|
||||||
use App\Modules\Catalog\Application\UseCases\MoveProduct;
|
use App\Modules\Catalog\Application\UseCases\MoveProduct;
|
||||||
use App\Modules\Catalog\Application\UseCases\MoveVatRate;
|
use App\Modules\Catalog\Application\UseCases\MoveVatRate;
|
||||||
|
use App\Modules\Catalog\Application\UseCases\SetDefaultExpenseMarkup;
|
||||||
use App\Modules\Catalog\Application\UseCases\SetHourlyRate;
|
use App\Modules\Catalog\Application\UseCases\SetHourlyRate;
|
||||||
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
|
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
|
||||||
use App\Modules\Catalog\Application\UseCases\SetProductActive;
|
use App\Modules\Catalog\Application\UseCases\SetProductActive;
|
||||||
@@ -18,6 +19,7 @@ use App\Modules\Catalog\Domain\Exceptions\ProductNotFound;
|
|||||||
use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound;
|
use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound;
|
||||||
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
|
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
|
||||||
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
|
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
|
||||||
|
use App\Modules\Shared\Domain\Exceptions\InvalidVatPercentage;
|
||||||
use App\Modules\Shared\Domain\ValueObjects\Money;
|
use App\Modules\Shared\Domain\ValueObjects\Money;
|
||||||
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
|
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
|
||||||
use Livewire\Attributes\Computed;
|
use Livewire\Attributes\Computed;
|
||||||
@@ -47,6 +49,8 @@ new class extends Component
|
|||||||
|
|
||||||
public string $mileageRate = '';
|
public string $mileageRate = '';
|
||||||
|
|
||||||
|
public string $expenseMarkup = '';
|
||||||
|
|
||||||
protected PriceListQueries $priceList;
|
protected PriceListQueries $priceList;
|
||||||
|
|
||||||
public function boot(PriceListQueries $priceList): void
|
public function boot(PriceListQueries $priceList): void
|
||||||
@@ -59,6 +63,8 @@ new class extends Component
|
|||||||
$this->authorize('catalog.manage');
|
$this->authorize('catalog.manage');
|
||||||
|
|
||||||
$this->mileageRate = $this->inputValue($this->priceList->mileageRateCents());
|
$this->mileageRate = $this->inputValue($this->priceList->mileageRateCents());
|
||||||
|
$markup = $this->priceList->defaultExpenseMarkupBasisPoints();
|
||||||
|
$this->expenseMarkup = $markup === 0 ? '' : (new VatPercentage($markup))->inputValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -177,6 +183,26 @@ new class extends Component
|
|||||||
$this->statusMessage = __($product->isActive ? 'catalog.products.deactivated' : 'catalog.status.activated', ['name' => $product->name]);
|
$this->statusMessage = __($product->isActive ? 'catalog.products.deactivated' : 'catalog.status.activated', ['name' => $product->name]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function saveExpenseMarkup(SetDefaultExpenseMarkup $setMarkup): void
|
||||||
|
{
|
||||||
|
$this->authorize('catalog.manage');
|
||||||
|
|
||||||
|
$this->resetErrorBag('expenseMarkup');
|
||||||
|
|
||||||
|
try {
|
||||||
|
$markup = $setMarkup->execute($this->expenseMarkup);
|
||||||
|
} catch (InvalidVatPercentage) {
|
||||||
|
$this->addError('expenseMarkup', __('catalog.errors.invalid_markup'));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->expenseMarkup = $markup === 0 ? '' : (new VatPercentage($markup))->inputValue();
|
||||||
|
$this->statusMessage = $markup === 0
|
||||||
|
? __('catalog.expense_markup.removed')
|
||||||
|
: __('catalog.expense_markup.saved', ['markup' => (new VatPercentage($markup))->format()]);
|
||||||
|
}
|
||||||
|
|
||||||
public function saveMileageRate(SetMileageRate $setMileageRate): void
|
public function saveMileageRate(SetMileageRate $setMileageRate): void
|
||||||
{
|
{
|
||||||
$this->authorize('catalog.manage');
|
$this->authorize('catalog.manage');
|
||||||
@@ -473,7 +499,7 @@ new class extends Component
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section aria-labelledby="mileage-heading" class="space-y-4">
|
<section aria-labelledby="mileage-heading" class="space-y-4">
|
||||||
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.mileage.title') }}</h2>
|
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.expense_markup.section') }}</h2>
|
||||||
|
|
||||||
<form wire:submit="saveMileageRate" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
|
<form wire:submit="saveMileageRate" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
|
||||||
<div class="min-w-40 flex-1">
|
<div class="min-w-40 flex-1">
|
||||||
@@ -487,5 +513,18 @@ new class extends Component
|
|||||||
</div>
|
</div>
|
||||||
<x-button submit :text="__('catalog.save')" />
|
<x-button submit :text="__('catalog.save')" />
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<form wire:submit="saveExpenseMarkup" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
|
||||||
|
<div class="min-w-40 flex-1">
|
||||||
|
<x-input
|
||||||
|
wire:model="expenseMarkup"
|
||||||
|
:label="__('catalog.expense_markup.label')"
|
||||||
|
:hint="__('catalog.expense_markup.help')"
|
||||||
|
inputmode="decimal"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<x-button submit :text="__('catalog.save')" />
|
||||||
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -206,7 +206,7 @@ new class extends Component
|
|||||||
|
|
||||||
<div class="space-y-1">
|
<div class="space-y-1">
|
||||||
<x-input
|
<x-input
|
||||||
wire:model.blur="form.price"
|
wire:model.live.blur="form.price"
|
||||||
:label="__($form->is_consumer_product ? 'catalog.products.price_gross' : 'catalog.products.price_net')"
|
:label="__($form->is_consumer_product ? 'catalog.products.price_gross' : 'catalog.products.price_net')"
|
||||||
:hint="__($form->is_consumer_product ? 'catalog.products.price_gross_help' : 'catalog.products.price_help')"
|
:hint="__($form->is_consumer_product ? 'catalog.products.price_gross_help' : 'catalog.products.price_help')"
|
||||||
inputmode="decimal"
|
inputmode="decimal"
|
||||||
|
|||||||
@@ -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',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
+84
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+82
@@ -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');
|
||||||
|
});
|
||||||
@@ -33,6 +33,14 @@ interface CustomerJobQueries
|
|||||||
|
|
||||||
public function findDetails(int $id): ?CustomerJobDetails;
|
public function findDetails(int $id): ?CustomerJobDetails;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Summaries of the given jobs, keyed by id; unknown ids are left out.
|
||||||
|
*
|
||||||
|
* @param list<int> $ids
|
||||||
|
* @return array<int, CustomerJobSummary>
|
||||||
|
*/
|
||||||
|
public function summariesByIds(array $ids): array;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The job's history, newest first.
|
* The job's history, newest first.
|
||||||
*
|
*
|
||||||
|
|||||||
+17
@@ -101,6 +101,23 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function summariesByIds(array $ids): array
|
||||||
|
{
|
||||||
|
if ($ids === []) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$models = CustomerJobModel::query()->whereIn('id', $ids)->get();
|
||||||
|
$toSummary = $this->summaryMapper($models);
|
||||||
|
$summaries = [];
|
||||||
|
|
||||||
|
foreach ($models as $model) {
|
||||||
|
$summaries[$model->id] = $toSummary($model);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $summaries;
|
||||||
|
}
|
||||||
|
|
||||||
public function findDetails(int $id): ?CustomerJobDetails
|
public function findDetails(int $id): ?CustomerJobDetails
|
||||||
{
|
{
|
||||||
$model = CustomerJobModel::query()->find($id);
|
$model = CustomerJobModel::query()->find($id);
|
||||||
|
|||||||
@@ -405,6 +405,13 @@ new class extends Component
|
|||||||
</x-confirm-dialog>
|
</x-confirm-dialog>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
@can('expenses.record')
|
||||||
|
<section aria-labelledby="expenses-heading" class="space-y-3">
|
||||||
|
<h2 id="expenses-heading" class="text-xl font-semibold">{{ __('jobs.sections.expenses') }}</h2>
|
||||||
|
<x-link :href="route('expenses.job', $job->id)" navigate>{{ __('expenses.job_page.link') }}</x-link>
|
||||||
|
</section>
|
||||||
|
@endcan
|
||||||
|
|
||||||
<section aria-labelledby="links-heading" class="space-y-3">
|
<section aria-labelledby="links-heading" class="space-y-3">
|
||||||
<h2 id="links-heading" class="text-xl font-semibold">{{ __('jobs.sections.links') }}</h2>
|
<h2 id="links-heading" class="text-xl font-semibold">{{ __('jobs.sections.links') }}</h2>
|
||||||
|
|
||||||
|
|||||||
@@ -60,7 +60,16 @@ final readonly class Money
|
|||||||
*/
|
*/
|
||||||
public function addVat(VatPercentage $vat): self
|
public function addVat(VatPercentage $vat): self
|
||||||
{
|
{
|
||||||
return new self(intdiv($this->cents * (10_000 + $vat->basisPoints) * 2 + 10_000, 20_000));
|
return $this->addPercent($vat->basisPoints);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This amount plus a percentage given in hundredths of a percent (1500 =
|
||||||
|
* 15 %), e.g. a markup, rounded half up to the cent.
|
||||||
|
*/
|
||||||
|
public function addPercent(int $basisPoints): self
|
||||||
|
{
|
||||||
|
return new self(intdiv($this->cents * (10_000 + $basisPoints) * 2 + 10_000, 20_000));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider;
|
use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider;
|
||||||
use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider;
|
use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider;
|
||||||
|
use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider;
|
||||||
use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider;
|
use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider;
|
||||||
use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider;
|
use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider;
|
||||||
use App\Modules\TimeTracking\Infrastructure\Providers\TimeTrackingServiceProvider;
|
use App\Modules\TimeTracking\Infrastructure\Providers\TimeTrackingServiceProvider;
|
||||||
@@ -18,4 +19,5 @@ return [
|
|||||||
JobsServiceProvider::class,
|
JobsServiceProvider::class,
|
||||||
// After Jobs: replaces its TaskUsage binding.
|
// After Jobs: replaces its TaskUsage binding.
|
||||||
TimeTrackingServiceProvider::class,
|
TimeTrackingServiceProvider::class,
|
||||||
|
ExpensesServiceProvider::class,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Database\Factories;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
|
||||||
|
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
|
||||||
|
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
|
||||||
|
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
|
||||||
|
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @extends Factory<ExpenseModel>
|
||||||
|
*/
|
||||||
|
class ExpenseFactory extends Factory
|
||||||
|
{
|
||||||
|
protected $model = ExpenseModel::class;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function definition(): array
|
||||||
|
{
|
||||||
|
$cost = fake()->numberBetween(500, 50000);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'customer_job_id' => CustomerJobModel::factory(),
|
||||||
|
'user_id' => User::factory(),
|
||||||
|
'recorded_by' => fn (array $attributes): int => $attributes['user_id'],
|
||||||
|
'category' => ExpenseCategory::Materials,
|
||||||
|
'paid_by' => ExpensePayer::Company,
|
||||||
|
'spent_on' => fake()->dateTimeBetween('-1 month')->format('Y-m-d'),
|
||||||
|
'description' => fake()->words(3, true),
|
||||||
|
'cost_cents' => $cost,
|
||||||
|
'kilometers' => null,
|
||||||
|
'destination' => null,
|
||||||
|
'purpose' => null,
|
||||||
|
'is_billable' => true,
|
||||||
|
'markup_basis_points' => null,
|
||||||
|
'billed_amount_cents' => $cost,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function mileage(float $kilometers = 40, int $rateCents = 59): static
|
||||||
|
{
|
||||||
|
$cost = (int) round($kilometers * $rateCents);
|
||||||
|
|
||||||
|
return $this->state(fn (): array => [
|
||||||
|
'category' => ExpenseCategory::Mileage,
|
||||||
|
'description' => null,
|
||||||
|
'kilometers' => $kilometers,
|
||||||
|
'destination' => 'Tampere',
|
||||||
|
'purpose' => 'Asiakastapaaminen',
|
||||||
|
'cost_cents' => $cost,
|
||||||
|
'billed_amount_cents' => $cost,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function paidByEmployee(): static
|
||||||
|
{
|
||||||
|
return $this->state(fn (): array => ['paid_by' => ExpensePayer::Employee]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function notBillable(): static
|
||||||
|
{
|
||||||
|
return $this->state(fn (): array => ['is_billable' => false, 'markup_basis_points' => null, 'billed_amount_cents' => null]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Expenses on customer jobs. Amounts are in cents without VAT; the
|
||||||
|
* billed amount is null when the expense is not billed to the customer.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('expenses', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('customer_job_id')->constrained()->restrictOnDelete();
|
||||||
|
$table->foreignId('user_id')->constrained()->restrictOnDelete();
|
||||||
|
$table->foreignId('recorded_by')->constrained('users')->restrictOnDelete();
|
||||||
|
$table->string('category', 20);
|
||||||
|
$table->string('paid_by', 20);
|
||||||
|
$table->date('spent_on');
|
||||||
|
$table->string('description', 255)->nullable();
|
||||||
|
$table->unsignedInteger('cost_cents');
|
||||||
|
$table->decimal('kilometers', 7, 1)->nullable();
|
||||||
|
$table->string('destination', 255)->nullable();
|
||||||
|
$table->string('purpose', 255)->nullable();
|
||||||
|
$table->boolean('is_billable')->default(true);
|
||||||
|
$table->unsignedInteger('markup_basis_points')->nullable();
|
||||||
|
$table->unsignedInteger('billed_amount_cents')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->index(['customer_job_id', 'spent_on']);
|
||||||
|
$table->index(['user_id', 'spent_on']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('expenses');
|
||||||
|
}
|
||||||
|
};
|
||||||
+14
-4
@@ -261,10 +261,14 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä
|
|||||||
## 10. Kulut *(K42–K45)*
|
## 10. Kulut *(K42–K45)*
|
||||||
|
|
||||||
- Kululajit: tuotteet, tarvikkeet ja materiaalit; matkakilometrit; muut hankinnat ja työkalut.
|
- Kululajit: tuotteet, tarvikkeet ja materiaalit; matkakilometrit; muut hankinnat ja työkalut.
|
||||||
- Kulun tyyppi: **suora kustannus** (laskutetaan asiakkaalta) tai **kulukorvaus** (työntekijän itse maksama, maksetaan takaisin).
|
- **Maksaja**: yritys tai työntekijä itse. Työntekijän itse maksamat kulut korvataan muun järjestelmän kautta; tämä järjestelmä ei seuraa korvausten maksua.
|
||||||
|
- **Laskutettavuus** on maksajasta erillinen tieto ("Laskutetaan asiakkaalta", oletus kyllä). Laskutettavalla kululla on laskutettava summa: annettu summa tai hankintahinta + kate (%). Uusien hankintakulujen kate esitäytetään hinnaston oletuskatteesta; kilometrikuluille ei katetta oletuksena.
|
||||||
- Summat kirjataan verottomina (ALV 0). Ei kuittikuvia.
|
- Summat kirjataan verottomina (ALV 0). Ei kuittikuvia.
|
||||||
- Kilometrikulu: päivämäärä, kohde, kilometrit, tarkoitus; hinta hinnaston km-hinnasta.
|
- Kilometrikulu: päivämäärä, kohde, kilometrit (0,1 km tarkkuus), tarkoitus; hankintahinta = km × hinnaston km-hinta kirjaushetkellä.
|
||||||
- Alihankkijan kulut kirjaa johto.
|
- Kulut kirjataan asiakastyön Kulut-sivulla; valikon "Kulut" näyttää käyttäjän omat kulut kuukausittain.
|
||||||
|
- Kirjaaja näkee aina omat kulunsa summineen; muiden kulujen summat näkyvät vain Kulut-oikeudella (2.3).
|
||||||
|
- Alihankkijan kulut kirjaa johto; alihankkija näkee ne omissa kuluissaan, mutta ei voi muuttaa niitä.
|
||||||
|
- Valmiin työn kuluja ei voi lisätä, muuttaa eikä poistaa.
|
||||||
|
|
||||||
## 11. Palveluyksiköt, hinnasto ja pohjatiedot *(K28–K30)*
|
## 11. Palveluyksiköt, hinnasto ja pohjatiedot *(K28–K30)*
|
||||||
|
|
||||||
@@ -356,7 +360,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
|
|||||||
- `time_entries`: `user_id`, `task_id`, `customer_job_id` (denormalisoitu), `work_type_id` (tehtävän työtehtävä kirjaushetkellä), `worked_on`, `hours`, `note` *(olemassa; uniikki käyttäjä + tehtävä + päivä)*, `approved_at` *(V2)*, `approved_by` *(V2)*, `billing_export_id` *(V2)*
|
- `time_entries`: `user_id`, `task_id`, `customer_job_id` (denormalisoitu), `work_type_id` (tehtävän työtehtävä kirjaushetkellä), `worked_on`, `hours`, `note` *(olemassa; uniikki käyttäjä + tehtävä + päivä)*, `approved_at` *(V2)*, `approved_by` *(V2)*, `billing_export_id` *(V2)*
|
||||||
|
|
||||||
**Expenses** *(V2)*
|
**Expenses** *(V2)*
|
||||||
- `expenses`: `customer_job_id`, `user_id`, `category` (`materials`/`mileage`/`other`), `kind` (`direct_cost`/`reimbursement`), `spent_on`, `description`, `amount_cents`, `kilometers`, `destination`, `purpose`, `billing_export_id`
|
- `expenses` *(olemassa)*: `customer_job_id`, `user_id` (kenen kulu), `recorded_by`, `category` (`materials`/`mileage`/`other`), `paid_by` (`company`/`employee`), `spent_on`, `description`, `cost_cents` (hankintahinta), `kilometers` (decimal 7,1), `destination`, `purpose`, `is_billable`, `markup_basis_points`, `billed_amount_cents` (laskutettava summa, null jos ei laskuteta); `billing_export_id` lisätään laskutuksen osassa
|
||||||
|
|
||||||
**Sales** *(V2)*
|
**Sales** *(V2)*
|
||||||
- `quick_sales`: `user_id`, `customer_id` (nullable), `payment_method` (`cash`/`card`), `sold_at`, `total_cents`
|
- `quick_sales`: `user_id`, `customer_id` (nullable), `payment_method` (`cash`/`card`), `sold_at`, `total_cents`
|
||||||
@@ -448,6 +452,12 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
|
|||||||
- Työntekijä ja harjoittelija näkevät valikon Hinnasto-linkistä lukusivun (`/catalog/price-list`): kuluttajatuotteet verollisine hintoineen aina; tuntihinnat, muut tuotteet (veroton ja verollinen hinta) ja km-hinta vain Hinnat-oikeudella. Alihankkija ei näe sivua.
|
- Työntekijä ja harjoittelija näkevät valikon Hinnasto-linkistä lukusivun (`/catalog/price-list`): kuluttajatuotteet verollisine hintoineen aina; tuntihinnat, muut tuotteet (veroton ja verollinen hinta) ja km-hinta vain Hinnat-oikeudella. Alihankkija ei näe sivua.
|
||||||
- Hinnaston hallinnassa ylläpidetään ALV-kantoja (lisäys, muokkaus, järjestys, käytöstä poisto, oletuskanta). Tuotelomakkeella valitaan ALV-kanta, ja hintakentän nimi kertoo, syötetäänkö hinta verollisena (kuluttajatuote) vai verottomana; toinen hinta näytetään laskettuna.
|
- Hinnaston hallinnassa ylläpidetään ALV-kantoja (lisäys, muokkaus, järjestys, käytöstä poisto, oletuskanta). Tuotelomakkeella valitaan ALV-kanta, ja hintakentän nimi kertoo, syötetäänkö hinta verollisena (kuluttajatuote) vai verottomana; toinen hinta näytetään laskettuna.
|
||||||
|
|
||||||
|
### 17.3 Kulut *(valmis)*
|
||||||
|
- Asiakastyön sivulla on linkki työn Kulut-sivulle (`/expenses/jobs/{job}`): kulujen lista, lisäys, muokkaus ja poisto (vahvistus dialogissa). Yhteissummat näkyvät Kulut-oikeudella.
|
||||||
|
- Kululomake: laji, päivä, maksaja, kenen kulu (vain johto), kuvaus ja hankintahinta tai kilometrit, kohde ja tarkoitus; laskutus (laskutetaan kyllä/ei, kate %, laskutettava summa). Laskettu kilometrihinta ja laskutettava summa näytetään ja ilmoitetaan ruudunlukijalle.
|
||||||
|
- Valikon "Kulut" (`/expenses`) näyttää omat kulut kuukausittain summineen.
|
||||||
|
- Hinnastoon lisättiin kulujen oletuskate.
|
||||||
|
|
||||||
## 18. Avoimet kysymykset
|
## 18. Avoimet kysymykset
|
||||||
|
|
||||||
1. **Lukitus**: voiko johto avata valmiin työn tunti- ja kululukituksen, jos jotain unohtui? (Ehdotus: kyllä, ja avaus kirjataan muutoshistoriaan.)
|
1. **Lukitus**: voiko johto avata valmiin työn tunti- ja kululukituksen, jos jotain unohtui? (Ehdotus: kyllä, ja avaus kirjataan muutoshistoriaan.)
|
||||||
|
|||||||
@@ -145,6 +145,14 @@ return [
|
|||||||
'package' => 'paketti',
|
'package' => 'paketti',
|
||||||
],
|
],
|
||||||
|
|
||||||
|
'expense_markup' => [
|
||||||
|
'section' => 'Kulut',
|
||||||
|
'label' => 'Kulujen oletuskate (%)',
|
||||||
|
'help' => 'Ehdotetaan uusien hankintakulujen katteeksi, esim. 15. Kilometrikuluille ei lisätä katetta. Tyhjä kenttä: ei katetta.',
|
||||||
|
'saved' => 'Kulujen oletuskate :markup tallennettu.',
|
||||||
|
'removed' => 'Kulujen oletuskate poistettu.',
|
||||||
|
],
|
||||||
|
|
||||||
'mileage' => [
|
'mileage' => [
|
||||||
'title' => 'Km-hinta',
|
'title' => 'Km-hinta',
|
||||||
'rate' => 'Km-hinta (€/km, ALV 0)',
|
'rate' => 'Km-hinta (€/km, ALV 0)',
|
||||||
@@ -164,6 +172,7 @@ return [
|
|||||||
'name_taken' => 'Samalla tasolla on jo tämänniminen rivi.',
|
'name_taken' => 'Samalla tasolla on jo tämänniminen rivi.',
|
||||||
'service_not_in_unit' => 'Valittu palvelu kuuluu toiseen palveluyksikköön.',
|
'service_not_in_unit' => 'Valittu palvelu kuuluu toiseen palveluyksikköön.',
|
||||||
'shared_unit_has_no_services' => 'Kaikille yhteisille työtehtäville ei voi lisätä palveluja.',
|
'shared_unit_has_no_services' => 'Kaikille yhteisille työtehtäville ei voi lisätä palveluja.',
|
||||||
|
'invalid_markup' => 'Anna kate prosentteina väliltä 0–100, enintään kaksi desimaalia (esim. 15).',
|
||||||
'invalid_price' => 'Anna hinta euroina, esim. 85 tai 85,50 (enintään kaksi desimaalia, 0–1 000 000 €).',
|
'invalid_price' => 'Anna hinta euroina, esim. 85 tai 85,50 (enintään kaksi desimaalia, 0–1 000 000 €).',
|
||||||
'price_required' => 'Anna hinta.',
|
'price_required' => 'Anna hinta.',
|
||||||
'invalid_unit' => 'Valitse yksikkö listasta.',
|
'invalid_unit' => 'Valitse yksikkö listasta.',
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
'add' => 'Lisää kulu',
|
||||||
|
'save' => 'Tallenna',
|
||||||
|
'cancel' => 'Peruuta',
|
||||||
|
'edit' => 'Muokkaa',
|
||||||
|
'edit_named' => 'Muokkaa kulua: :expense, :day',
|
||||||
|
'remove' => 'Poista',
|
||||||
|
'remove_named' => 'Poista kulu: :expense, :day',
|
||||||
|
'removal_title' => 'Poistetaanko kulu?',
|
||||||
|
'remove_question' => 'Poistetaanko kulu ":expense" (:day)? Poistoa ei voi perua.',
|
||||||
|
'removed' => 'Kulu ":expense" poistettu.',
|
||||||
|
'saved' => 'Kulu tallennettu.',
|
||||||
|
'updated' => 'Kulu päivitetty.',
|
||||||
|
'actions' => 'Toiminnot',
|
||||||
|
'none' => 'Ei kuluja.',
|
||||||
|
'locked' => 'Työ on valmis, joten sen kuluja ei voi lisätä, muuttaa eikä poistaa.',
|
||||||
|
'locked_short' => 'Lukittu',
|
||||||
|
'hidden_amount' => 'Ei näytetä',
|
||||||
|
'not_billed' => 'Ei laskuteta',
|
||||||
|
'amounts_hidden_help' => 'Muiden kirjaamien kulujen summat näkyvät vain, jos pääkäyttäjä on antanut sinulle oikeuden kuluihin. Omat kulusi näet aina.',
|
||||||
|
'mileage_summary' => ':km km, :destination (:purpose)',
|
||||||
|
|
||||||
|
'categories' => [
|
||||||
|
'materials' => 'Tuotteet, tarvikkeet ja materiaalit',
|
||||||
|
'mileage' => 'Matkakilometrit',
|
||||||
|
'other' => 'Muut hankinnat ja työkalut',
|
||||||
|
],
|
||||||
|
|
||||||
|
'payers' => [
|
||||||
|
'company' => 'Yritys maksoi',
|
||||||
|
'employee' => 'Itse maksettu',
|
||||||
|
],
|
||||||
|
|
||||||
|
'fields' => [
|
||||||
|
'job' => 'Asiakastyö',
|
||||||
|
'category' => 'Kululaji',
|
||||||
|
'spent_on' => 'Päivämäärä',
|
||||||
|
'paid_by' => 'Maksaja',
|
||||||
|
'user' => 'Kenen kulu',
|
||||||
|
'what' => 'Kulu',
|
||||||
|
'description' => 'Kuvaus',
|
||||||
|
'note' => 'Lisätieto',
|
||||||
|
'cost' => 'Hankintahinta (€, ALV 0)',
|
||||||
|
'cost_column' => 'Hankinta (ALV 0)',
|
||||||
|
'billed_column' => 'Laskutetaan (ALV 0)',
|
||||||
|
'kilometers' => 'Kilometrit',
|
||||||
|
'destination' => 'Kohde',
|
||||||
|
'purpose' => 'Tarkoitus',
|
||||||
|
'is_billable' => 'Laskutetaan asiakkaalta',
|
||||||
|
'markup' => 'Kate (%)',
|
||||||
|
'billed_amount' => 'Laskutettava summa (€, ALV 0)',
|
||||||
|
],
|
||||||
|
|
||||||
|
'form' => [
|
||||||
|
'create_title' => 'Uusi kulu',
|
||||||
|
'edit_title' => 'Muokkaa kulua',
|
||||||
|
'user_help' => 'Johto kirjaa myös alihankkijoiden kulut.',
|
||||||
|
'description_help' => 'Mitä hankittiin, esim. tulostuspaperi.',
|
||||||
|
'cost_help' => 'Veroton hinta, esim. 24,90.',
|
||||||
|
'kilometers_help' => 'Ajetut kilometrit, esim. 42 tai 42,5. Hinta lasketaan hinnaston km-hinnasta.',
|
||||||
|
'mileage_rate' => 'Km-hinta :rate / km.',
|
||||||
|
'mileage_cost' => 'Hankintahinta: :km km × :rate = :cost',
|
||||||
|
'billing' => 'Laskutus',
|
||||||
|
'markup_help' => 'Lisätään hankintahintaan, esim. 15.',
|
||||||
|
'billed_amount_help' => 'Jätä tyhjäksi, niin laskutetaan hankintahinta + kate.',
|
||||||
|
'suggested_billed' => 'Laskutetaan :amount (hankintahinta + kate).',
|
||||||
|
],
|
||||||
|
|
||||||
|
'job_page' => [
|
||||||
|
'title' => 'Kulut: :job',
|
||||||
|
'list' => 'Kirjatut kulut',
|
||||||
|
'back_to_job' => 'Takaisin asiakastyöhön',
|
||||||
|
'link' => 'Näytä ja kirjaa työn kulut',
|
||||||
|
],
|
||||||
|
|
||||||
|
'mine' => [
|
||||||
|
'title' => 'Omat kulut',
|
||||||
|
'help' => 'Kulut kirjataan asiakastyön Kulut-sivulla. Itse maksetut kulut korvataan muuta kautta.',
|
||||||
|
'help_subcontractor' => 'Johto kirjaa kulusi. Tässä näet kuukauden kulut.',
|
||||||
|
'month_navigation' => 'Kuukauden valinta',
|
||||||
|
'previous' => 'Edellinen kuukausi',
|
||||||
|
'current' => 'Tämä kuukausi',
|
||||||
|
'next' => 'Seuraava kuukausi',
|
||||||
|
'total' => 'Yhteensä (hankintahinnat, ALV 0): :total',
|
||||||
|
],
|
||||||
|
|
||||||
|
'totals' => [
|
||||||
|
'cost' => 'Hankinnat yhteensä (ALV 0)',
|
||||||
|
'billed' => 'Laskutetaan yhteensä (ALV 0)',
|
||||||
|
],
|
||||||
|
|
||||||
|
'months' => ['Tammikuu', 'Helmikuu', 'Maaliskuu', 'Huhtikuu', 'Toukokuu', 'Kesäkuu', 'Heinäkuu', 'Elokuu', 'Syyskuu', 'Lokakuu', 'Marraskuu', 'Joulukuu'],
|
||||||
|
|
||||||
|
'errors' => [
|
||||||
|
'locked' => 'Työ on valmis, joten sen kuluja ei voi enää muuttaa.',
|
||||||
|
'not_found' => 'Kulua ei löytynyt. Päivitä sivu.',
|
||||||
|
'user_required' => 'Valitse, kenen kulu on.',
|
||||||
|
'category_required' => 'Valitse kululaji listasta.',
|
||||||
|
'payer_required' => 'Valitse maksaja listasta.',
|
||||||
|
'date_required' => 'Anna päivämäärä.',
|
||||||
|
'invalid_date' => 'Anna päivämäärä muodossa pp.kk.vvvv.',
|
||||||
|
'description_required' => 'Kerro, mitä hankittiin.',
|
||||||
|
'cost_required' => 'Anna hankintahinta.',
|
||||||
|
'invalid_amount' => 'Anna summa euroina, esim. 24 tai 24,90 (enintään kaksi desimaalia).',
|
||||||
|
'invalid_kilometers' => 'Anna kilometrit yhden desimaalin tarkkuudella, esim. 42 tai 42,5.',
|
||||||
|
'mileage_details_required' => 'Anna kilometrit, kohde ja tarkoitus.',
|
||||||
|
'mileage_rate_missing' => 'Hinnastossa ei ole km-hintaa. Pyydä johtoa lisäämään se.',
|
||||||
|
'invalid_markup' => 'Anna kate prosentteina, esim. 15 (enintään kaksi desimaalia).',
|
||||||
|
'text_too_long' => 'Teksti voi olla enintään 255 merkkiä.',
|
||||||
|
],
|
||||||
|
];
|
||||||
@@ -97,6 +97,7 @@ return [
|
|||||||
],
|
],
|
||||||
|
|
||||||
'sections' => [
|
'sections' => [
|
||||||
|
'expenses' => 'Kulut',
|
||||||
'basics' => 'Perustiedot',
|
'basics' => 'Perustiedot',
|
||||||
'schedule' => 'Aikataulu',
|
'schedule' => 'Aikataulu',
|
||||||
'classification' => 'Luokittelu',
|
'classification' => 'Luokittelu',
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ return [
|
|||||||
'quick_intake' => 'Pikavastaanotto',
|
'quick_intake' => 'Pikavastaanotto',
|
||||||
'board' => 'Kanban',
|
'board' => 'Kanban',
|
||||||
'time' => 'Tuntikirjaus',
|
'time' => 'Tuntikirjaus',
|
||||||
|
'expenses' => 'Kulut',
|
||||||
'customers' => 'Asiakkaat',
|
'customers' => 'Asiakkaat',
|
||||||
'users' => 'Käyttäjät',
|
'users' => 'Käyttäjät',
|
||||||
'catalog' => 'Pohjatiedot',
|
'catalog' => 'Pohjatiedot',
|
||||||
|
|||||||
@@ -61,6 +61,8 @@
|
|||||||
|
|
||||||
@include('partials.nav-item', ['route' => 'time.week', 'pattern' => 'time.*', 'label' => __('layout.time')])
|
@include('partials.nav-item', ['route' => 'time.week', 'pattern' => 'time.*', 'label' => __('layout.time')])
|
||||||
|
|
||||||
|
@include('partials.nav-item', ['route' => 'expenses.mine', 'pattern' => 'expenses.*', 'label' => __('layout.expenses')])
|
||||||
|
|
||||||
@can('jobs.manage')
|
@can('jobs.manage')
|
||||||
@include('partials.nav-item', ['route' => 'jobs.quick', 'pattern' => 'jobs.quick', 'label' => __('layout.quick_intake')])
|
@include('partials.nav-item', ['route' => 'jobs.quick', 'pattern' => 'jobs.quick', 'label' => __('layout.quick_intake')])
|
||||||
@endcan
|
@endcan
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
|
||||||
|
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
|
||||||
|
use App\Modules\Jobs\Domain\Enums\JobStatus;
|
||||||
|
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
|
||||||
|
use App\Modules\Shared\Application\Contracts\Settings;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
|
||||||
|
uses(RefreshDatabase::class);
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->user = User::factory()->employee()->create();
|
||||||
|
$this->actingAs($this->user);
|
||||||
|
app(Settings::class)->put(SetMileageRate::SETTING_KEY, '59');
|
||||||
|
$this->job = CustomerJobModel::factory()->create(['name' => 'Messuvideo', 'status' => JobStatus::Order]);
|
||||||
|
$this->purchase = ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->user->id, 'description' => 'Tulostuspaperi', 'spent_on' => now()->toDateString()]);
|
||||||
|
$this->mileage = ExpenseModel::factory()->mileage()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->user->id, 'spent_on' => now()->toDateString()]);
|
||||||
|
ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'description' => 'Kollegan hankinta']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('has no accessibility issues on the expense pages and no sideways scrolling', function (string $page, string $device, string $colorScheme) {
|
||||||
|
$url = match ($page) {
|
||||||
|
'job expenses' => route('expenses.job', $this->job->id),
|
||||||
|
'new expense' => route('expenses.create', $this->job->id),
|
||||||
|
'edit mileage' => route('expenses.edit', $this->mileage->id),
|
||||||
|
'own expenses' => route('expenses.mine'),
|
||||||
|
};
|
||||||
|
|
||||||
|
$visit = visit($url);
|
||||||
|
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
|
||||||
|
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||||
|
|
||||||
|
$visit->assertSee('Messuvideo')
|
||||||
|
->assertNoJavaScriptErrors()
|
||||||
|
->assertNoAccessibilityIssues(level: 2);
|
||||||
|
})->with(['job expenses', 'new expense', 'edit mileage', 'own expenses'])->with([
|
||||||
|
'desktop, light' => ['desktop', 'light'],
|
||||||
|
'desktop, dark' => ['desktop', 'dark'],
|
||||||
|
'mobile, light' => ['mobile', 'light'],
|
||||||
|
'mobile, dark' => ['mobile', 'dark'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('works out the cost of kilometres as they are typed', function () {
|
||||||
|
$field = '[wire\\:model\\.live\\.blur="form.kilometers"]';
|
||||||
|
|
||||||
|
visit(route('expenses.edit', $this->mileage->id))
|
||||||
|
->clear($field)
|
||||||
|
->type($field, '100')
|
||||||
|
->keys($field, 'Tab')
|
||||||
|
->assertSee('100 km × 0,59')
|
||||||
|
->assertSee('59,00')
|
||||||
|
->assertNoAccessibilityIssues(level: 2);
|
||||||
|
});
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Fakes;
|
||||||
|
|
||||||
|
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
|
||||||
|
use App\Modules\Expenses\Application\DTOs\ExpenseJob;
|
||||||
|
|
||||||
|
class FakeExpenseJobs implements ExpenseJobs
|
||||||
|
{
|
||||||
|
/** @var array<int, ExpenseJob> */
|
||||||
|
public array $jobs = [];
|
||||||
|
|
||||||
|
public function add(int $id, bool $locked = false): void
|
||||||
|
{
|
||||||
|
$this->jobs[$id] = new ExpenseJob($id, '2026-'.str_pad((string) $id, 4, '0', STR_PAD_LEFT), 'Työ '.$id, $locked);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function find(int $jobId): ?ExpenseJob
|
||||||
|
{
|
||||||
|
return $this->jobs[$jobId] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function findMany(array $jobIds): array
|
||||||
|
{
|
||||||
|
return array_intersect_key($this->jobs, array_flip($jobIds));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Fakes;
|
||||||
|
|
||||||
|
use App\Modules\Expenses\Application\Contracts\ExpensePricing;
|
||||||
|
|
||||||
|
class FakeExpensePricing implements ExpensePricing
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public ?int $mileageRateCents = 59,
|
||||||
|
public int $defaultMarkupBasisPoints = 0,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function mileageRateCents(): ?int
|
||||||
|
{
|
||||||
|
return $this->mileageRateCents;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function defaultMarkupBasisPoints(): int
|
||||||
|
{
|
||||||
|
return $this->defaultMarkupBasisPoints;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Fakes;
|
||||||
|
|
||||||
|
use App\Modules\Expenses\Domain\Contracts\ExpenseRepository;
|
||||||
|
use App\Modules\Expenses\Domain\Entities\Expense;
|
||||||
|
|
||||||
|
class InMemoryExpenseRepository implements ExpenseRepository
|
||||||
|
{
|
||||||
|
/** @var array<int, Expense> */
|
||||||
|
public array $items = [];
|
||||||
|
|
||||||
|
private int $nextId = 1;
|
||||||
|
|
||||||
|
public function findById(int $id): ?Expense
|
||||||
|
{
|
||||||
|
return isset($this->items[$id]) ? clone $this->items[$id] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(Expense $expense): Expense
|
||||||
|
{
|
||||||
|
$id = $expense->id() ?? $this->nextId++;
|
||||||
|
$this->items[$id] = Expense::reconstitute($id, $expense->jobId(), $expense->userId(), $expense->recordedBy(), $expense->details());
|
||||||
|
|
||||||
|
return clone $this->items[$id];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete(Expense $expense): void
|
||||||
|
{
|
||||||
|
unset($this->items[$expense->id()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Modules\Catalog\Application\UseCases\SetDefaultExpenseMarkup;
|
||||||
|
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
|
||||||
|
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
|
||||||
|
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
|
||||||
|
use App\Modules\Jobs\Domain\Enums\JobStatus;
|
||||||
|
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
|
||||||
|
use App\Modules\Shared\Application\Contracts\Settings;
|
||||||
|
use App\Modules\Users\Domain\Enums\MoneyPermission;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Livewire\Livewire;
|
||||||
|
|
||||||
|
uses(RefreshDatabase::class);
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']);
|
||||||
|
$this->job = CustomerJobModel::factory()->create(['name' => 'Messuvideo', 'status' => JobStatus::Order]);
|
||||||
|
app(Settings::class)->put(SetMileageRate::SETTING_KEY, '59');
|
||||||
|
$this->actingAs($this->employee);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records a purchase with the default markup', function () {
|
||||||
|
app(Settings::class)->put(SetDefaultExpenseMarkup::SETTING_KEY, '1500');
|
||||||
|
|
||||||
|
Livewire::test('expenses::form', ['job' => $this->job->id])
|
||||||
|
->assertSet('form.markup', '15')
|
||||||
|
->set('form.description', 'Tulostuspaperi')
|
||||||
|
->set('form.cost', '100')
|
||||||
|
->set('form.paid_by', 'employee')
|
||||||
|
->assertSee("Laskutetaan 115,00\u{00A0}€ (hankintahinta + kate).")
|
||||||
|
->call('save')
|
||||||
|
->assertHasNoErrors()
|
||||||
|
->assertRedirect(route('expenses.job', $this->job->id));
|
||||||
|
|
||||||
|
$expense = ExpenseModel::query()->sole();
|
||||||
|
|
||||||
|
expect($expense->only(['user_id', 'recorded_by', 'cost_cents', 'billed_amount_cents', 'markup_basis_points']))->toBe([
|
||||||
|
'user_id' => $this->employee->id,
|
||||||
|
'recorded_by' => $this->employee->id,
|
||||||
|
'cost_cents' => 10000,
|
||||||
|
'billed_amount_cents' => 11500,
|
||||||
|
'markup_basis_points' => 1500,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records kilometres priced with the mileage rate and no default markup', function () {
|
||||||
|
app(Settings::class)->put(SetDefaultExpenseMarkup::SETTING_KEY, '1500');
|
||||||
|
|
||||||
|
Livewire::test('expenses::form', ['job' => $this->job->id])
|
||||||
|
->set('form.category', 'mileage')
|
||||||
|
->assertSet('form.markup', '')
|
||||||
|
->set('form.kilometers', '40')
|
||||||
|
->assertSee("Hankintahinta: 40 km × 0,59\u{00A0}€ = 23,60\u{00A0}€")
|
||||||
|
->set('form.destination', 'Tampere')
|
||||||
|
->set('form.purpose', 'Kuvaukset')
|
||||||
|
->call('save')
|
||||||
|
->assertHasNoErrors();
|
||||||
|
|
||||||
|
expect(ExpenseModel::query()->sole()->only(['category', 'cost_cents', 'billed_amount_cents']))->toBe([
|
||||||
|
'category' => ExpenseCategory::Mileage,
|
||||||
|
'cost_cents' => 2360,
|
||||||
|
'billed_amount_cents' => 2360,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows expense rule violations as Finnish field errors', function (array $fields, string $field, string $message) {
|
||||||
|
$component = Livewire::test('expenses::form', ['job' => $this->job->id]);
|
||||||
|
|
||||||
|
foreach ($fields as $name => $value) {
|
||||||
|
$component->set("form.{$name}", $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
$component->call('save')->assertHasErrors(["form.{$field}" => [__($message)]]);
|
||||||
|
})->with([
|
||||||
|
'description' => [['cost' => '10'], 'description', 'expenses.errors.description_required'],
|
||||||
|
'cost' => [['description' => 'Paperi', 'cost' => '10,123'], 'cost', 'expenses.errors.invalid_amount'],
|
||||||
|
'billed amount' => [['description' => 'Paperi', 'cost' => '10', 'billed_amount' => 'x'], 'billed_amount', 'expenses.errors.invalid_amount'],
|
||||||
|
'mileage' => [['category' => 'mileage', 'kilometers' => '40', 'destination' => 'Tampere'], 'purpose', 'expenses.errors.mileage_details_required'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('hides the amounts of others\' expenses without the expenses permission', function () {
|
||||||
|
$colleague = User::factory()->employee()->create(['name' => 'Kaisa Kollega']);
|
||||||
|
ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->employee->id, 'description' => 'Oma hankinta', 'cost_cents' => 1234, 'billed_amount_cents' => 1234]);
|
||||||
|
ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $colleague->id, 'description' => 'Kollegan hankinta', 'cost_cents' => 9876, 'billed_amount_cents' => 9876]);
|
||||||
|
|
||||||
|
$this->get(route('expenses.job', $this->job->id))
|
||||||
|
->assertOk()
|
||||||
|
->assertSee('Oma hankinta')
|
||||||
|
->assertSee("12,34\u{00A0}€", false)
|
||||||
|
->assertSee('Kollegan hankinta')
|
||||||
|
->assertDontSee("98,76\u{00A0}€", false)
|
||||||
|
->assertDontSee(__('expenses.totals.cost'));
|
||||||
|
|
||||||
|
$this->actingAs(User::factory()->employee()->withMoneyPermissions(MoneyPermission::Expenses)->create())
|
||||||
|
->get(route('expenses.job', $this->job->id))
|
||||||
|
->assertSee("98,76\u{00A0}€", false)
|
||||||
|
->assertSee("111,10\u{00A0}€", false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('locks the expenses of a done job', function () {
|
||||||
|
$expense = ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->employee->id]);
|
||||||
|
$this->job->update(['status' => JobStatus::Done]);
|
||||||
|
|
||||||
|
$this->get(route('expenses.job', $this->job->id))
|
||||||
|
->assertSee(__('expenses.locked'))
|
||||||
|
->assertDontSee(route('expenses.create', $this->job->id), false)
|
||||||
|
->assertDontSee(route('expenses.edit', $expense->id), false);
|
||||||
|
|
||||||
|
Livewire::test('expenses::job', ['job' => $this->job->id])
|
||||||
|
->call('confirmRemoval', $expense->id)
|
||||||
|
->assertSet('removalExpenseId', null);
|
||||||
|
|
||||||
|
expect(ExpenseModel::query()->count())->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes an own expense after confirmation but not a colleague\'s', function () {
|
||||||
|
$own = ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->employee->id, 'description' => 'Paperi']);
|
||||||
|
$colleagues = ExpenseModel::factory()->create(['customer_job_id' => $this->job->id]);
|
||||||
|
|
||||||
|
Livewire::test('expenses::job', ['job' => $this->job->id])
|
||||||
|
->call('confirmRemoval', $colleagues->id)
|
||||||
|
->assertSet('removalExpenseId', null)
|
||||||
|
->call('confirmRemoval', $own->id)
|
||||||
|
->call('removeExpense')
|
||||||
|
->assertSet('statusMessage', 'Kulu "Paperi" poistettu.');
|
||||||
|
|
||||||
|
expect(ExpenseModel::query()->pluck('id')->all())->toBe([$colleagues->id]);
|
||||||
|
|
||||||
|
$this->get(route('expenses.edit', $colleagues->id))->assertForbidden();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets management record a subcontractor\'s expense, which the subcontractor sees but cannot change', function () {
|
||||||
|
$subcontractor = User::factory()->subcontractor()->create(['name' => 'Alihankkija Oy']);
|
||||||
|
$this->actingAs(User::factory()->management()->create());
|
||||||
|
|
||||||
|
Livewire::test('expenses::form', ['job' => $this->job->id])
|
||||||
|
->set('form.user_id', (string) $subcontractor->id)
|
||||||
|
->set('form.description', 'Vuokrakalusto')
|
||||||
|
->set('form.cost', '250')
|
||||||
|
->call('save')
|
||||||
|
->assertHasNoErrors();
|
||||||
|
|
||||||
|
$expense = ExpenseModel::query()->sole();
|
||||||
|
|
||||||
|
$this->actingAs($subcontractor)
|
||||||
|
->get(route('expenses.mine', ['kuukausi' => now()->format('Y-m')]))
|
||||||
|
->assertOk()
|
||||||
|
->assertSee('Vuokrakalusto')
|
||||||
|
->assertSee("250,00\u{00A0}€", false)
|
||||||
|
->assertDontSee(route('expenses.edit', $expense->id), false);
|
||||||
|
|
||||||
|
$this->get(route('expenses.job', $this->job->id))->assertForbidden();
|
||||||
|
$this->get(route('expenses.create', $this->job->id))->assertForbidden();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not let an employee record an expense for someone else', function () {
|
||||||
|
$colleague = User::factory()->employee()->create();
|
||||||
|
|
||||||
|
Livewire::test('expenses::form', ['job' => $this->job->id])
|
||||||
|
->set('form.user_id', (string) $colleague->id)
|
||||||
|
->set('form.description', 'Paperi')
|
||||||
|
->set('form.cost', '10')
|
||||||
|
->call('save')
|
||||||
|
->assertHasNoErrors();
|
||||||
|
|
||||||
|
expect(ExpenseModel::query()->sole()->user_id)->toBe($this->employee->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('links the job page to its expenses and shows the own expenses by month', function () {
|
||||||
|
ExpenseModel::factory()->create(['user_id' => $this->employee->id, 'spent_on' => '2026-10-15', 'description' => 'Lokakuun hankinta']);
|
||||||
|
|
||||||
|
$this->get(route('jobs.show', $this->job->id))->assertSee(route('expenses.job', $this->job->id), false);
|
||||||
|
|
||||||
|
$this->get(route('expenses.mine', ['kuukausi' => '2026-10']))
|
||||||
|
->assertOk()
|
||||||
|
->assertSee('Lokakuu 2026')
|
||||||
|
->assertSee('Lokakuun hankinta');
|
||||||
|
});
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Modules\Expenses\Application\DTOs\ExpenseData;
|
||||||
|
use App\Modules\Expenses\Application\UseCases\ExpenseDetailsFactory;
|
||||||
|
use App\Modules\Expenses\Application\UseCases\RecordExpense;
|
||||||
|
use App\Modules\Expenses\Application\UseCases\RemoveExpense;
|
||||||
|
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\ExpenseCostRequired;
|
||||||
|
use App\Modules\Expenses\Domain\Exceptions\ExpenseDescriptionRequired;
|
||||||
|
use App\Modules\Expenses\Domain\Exceptions\ExpenseJobNotFound;
|
||||||
|
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
|
||||||
|
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\InvalidMoneyAmount;
|
||||||
|
use App\Modules\Shared\Domain\ValueObjects\Money;
|
||||||
|
use Tests\Fakes\FakeExpenseJobs;
|
||||||
|
use Tests\Fakes\FakeExpensePricing;
|
||||||
|
use Tests\Fakes\FakeTransactionManager;
|
||||||
|
use Tests\Fakes\InMemoryExpenseRepository;
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->expenses = new InMemoryExpenseRepository;
|
||||||
|
$this->jobs = new FakeExpenseJobs;
|
||||||
|
$this->pricing = new FakeExpensePricing;
|
||||||
|
$transactions = new FakeTransactionManager;
|
||||||
|
$factory = new ExpenseDetailsFactory($this->pricing);
|
||||||
|
|
||||||
|
$this->record = new RecordExpense($this->expenses, $this->jobs, $factory, $transactions);
|
||||||
|
$this->update = new UpdateExpense($this->expenses, $this->jobs, $factory, $transactions);
|
||||||
|
$this->remove = new RemoveExpense($this->expenses, $this->jobs, $transactions);
|
||||||
|
|
||||||
|
$this->jobs->add(1);
|
||||||
|
$this->jobs->add(2, locked: true);
|
||||||
|
});
|
||||||
|
|
||||||
|
function purchase(array $fields = []): ExpenseData
|
||||||
|
{
|
||||||
|
return new ExpenseData(...array_merge([
|
||||||
|
'userId' => 5,
|
||||||
|
'category' => ExpenseCategory::Materials,
|
||||||
|
'paidBy' => ExpensePayer::Company,
|
||||||
|
'spentOn' => '2026-11-20',
|
||||||
|
'description' => 'Tulostuspaperi',
|
||||||
|
'cost' => '100',
|
||||||
|
], $fields));
|
||||||
|
}
|
||||||
|
|
||||||
|
function mileage(array $fields = []): ExpenseData
|
||||||
|
{
|
||||||
|
return purchase(array_merge([
|
||||||
|
'category' => ExpenseCategory::Mileage,
|
||||||
|
'description' => '',
|
||||||
|
'cost' => '',
|
||||||
|
'kilometers' => '42,5',
|
||||||
|
'destination' => 'Tampere',
|
||||||
|
'purpose' => 'Kuvaukset',
|
||||||
|
], $fields));
|
||||||
|
}
|
||||||
|
|
||||||
|
it('records a purchase billed at cost plus markup', function () {
|
||||||
|
$id = $this->record->execute(1, purchase(['markup' => '15', 'paidBy' => ExpensePayer::Employee]), recordedBy: 9);
|
||||||
|
|
||||||
|
$expense = $this->expenses->findById($id);
|
||||||
|
|
||||||
|
expect($expense?->userId())->toBe(5)
|
||||||
|
->and($expense?->recordedBy())->toBe(9)
|
||||||
|
->and($expense?->details()->cost->cents)->toBe(10000)
|
||||||
|
->and($expense?->details()->billing?->amount->cents)->toBe(11500)
|
||||||
|
->and($expense?->details()->paidBy)->toBe(ExpensePayer::Employee);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('bills a given amount instead of cost plus markup', function () {
|
||||||
|
$id = $this->record->execute(1, purchase(['markup' => '15', 'billedAmount' => '130']), 5);
|
||||||
|
|
||||||
|
expect($this->expenses->findById($id)?->details()->billing?->amount->cents)->toBe(13000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps no billed amount for an expense that is not billed', function () {
|
||||||
|
$id = $this->record->execute(1, purchase(['isBillable' => false, 'markup' => '15', 'billedAmount' => '130']), 5);
|
||||||
|
|
||||||
|
expect($this->expenses->findById($id)?->details()->billing)->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prices kilometres with the mileage rate', function () {
|
||||||
|
$id = $this->record->execute(1, mileage(), 5);
|
||||||
|
|
||||||
|
$details = $this->expenses->findById($id)?->details();
|
||||||
|
|
||||||
|
expect($details?->cost->cents)->toBe(2508)
|
||||||
|
->and($details?->kilometers?->tenths)->toBe(425)
|
||||||
|
->and($details?->billing?->amount->cents)->toBe(2508);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enforces expense rules', function (Closure $record, string $exception) {
|
||||||
|
expect(fn () => $record->call($this))->toThrow($exception);
|
||||||
|
})->with([
|
||||||
|
'description' => [fn () => $this->record->execute(1, purchase(['description' => ' ']), 5), ExpenseDescriptionRequired::class],
|
||||||
|
'cost' => [fn () => $this->record->execute(1, purchase(['cost' => '']), 5), ExpenseCostRequired::class],
|
||||||
|
'cost format' => [fn () => $this->record->execute(1, purchase(['cost' => '10,999']), 5), InvalidMoneyAmount::class],
|
||||||
|
'mileage details' => [fn () => $this->record->execute(1, mileage(['purpose' => '']), 5), MileageDetailsRequired::class],
|
||||||
|
'kilometres format' => [fn () => $this->record->execute(1, mileage(['kilometers' => '4,25']), 5), InvalidKilometers::class],
|
||||||
|
'markup format' => [fn () => $this->record->execute(1, purchase(['markup' => 'paljon']), 5), InvalidMarkup::class],
|
||||||
|
'locked job' => [fn () => $this->record->execute(2, purchase(), 5), ExpenseLocked::class],
|
||||||
|
'unknown job' => [fn () => $this->record->execute(99, purchase(), 5), ExpenseJobNotFound::class],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('needs a mileage rate for kilometres', function () {
|
||||||
|
$this->pricing->mileageRateCents = null;
|
||||||
|
|
||||||
|
$this->record->execute(1, mileage(), 5);
|
||||||
|
})->throws(MileageRateMissing::class);
|
||||||
|
|
||||||
|
it('changes and removes expenses only while the job is open', function () {
|
||||||
|
$id = $this->record->execute(1, purchase(), 5);
|
||||||
|
|
||||||
|
$this->update->execute($id, purchase(['userId' => 6, 'cost' => '80']));
|
||||||
|
expect($this->expenses->findById($id)?->userId())->toBe(6)
|
||||||
|
->and($this->expenses->findById($id)?->details()->cost->cents)->toBe(8000);
|
||||||
|
|
||||||
|
$this->jobs->add(1, locked: true);
|
||||||
|
|
||||||
|
expect(fn () => $this->update->execute($id, purchase()))->toThrow(ExpenseLocked::class)
|
||||||
|
->and(fn () => $this->remove->execute($id))->toThrow(ExpenseLocked::class);
|
||||||
|
|
||||||
|
$this->jobs->add(1);
|
||||||
|
$this->remove->execute($id);
|
||||||
|
|
||||||
|
expect($this->expenses->items)->toBe([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses kilometres, markups and percentages', function () {
|
||||||
|
expect(Kilometers::parse('42,5 km')?->tenths)->toBe(425)
|
||||||
|
->and(Kilometers::parse('')?->tenths)->toBeNull()
|
||||||
|
->and((new Kilometers(400))->format())->toBe('40')
|
||||||
|
->and(MarkupPercentage::parse('12,5 %')?->basisPoints)->toBe(1250)
|
||||||
|
->and(Money::fromCents(1999)->addPercent(1500)->cents)->toBe(2299);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user