From 54d98d9d2f551b658ecf583302f472d3da6da0a8 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Tue, 24 Nov 2026 08:11:27 +0200 Subject: [PATCH] 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 --- CLAUDE.md | 4 +- .../Contracts/PriceListQueries.php | 5 + .../UseCases/SetDefaultExpenseMarkup.php | 34 ++ .../Repositories/EloquentPriceListQueries.php | 6 + .../Presentation/Livewire/⚡prices.blade.php | 41 ++- .../Livewire/⚡product-form.blade.php | 2 +- .../Application/Contracts/ExpenseJobs.php | 22 ++ .../Application/Contracts/ExpensePricing.php | 22 ++ .../Application/Contracts/ExpenseQueries.php | 28 ++ .../Expenses/Application/DTOs/ExpenseData.php | 33 ++ .../Expenses/Application/DTOs/ExpenseJob.php | 27 ++ .../Application/DTOs/ExpenseSummary.php | 38 +++ .../UseCases/ExpenseDetailsFactory.php | 87 +++++ .../Application/UseCases/RecordExpense.php | 49 +++ .../Application/UseCases/RemoveExpense.php | 40 +++ .../Application/UseCases/UpdateExpense.php | 47 +++ .../Domain/Contracts/ExpenseRepository.php | 19 ++ .../Expenses/Domain/Entities/Expense.php | 63 ++++ .../Expenses/Domain/Enums/ExpenseCategory.php | 20 ++ .../Expenses/Domain/Enums/ExpensePayer.php | 15 + .../Domain/Exceptions/ExpenseCostRequired.php | 15 + .../Exceptions/ExpenseDescriptionRequired.php | 15 + .../Domain/Exceptions/ExpenseJobNotFound.php | 15 + .../Domain/Exceptions/ExpenseLocked.php | 15 + .../Domain/Exceptions/ExpenseNotFound.php | 15 + .../Domain/Exceptions/InvalidKilometers.php | 15 + .../Domain/Exceptions/InvalidMarkup.php | 15 + .../Exceptions/MileageDetailsRequired.php | 15 + .../Domain/Exceptions/MileageRateMissing.php | 15 + .../Domain/ValueObjects/ExpenseBilling.php | 25 ++ .../Domain/ValueObjects/ExpenseDetails.php | 131 ++++++++ .../Domain/ValueObjects/Kilometers.php | 65 ++++ .../Domain/ValueObjects/MarkupPercentage.php | 55 ++++ .../Infrastructure/JobsForExpenses.php | 29 ++ .../Persistence/Eloquent/ExpenseModel.php | 64 ++++ .../Repositories/EloquentExpenseQueries.php | 84 +++++ .../EloquentExpenseRepository.php | 82 +++++ .../Infrastructure/PriceListForExpenses.php | 24 ++ .../Providers/ExpensesServiceProvider.php | 61 ++++ .../Livewire/Concerns/ShowsExpenses.php | 62 ++++ .../Livewire/Forms/ExpenseForm.php | 186 +++++++++++ .../Presentation/Livewire/⚡form.blade.php | 310 ++++++++++++++++++ .../Presentation/Livewire/⚡job.blade.php | 244 ++++++++++++++ .../Presentation/Livewire/⚡mine.blade.php | 170 ++++++++++ .../Expenses/Presentation/Routes/web.php | 13 + .../Contracts/CustomerJobQueries.php | 8 + .../EloquentCustomerJobQueries.php | 17 + .../Presentation/Livewire/⚡show.blade.php | 7 + .../Shared/Domain/ValueObjects/Money.php | 11 +- bootstrap/providers.php | 2 + database/factories/ExpenseFactory.php | 68 ++++ ...026_11_24_060013_create_expenses_table.php | 42 +++ docs/maarittely.md | 18 +- lang/fi/catalog.php | 9 + lang/fi/expenses.php | 113 +++++++ lang/fi/jobs.php | 1 + lang/fi/layout.php | 1 + resources/views/layouts/app.blade.php | 2 + tests/Browser/ExpensesAccessibilityTest.php | 55 ++++ tests/Fakes/FakeExpenseJobs.php | 27 ++ tests/Fakes/FakeExpensePricing.php | 23 ++ tests/Fakes/InMemoryExpenseRepository.php | 32 ++ .../Feature/Modules/Expenses/ExpensesTest.php | 180 ++++++++++ .../Modules/Expenses/ExpenseUseCasesTest.php | 143 ++++++++ 64 files changed, 3092 insertions(+), 9 deletions(-) create mode 100644 app/Modules/Catalog/Application/UseCases/SetDefaultExpenseMarkup.php create mode 100644 app/Modules/Expenses/Application/Contracts/ExpenseJobs.php create mode 100644 app/Modules/Expenses/Application/Contracts/ExpensePricing.php create mode 100644 app/Modules/Expenses/Application/Contracts/ExpenseQueries.php create mode 100644 app/Modules/Expenses/Application/DTOs/ExpenseData.php create mode 100644 app/Modules/Expenses/Application/DTOs/ExpenseJob.php create mode 100644 app/Modules/Expenses/Application/DTOs/ExpenseSummary.php create mode 100644 app/Modules/Expenses/Application/UseCases/ExpenseDetailsFactory.php create mode 100644 app/Modules/Expenses/Application/UseCases/RecordExpense.php create mode 100644 app/Modules/Expenses/Application/UseCases/RemoveExpense.php create mode 100644 app/Modules/Expenses/Application/UseCases/UpdateExpense.php create mode 100644 app/Modules/Expenses/Domain/Contracts/ExpenseRepository.php create mode 100644 app/Modules/Expenses/Domain/Entities/Expense.php create mode 100644 app/Modules/Expenses/Domain/Enums/ExpenseCategory.php create mode 100644 app/Modules/Expenses/Domain/Enums/ExpensePayer.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/ExpenseCostRequired.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/ExpenseDescriptionRequired.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/ExpenseJobNotFound.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/ExpenseLocked.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/ExpenseNotFound.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/InvalidKilometers.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/InvalidMarkup.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/MileageDetailsRequired.php create mode 100644 app/Modules/Expenses/Domain/Exceptions/MileageRateMissing.php create mode 100644 app/Modules/Expenses/Domain/ValueObjects/ExpenseBilling.php create mode 100644 app/Modules/Expenses/Domain/ValueObjects/ExpenseDetails.php create mode 100644 app/Modules/Expenses/Domain/ValueObjects/Kilometers.php create mode 100644 app/Modules/Expenses/Domain/ValueObjects/MarkupPercentage.php create mode 100644 app/Modules/Expenses/Infrastructure/JobsForExpenses.php create mode 100644 app/Modules/Expenses/Infrastructure/Persistence/Eloquent/ExpenseModel.php create mode 100644 app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseQueries.php create mode 100644 app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseRepository.php create mode 100644 app/Modules/Expenses/Infrastructure/PriceListForExpenses.php create mode 100644 app/Modules/Expenses/Infrastructure/Providers/ExpensesServiceProvider.php create mode 100644 app/Modules/Expenses/Presentation/Livewire/Concerns/ShowsExpenses.php create mode 100644 app/Modules/Expenses/Presentation/Livewire/Forms/ExpenseForm.php create mode 100644 app/Modules/Expenses/Presentation/Livewire/⚡form.blade.php create mode 100644 app/Modules/Expenses/Presentation/Livewire/⚡job.blade.php create mode 100644 app/Modules/Expenses/Presentation/Livewire/⚡mine.blade.php create mode 100644 app/Modules/Expenses/Presentation/Routes/web.php create mode 100644 database/factories/ExpenseFactory.php create mode 100644 database/migrations/2026_11_24_060013_create_expenses_table.php create mode 100644 lang/fi/expenses.php create mode 100644 tests/Browser/ExpensesAccessibilityTest.php create mode 100644 tests/Fakes/FakeExpenseJobs.php create mode 100644 tests/Fakes/FakeExpensePricing.php create mode 100644 tests/Fakes/InMemoryExpenseRepository.php create mode 100644 tests/Feature/Modules/Expenses/ExpensesTest.php create mode 100644 tests/Unit/Modules/Expenses/ExpenseUseCasesTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 220749a..fcbcdfb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## 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: ``, ``), 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: ``, ``), 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. - **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/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::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. -- **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. - **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. diff --git a/app/Modules/Catalog/Application/Contracts/PriceListQueries.php b/app/Modules/Catalog/Application/Contracts/PriceListQueries.php index e2bf2e3..dcab407 100644 --- a/app/Modules/Catalog/Application/Contracts/PriceListQueries.php +++ b/app/Modules/Catalog/Application/Contracts/PriceListQueries.php @@ -44,6 +44,11 @@ interface PriceListQueries */ 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 */ diff --git a/app/Modules/Catalog/Application/UseCases/SetDefaultExpenseMarkup.php b/app/Modules/Catalog/Application/UseCases/SetDefaultExpenseMarkup.php new file mode 100644 index 0000000..8962239 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/SetDefaultExpenseMarkup.php @@ -0,0 +1,34 @@ +basisPoints; + + $this->settings->put(self::SETTING_KEY, $basisPoints === 0 ? null : (string) $basisPoints); + + return $basisPoints; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php index dc77959..63a103a 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php @@ -10,6 +10,7 @@ use App\Modules\Catalog\Application\DTOs\ProductSummary; use App\Modules\Catalog\Application\DTOs\ServiceUnitNode; use App\Modules\Catalog\Application\DTOs\VatRateSummary; 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\Domain\Enums\ProductUnit; use App\Modules\Catalog\Domain\ValueObjects\ProductDuration; @@ -124,6 +125,11 @@ class EloquentPriceListQueries implements PriceListQueries 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 { return new VatRateSummary($model->id, $model->name, $model->basis_points, $model->is_default, $model->is_active); diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php index 00cf078..ca94bb4 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php @@ -7,6 +7,7 @@ use App\Modules\Catalog\Application\DTOs\ProductSummary; use App\Modules\Catalog\Application\DTOs\VatRateSummary; use App\Modules\Catalog\Application\UseCases\MoveProduct; 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\SetMileageRate; 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\ValueObjects\ProductDuration; 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\VatPercentage; use Livewire\Attributes\Computed; @@ -47,6 +49,8 @@ new class extends Component public string $mileageRate = ''; + public string $expenseMarkup = ''; + protected PriceListQueries $priceList; public function boot(PriceListQueries $priceList): void @@ -59,6 +63,8 @@ new class extends Component $this->authorize('catalog.manage'); $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]); } + 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 { $this->authorize('catalog.manage'); @@ -473,7 +499,7 @@ new class extends Component
-

{{ __('catalog.mileage.title') }}

+

{{ __('catalog.expense_markup.section') }}

@@ -487,5 +513,18 @@ new class extends Component
+ +
+
+ +
+ +
diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php index efed271..8d4b61a 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php @@ -206,7 +206,7 @@ new class extends Component
$jobIds + * @return array Keyed by job id. + */ + public function findMany(array $jobIds): array; +} diff --git a/app/Modules/Expenses/Application/Contracts/ExpensePricing.php b/app/Modules/Expenses/Application/Contracts/ExpensePricing.php new file mode 100644 index 0000000..ad87b51 --- /dev/null +++ b/app/Modules/Expenses/Application/Contracts/ExpensePricing.php @@ -0,0 +1,22 @@ + + */ + public function forJob(int $jobId): array; + + /** + * A user's own expenses in a month. + * + * @param string $month As Y-m. + * @return list + */ + public function forUserInMonth(int $userId, string $month): array; + + public function find(int $id): ?ExpenseSummary; +} diff --git a/app/Modules/Expenses/Application/DTOs/ExpenseData.php b/app/Modules/Expenses/Application/DTOs/ExpenseData.php new file mode 100644 index 0000000..d197e8f --- /dev/null +++ b/app/Modules/Expenses/Application/DTOs/ExpenseData.php @@ -0,0 +1,33 @@ +number.' '.$this->name; + } +} diff --git a/app/Modules/Expenses/Application/DTOs/ExpenseSummary.php b/app/Modules/Expenses/Application/DTOs/ExpenseSummary.php new file mode 100644 index 0000000..33a6f0d --- /dev/null +++ b/app/Modules/Expenses/Application/DTOs/ExpenseSummary.php @@ -0,0 +1,38 @@ +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; + } +} diff --git a/app/Modules/Expenses/Application/UseCases/RecordExpense.php b/app/Modules/Expenses/Application/UseCases/RecordExpense.php new file mode 100644 index 0000000..dba43fb --- /dev/null +++ b/app/Modules/Expenses/Application/UseCases/RecordExpense.php @@ -0,0 +1,49 @@ +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(); + }); + } +} diff --git a/app/Modules/Expenses/Application/UseCases/RemoveExpense.php b/app/Modules/Expenses/Application/UseCases/RemoveExpense.php new file mode 100644 index 0000000..638e639 --- /dev/null +++ b/app/Modules/Expenses/Application/UseCases/RemoveExpense.php @@ -0,0 +1,40 @@ +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); + }); + } +} diff --git a/app/Modules/Expenses/Application/UseCases/UpdateExpense.php b/app/Modules/Expenses/Application/UseCases/UpdateExpense.php new file mode 100644 index 0000000..01365c7 --- /dev/null +++ b/app/Modules/Expenses/Application/UseCases/UpdateExpense.php @@ -0,0 +1,47 @@ +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); + }); + } +} diff --git a/app/Modules/Expenses/Domain/Contracts/ExpenseRepository.php b/app/Modules/Expenses/Domain/Contracts/ExpenseRepository.php new file mode 100644 index 0000000..d9dd7fe --- /dev/null +++ b/app/Modules/Expenses/Domain/Contracts/ExpenseRepository.php @@ -0,0 +1,19 @@ +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; + } +} diff --git a/app/Modules/Expenses/Domain/Enums/ExpenseCategory.php b/app/Modules/Expenses/Domain/Enums/ExpenseCategory.php new file mode 100644 index 0000000..1a654c1 --- /dev/null +++ b/app/Modules/Expenses/Domain/Enums/ExpenseCategory.php @@ -0,0 +1,20 @@ +addPercent($markup->basisPoints ?? 0), $markup); + } +} diff --git a/app/Modules/Expenses/Domain/ValueObjects/ExpenseDetails.php b/app/Modules/Expenses/Domain/ValueObjects/ExpenseDetails.php new file mode 100644 index 0000000..7e776d2 --- /dev/null +++ b/app/Modules/Expenses/Domain/ValueObjects/ExpenseDetails.php @@ -0,0 +1,131 @@ +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; + } +} diff --git a/app/Modules/Expenses/Domain/ValueObjects/Kilometers.php b/app/Modules/Expenses/Domain/ValueObjects/Kilometers.php new file mode 100644 index 0000000..4586b05 --- /dev/null +++ b/app/Modules/Expenses/Domain/ValueObjects/Kilometers.php @@ -0,0 +1,65 @@ + 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); + } +} diff --git a/app/Modules/Expenses/Domain/ValueObjects/MarkupPercentage.php b/app/Modules/Expenses/Domain/ValueObjects/MarkupPercentage.php new file mode 100644 index 0000000..e97cee9 --- /dev/null +++ b/app/Modules/Expenses/Domain/ValueObjects/MarkupPercentage.php @@ -0,0 +1,55 @@ + 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'), '.')); + } +} diff --git a/app/Modules/Expenses/Infrastructure/JobsForExpenses.php b/app/Modules/Expenses/Infrastructure/JobsForExpenses.php new file mode 100644 index 0000000..2d85578 --- /dev/null +++ b/app/Modules/Expenses/Infrastructure/JobsForExpenses.php @@ -0,0 +1,29 @@ +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), + ); + } +} diff --git a/app/Modules/Expenses/Infrastructure/Persistence/Eloquent/ExpenseModel.php b/app/Modules/Expenses/Infrastructure/Persistence/Eloquent/ExpenseModel.php new file mode 100644 index 0000000..1d10d74 --- /dev/null +++ b/app/Modules/Expenses/Infrastructure/Persistence/Eloquent/ExpenseModel.php @@ -0,0 +1,64 @@ + */ + use HasFactory; + + /** + * @return array + */ + 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', + ]; + } +} diff --git a/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseQueries.php b/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseQueries.php new file mode 100644 index 0000000..cd2602d --- /dev/null +++ b/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseQueries.php @@ -0,0 +1,84 @@ +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 $query + * @return list + */ + private function summaries(Builder $query): array + { + /** @var Collection $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(); + } +} diff --git a/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseRepository.php b/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseRepository.php new file mode 100644 index 0000000..4105a90 --- /dev/null +++ b/app/Modules/Expenses/Infrastructure/Persistence/Repositories/EloquentExpenseRepository.php @@ -0,0 +1,82 @@ +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, + ), + ); + } +} diff --git a/app/Modules/Expenses/Infrastructure/PriceListForExpenses.php b/app/Modules/Expenses/Infrastructure/PriceListForExpenses.php new file mode 100644 index 0000000..853f80f --- /dev/null +++ b/app/Modules/Expenses/Infrastructure/PriceListForExpenses.php @@ -0,0 +1,24 @@ +priceList->mileageRateCents(); + } + + public function defaultMarkupBasisPoints(): int + { + return $this->priceList->defaultExpenseMarkupBasisPoints(); + } +} diff --git a/app/Modules/Expenses/Infrastructure/Providers/ExpensesServiceProvider.php b/app/Modules/Expenses/Infrastructure/Providers/ExpensesServiceProvider.php new file mode 100644 index 0000000..8b34c3f --- /dev/null +++ b/app/Modules/Expenses/Infrastructure/Providers/ExpensesServiceProvider.php @@ -0,0 +1,61 @@ + + */ + 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')); + } +} diff --git a/app/Modules/Expenses/Presentation/Livewire/Concerns/ShowsExpenses.php b/app/Modules/Expenses/Presentation/Livewire/Concerns/ShowsExpenses.php new file mode 100644 index 0000000..3a53641 --- /dev/null +++ b/app/Modules/Expenses/Presentation/Livewire/Concerns/ShowsExpenses.php @@ -0,0 +1,62 @@ +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'); + } +} diff --git a/app/Modules/Expenses/Presentation/Livewire/Forms/ExpenseForm.php b/app/Modules/Expenses/Presentation/Livewire/Forms/ExpenseForm.php new file mode 100644 index 0000000..15869e2 --- /dev/null +++ b/app/Modules/Expenses/Presentation/Livewire/Forms/ExpenseForm.php @@ -0,0 +1,186 @@ +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> + */ + 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 + */ + 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'; + } +} diff --git a/app/Modules/Expenses/Presentation/Livewire/⚡form.blade.php b/app/Modules/Expenses/Presentation/Livewire/⚡form.blade.php new file mode 100644 index 0000000..0f24c0a --- /dev/null +++ b/app/Modules/Expenses/Presentation/Livewire/⚡form.blade.php @@ -0,0 +1,310 @@ +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 + */ + #[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) + +
+
+

{{ $this->heading() }}

+

{{ __('expenses.fields.job') }}: {{ $job->label() }}

+
+ + @if ($job->isLocked) +

+

+ @else +
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + @foreach (ExpenseCategory::cases() as $category) + + @endforeach + + +
+ + + + @foreach (ExpensePayer::cases() as $payer) + + @endforeach + +
+ + @if ($this->canRecordForOthers) + + @foreach ($this->userOptions as $option) + + @endforeach + + @endif + + @if ($form->isMileage()) +
+ +

{{ $this->mileageCost() }}

+
+ + + + @else + + + @endif + +
+ {{ __('expenses.form.billing') }} + + + + @if ($form->is_billable) +
+ + +
+

{{ $form->billed_amount === '' ? $this->suggestedBilledAmount() : '' }}

+ @endif +
+ +
+ + +
+ + @endif +
diff --git a/app/Modules/Expenses/Presentation/Livewire/⚡job.blade.php b/app/Modules/Expenses/Presentation/Livewire/⚡job.blade.php new file mode 100644 index 0000000..7381f6f --- /dev/null +++ b/app/Modules/Expenses/Presentation/Livewire/⚡job.blade.php @@ -0,0 +1,244 @@ +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 + */ + #[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 + */ + 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) + +
+
+

{{ __('expenses.job_page.title', ['job' => $job->label()]) }}

+ {{ __('expenses.job_page.back_to_job') }} +
+ +

{{ $statusMessage }}

+ + @if (session('status')) + + @endif + + @if ($job->isLocked) +

+

+ @else + + @endif + +
+

{{ __('expenses.job_page.list') }}

+ + @unless ($this->canSeeTotals) +

{{ __('expenses.amounts_hidden_help') }}

+ @endunless + + @if ($this->expenses === []) +

{{ __('expenses.none') }}

+ @else + + @interact('column_spentOn', $expense) + {{ $this->dayLabel($expense->spentOn) }} + @endinteract + + @interact('column_what', $expense) + {{ $this->summaryText($expense) }} + + {{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }} + + @endinteract + + @interact('column_user', $expense) + {{ $expense->userName }} + @endinteract + + @interact('column_cost', $expense) + {{ $this->amount($expense, $expense->costCents) }} + @endinteract + + @interact('column_billed', $expense) + {{ $this->amount($expense, $expense->billedAmountCents) }} + @endinteract + + @interact('column_actions', $expense) + @if ($this->canChange($expense)) +
+ + +
+ @endif + @endinteract +
+ + @if ($this->canSeeTotals) +
+
{{ __('expenses.totals.cost') }}
+
{{ $this->money($this->totals['cost']) }}
+
{{ __('expenses.totals.billed') }}
+
{{ $this->money($this->totals['billed']) }}
+
+ @endif + @endif +
+ + +

+ @php($removal = collect($this->expenses)->firstWhere('id', $removalExpenseId)) + @if ($removal !== null) + {{ __('expenses.remove_question', ['expense' => $this->summaryText($removal), 'day' => $this->dayLabel($removal->spentOn)]) }} + @endif +

+ + + + +
+
diff --git a/app/Modules/Expenses/Presentation/Livewire/⚡mine.blade.php b/app/Modules/Expenses/Presentation/Livewire/⚡mine.blade.php new file mode 100644 index 0000000..e570dc8 --- /dev/null +++ b/app/Modules/Expenses/Presentation/Livewire/⚡mine.blade.php @@ -0,0 +1,170 @@ +authorize('expenses.use'); + + $this->month = $this->monthStart($this->month)?->format('Y-m') ?? $clock->today()->format('Y-m'); + } + + /** + * @return list + */ + #[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 + */ + 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; + } +}; +?> + +
+
+

{{ __('expenses.mine.title') }}

+

+ {{ __(auth()->user()?->can('expenses.record') ? 'expenses.mine.help' : 'expenses.mine.help_subcontractor') }} +

+
+ + + +
+

{{ $this->monthLabel() }}

+ + @if ($this->expenses === []) +

{{ __('expenses.none') }}

+ @else + + @interact('column_spentOn', $expense) + {{ $this->dayLabel($expense->spentOn) }} + @endinteract + + @interact('column_job', $expense) + @can('expenses.record') + {{ $expense->job->label() }} + @else + {{ $expense->job->label() }} + @endcan + @if ($expense->job->isLocked) + + + @endif + @endinteract + + @interact('column_what', $expense) + {{ $this->summaryText($expense) }} + + {{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }} + + @endinteract + + @interact('column_cost', $expense) + {{ $this->amount($expense, $expense->costCents) }} + @endinteract + + @interact('column_actions', $expense) + @if ($this->canChange($expense)) + + @endif + @endinteract + + +

{{ __('expenses.mine.total', ['total' => $this->money($this->total)]) }}

+ @endif +
+
diff --git a/app/Modules/Expenses/Presentation/Routes/web.php b/app/Modules/Expenses/Presentation/Routes/web.php new file mode 100644 index 0000000..3f61255 --- /dev/null +++ b/app/Modules/Expenses/Presentation/Routes/web.php @@ -0,0 +1,13 @@ +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'); + }); diff --git a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php index 4f13bcb..2a0f1b1 100644 --- a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php +++ b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php @@ -33,6 +33,14 @@ interface CustomerJobQueries public function findDetails(int $id): ?CustomerJobDetails; + /** + * Summaries of the given jobs, keyed by id; unknown ids are left out. + * + * @param list $ids + * @return array + */ + public function summariesByIds(array $ids): array; + /** * The job's history, newest first. * diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php index c151bec..f107e62 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php @@ -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 { $model = CustomerJobModel::query()->find($id); diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index 48ae7f3..08c4dc2 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -405,6 +405,13 @@ new class extends Component + @can('expenses.record') +
+

{{ __('jobs.sections.expenses') }}

+ {{ __('expenses.job_page.link') }} +
+ @endcan +
diff --git a/app/Modules/Shared/Domain/ValueObjects/Money.php b/app/Modules/Shared/Domain/ValueObjects/Money.php index c2b7845..d799799 100644 --- a/app/Modules/Shared/Domain/ValueObjects/Money.php +++ b/app/Modules/Shared/Domain/ValueObjects/Money.php @@ -60,7 +60,16 @@ final readonly class Money */ 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)); } /** diff --git a/bootstrap/providers.php b/bootstrap/providers.php index e440306..d4505a5 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -2,6 +2,7 @@ use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider; use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; +use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider; use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider; use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider; use App\Modules\TimeTracking\Infrastructure\Providers\TimeTrackingServiceProvider; @@ -18,4 +19,5 @@ return [ JobsServiceProvider::class, // After Jobs: replaces its TaskUsage binding. TimeTrackingServiceProvider::class, + ExpensesServiceProvider::class, ]; diff --git a/database/factories/ExpenseFactory.php b/database/factories/ExpenseFactory.php new file mode 100644 index 0000000..0a25e32 --- /dev/null +++ b/database/factories/ExpenseFactory.php @@ -0,0 +1,68 @@ + + */ +class ExpenseFactory extends Factory +{ + protected $model = ExpenseModel::class; + + /** + * @return array + */ + 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]); + } +} diff --git a/database/migrations/2026_11_24_060013_create_expenses_table.php b/database/migrations/2026_11_24_060013_create_expenses_table.php new file mode 100644 index 0000000..514cbc8 --- /dev/null +++ b/database/migrations/2026_11_24_060013_create_expenses_table.php @@ -0,0 +1,42 @@ +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'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 621f55a..ea97cad 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -261,10 +261,14 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä ## 10. Kulut *(K42–K45)* - 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. -- Kilometrikulu: päivämäärä, kohde, kilometrit, tarkoitus; hinta hinnaston km-hinnasta. -- Alihankkijan kulut kirjaa johto. +- Kilometrikulu: päivämäärä, kohde, kilometrit (0,1 km tarkkuus), tarkoitus; hankintahinta = km × hinnaston km-hinta kirjaushetkellä. +- 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)* @@ -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)* **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)* - `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. - 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 1. **Lukitus**: voiko johto avata valmiin työn tunti- ja kululukituksen, jos jotain unohtui? (Ehdotus: kyllä, ja avaus kirjataan muutoshistoriaan.) diff --git a/lang/fi/catalog.php b/lang/fi/catalog.php index d94c5ce..0e0bb1f 100644 --- a/lang/fi/catalog.php +++ b/lang/fi/catalog.php @@ -145,6 +145,14 @@ return [ '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' => [ 'title' => 'Km-hinta', 'rate' => 'Km-hinta (€/km, ALV 0)', @@ -164,6 +172,7 @@ return [ 'name_taken' => 'Samalla tasolla on jo tämänniminen rivi.', '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.', + '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 €).', 'price_required' => 'Anna hinta.', 'invalid_unit' => 'Valitse yksikkö listasta.', diff --git a/lang/fi/expenses.php b/lang/fi/expenses.php new file mode 100644 index 0000000..a1a6dfc --- /dev/null +++ b/lang/fi/expenses.php @@ -0,0 +1,113 @@ + '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ä.', + ], +]; diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index 937bedd..1f06a53 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -97,6 +97,7 @@ return [ ], 'sections' => [ + 'expenses' => 'Kulut', 'basics' => 'Perustiedot', 'schedule' => 'Aikataulu', 'classification' => 'Luokittelu', diff --git a/lang/fi/layout.php b/lang/fi/layout.php index 9e6db1b..f84d0cb 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -8,6 +8,7 @@ return [ 'quick_intake' => 'Pikavastaanotto', 'board' => 'Kanban', 'time' => 'Tuntikirjaus', + 'expenses' => 'Kulut', 'customers' => 'Asiakkaat', 'users' => 'Käyttäjät', 'catalog' => 'Pohjatiedot', diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 39030e6..85b616b 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -61,6 +61,8 @@ @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') @include('partials.nav-item', ['route' => 'jobs.quick', 'pattern' => 'jobs.quick', 'label' => __('layout.quick_intake')]) @endcan diff --git a/tests/Browser/ExpensesAccessibilityTest.php b/tests/Browser/ExpensesAccessibilityTest.php new file mode 100644 index 0000000..55a982f --- /dev/null +++ b/tests/Browser/ExpensesAccessibilityTest.php @@ -0,0 +1,55 @@ +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); +}); diff --git a/tests/Fakes/FakeExpenseJobs.php b/tests/Fakes/FakeExpenseJobs.php new file mode 100644 index 0000000..47b3fd1 --- /dev/null +++ b/tests/Fakes/FakeExpenseJobs.php @@ -0,0 +1,27 @@ + */ + 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)); + } +} diff --git a/tests/Fakes/FakeExpensePricing.php b/tests/Fakes/FakeExpensePricing.php new file mode 100644 index 0000000..1b54e31 --- /dev/null +++ b/tests/Fakes/FakeExpensePricing.php @@ -0,0 +1,23 @@ +mileageRateCents; + } + + public function defaultMarkupBasisPoints(): int + { + return $this->defaultMarkupBasisPoints; + } +} diff --git a/tests/Fakes/InMemoryExpenseRepository.php b/tests/Fakes/InMemoryExpenseRepository.php new file mode 100644 index 0000000..5c6e8ee --- /dev/null +++ b/tests/Fakes/InMemoryExpenseRepository.php @@ -0,0 +1,32 @@ + */ + 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()]); + } +} diff --git a/tests/Feature/Modules/Expenses/ExpensesTest.php b/tests/Feature/Modules/Expenses/ExpensesTest.php new file mode 100644 index 0000000..63056e8 --- /dev/null +++ b/tests/Feature/Modules/Expenses/ExpensesTest.php @@ -0,0 +1,180 @@ +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'); +}); diff --git a/tests/Unit/Modules/Expenses/ExpenseUseCasesTest.php b/tests/Unit/Modules/Expenses/ExpenseUseCasesTest.php new file mode 100644 index 0000000..9150941 --- /dev/null +++ b/tests/Unit/Modules/Expenses/ExpenseUseCasesTest.php @@ -0,0 +1,143 @@ +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); +});