Add expenses on customer jobs

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 08:11:27 +02:00
co-authored by Claude Opus 5.5
parent bdd8d446d8
commit 54d98d9d2f
64 changed files with 3092 additions and 9 deletions
@@ -0,0 +1,55 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Shared\Application\Contracts\Settings;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->user = User::factory()->employee()->create();
$this->actingAs($this->user);
app(Settings::class)->put(SetMileageRate::SETTING_KEY, '59');
$this->job = CustomerJobModel::factory()->create(['name' => 'Messuvideo', 'status' => JobStatus::Order]);
$this->purchase = ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->user->id, 'description' => 'Tulostuspaperi', 'spent_on' => now()->toDateString()]);
$this->mileage = ExpenseModel::factory()->mileage()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->user->id, 'spent_on' => now()->toDateString()]);
ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'description' => 'Kollegan hankinta']);
});
it('has no accessibility issues on the expense pages and no sideways scrolling', function (string $page, string $device, string $colorScheme) {
$url = match ($page) {
'job expenses' => route('expenses.job', $this->job->id),
'new expense' => route('expenses.create', $this->job->id),
'edit mileage' => route('expenses.edit', $this->mileage->id),
'own expenses' => route('expenses.mine'),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee('Messuvideo')
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['job expenses', 'new expense', 'edit mileage', 'own expenses'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('works out the cost of kilometres as they are typed', function () {
$field = '[wire\\:model\\.live\\.blur="form.kilometers"]';
visit(route('expenses.edit', $this->mileage->id))
->clear($field)
->type($field, '100')
->keys($field, 'Tab')
->assertSee('100 km × 0,59')
->assertSee('59,00')
->assertNoAccessibilityIssues(level: 2);
});
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Tests\Fakes;
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Application\DTOs\ExpenseJob;
class FakeExpenseJobs implements ExpenseJobs
{
/** @var array<int, ExpenseJob> */
public array $jobs = [];
public function add(int $id, bool $locked = false): void
{
$this->jobs[$id] = new ExpenseJob($id, '2026-'.str_pad((string) $id, 4, '0', STR_PAD_LEFT), 'Työ '.$id, $locked);
}
public function find(int $jobId): ?ExpenseJob
{
return $this->jobs[$jobId] ?? null;
}
public function findMany(array $jobIds): array
{
return array_intersect_key($this->jobs, array_flip($jobIds));
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Tests\Fakes;
use App\Modules\Expenses\Application\Contracts\ExpensePricing;
class FakeExpensePricing implements ExpensePricing
{
public function __construct(
public ?int $mileageRateCents = 59,
public int $defaultMarkupBasisPoints = 0,
) {}
public function mileageRateCents(): ?int
{
return $this->mileageRateCents;
}
public function defaultMarkupBasisPoints(): int
{
return $this->defaultMarkupBasisPoints;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Tests\Fakes;
use App\Modules\Expenses\Domain\Contracts\ExpenseRepository;
use App\Modules\Expenses\Domain\Entities\Expense;
class InMemoryExpenseRepository implements ExpenseRepository
{
/** @var array<int, Expense> */
public array $items = [];
private int $nextId = 1;
public function findById(int $id): ?Expense
{
return isset($this->items[$id]) ? clone $this->items[$id] : null;
}
public function save(Expense $expense): Expense
{
$id = $expense->id() ?? $this->nextId++;
$this->items[$id] = Expense::reconstitute($id, $expense->jobId(), $expense->userId(), $expense->recordedBy(), $expense->details());
return clone $this->items[$id];
}
public function delete(Expense $expense): void
{
unset($this->items[$expense->id()]);
}
}
@@ -0,0 +1,180 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Application\UseCases\SetDefaultExpenseMarkup;
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Shared\Application\Contracts\Settings;
use App\Modules\Users\Domain\Enums\MoneyPermission;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']);
$this->job = CustomerJobModel::factory()->create(['name' => 'Messuvideo', 'status' => JobStatus::Order]);
app(Settings::class)->put(SetMileageRate::SETTING_KEY, '59');
$this->actingAs($this->employee);
});
it('records a purchase with the default markup', function () {
app(Settings::class)->put(SetDefaultExpenseMarkup::SETTING_KEY, '1500');
Livewire::test('expenses::form', ['job' => $this->job->id])
->assertSet('form.markup', '15')
->set('form.description', 'Tulostuspaperi')
->set('form.cost', '100')
->set('form.paid_by', 'employee')
->assertSee("Laskutetaan 115,00\u{00A0}€ (hankintahinta + kate).")
->call('save')
->assertHasNoErrors()
->assertRedirect(route('expenses.job', $this->job->id));
$expense = ExpenseModel::query()->sole();
expect($expense->only(['user_id', 'recorded_by', 'cost_cents', 'billed_amount_cents', 'markup_basis_points']))->toBe([
'user_id' => $this->employee->id,
'recorded_by' => $this->employee->id,
'cost_cents' => 10000,
'billed_amount_cents' => 11500,
'markup_basis_points' => 1500,
]);
});
it('records kilometres priced with the mileage rate and no default markup', function () {
app(Settings::class)->put(SetDefaultExpenseMarkup::SETTING_KEY, '1500');
Livewire::test('expenses::form', ['job' => $this->job->id])
->set('form.category', 'mileage')
->assertSet('form.markup', '')
->set('form.kilometers', '40')
->assertSee("Hankintahinta: 40 km × 0,59\u{00A0}€ = 23,60\u{00A0}€")
->set('form.destination', 'Tampere')
->set('form.purpose', 'Kuvaukset')
->call('save')
->assertHasNoErrors();
expect(ExpenseModel::query()->sole()->only(['category', 'cost_cents', 'billed_amount_cents']))->toBe([
'category' => ExpenseCategory::Mileage,
'cost_cents' => 2360,
'billed_amount_cents' => 2360,
]);
});
it('shows expense rule violations as Finnish field errors', function (array $fields, string $field, string $message) {
$component = Livewire::test('expenses::form', ['job' => $this->job->id]);
foreach ($fields as $name => $value) {
$component->set("form.{$name}", $value);
}
$component->call('save')->assertHasErrors(["form.{$field}" => [__($message)]]);
})->with([
'description' => [['cost' => '10'], 'description', 'expenses.errors.description_required'],
'cost' => [['description' => 'Paperi', 'cost' => '10,123'], 'cost', 'expenses.errors.invalid_amount'],
'billed amount' => [['description' => 'Paperi', 'cost' => '10', 'billed_amount' => 'x'], 'billed_amount', 'expenses.errors.invalid_amount'],
'mileage' => [['category' => 'mileage', 'kilometers' => '40', 'destination' => 'Tampere'], 'purpose', 'expenses.errors.mileage_details_required'],
]);
it('hides the amounts of others\' expenses without the expenses permission', function () {
$colleague = User::factory()->employee()->create(['name' => 'Kaisa Kollega']);
ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->employee->id, 'description' => 'Oma hankinta', 'cost_cents' => 1234, 'billed_amount_cents' => 1234]);
ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $colleague->id, 'description' => 'Kollegan hankinta', 'cost_cents' => 9876, 'billed_amount_cents' => 9876]);
$this->get(route('expenses.job', $this->job->id))
->assertOk()
->assertSee('Oma hankinta')
->assertSee("12,34\u{00A0}€", false)
->assertSee('Kollegan hankinta')
->assertDontSee("98,76\u{00A0}€", false)
->assertDontSee(__('expenses.totals.cost'));
$this->actingAs(User::factory()->employee()->withMoneyPermissions(MoneyPermission::Expenses)->create())
->get(route('expenses.job', $this->job->id))
->assertSee("98,76\u{00A0}€", false)
->assertSee("111,10\u{00A0}€", false);
});
it('locks the expenses of a done job', function () {
$expense = ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->employee->id]);
$this->job->update(['status' => JobStatus::Done]);
$this->get(route('expenses.job', $this->job->id))
->assertSee(__('expenses.locked'))
->assertDontSee(route('expenses.create', $this->job->id), false)
->assertDontSee(route('expenses.edit', $expense->id), false);
Livewire::test('expenses::job', ['job' => $this->job->id])
->call('confirmRemoval', $expense->id)
->assertSet('removalExpenseId', null);
expect(ExpenseModel::query()->count())->toBe(1);
});
it('removes an own expense after confirmation but not a colleague\'s', function () {
$own = ExpenseModel::factory()->create(['customer_job_id' => $this->job->id, 'user_id' => $this->employee->id, 'description' => 'Paperi']);
$colleagues = ExpenseModel::factory()->create(['customer_job_id' => $this->job->id]);
Livewire::test('expenses::job', ['job' => $this->job->id])
->call('confirmRemoval', $colleagues->id)
->assertSet('removalExpenseId', null)
->call('confirmRemoval', $own->id)
->call('removeExpense')
->assertSet('statusMessage', 'Kulu "Paperi" poistettu.');
expect(ExpenseModel::query()->pluck('id')->all())->toBe([$colleagues->id]);
$this->get(route('expenses.edit', $colleagues->id))->assertForbidden();
});
it('lets management record a subcontractor\'s expense, which the subcontractor sees but cannot change', function () {
$subcontractor = User::factory()->subcontractor()->create(['name' => 'Alihankkija Oy']);
$this->actingAs(User::factory()->management()->create());
Livewire::test('expenses::form', ['job' => $this->job->id])
->set('form.user_id', (string) $subcontractor->id)
->set('form.description', 'Vuokrakalusto')
->set('form.cost', '250')
->call('save')
->assertHasNoErrors();
$expense = ExpenseModel::query()->sole();
$this->actingAs($subcontractor)
->get(route('expenses.mine', ['kuukausi' => now()->format('Y-m')]))
->assertOk()
->assertSee('Vuokrakalusto')
->assertSee("250,00\u{00A0}€", false)
->assertDontSee(route('expenses.edit', $expense->id), false);
$this->get(route('expenses.job', $this->job->id))->assertForbidden();
$this->get(route('expenses.create', $this->job->id))->assertForbidden();
});
it('does not let an employee record an expense for someone else', function () {
$colleague = User::factory()->employee()->create();
Livewire::test('expenses::form', ['job' => $this->job->id])
->set('form.user_id', (string) $colleague->id)
->set('form.description', 'Paperi')
->set('form.cost', '10')
->call('save')
->assertHasNoErrors();
expect(ExpenseModel::query()->sole()->user_id)->toBe($this->employee->id);
});
it('links the job page to its expenses and shows the own expenses by month', function () {
ExpenseModel::factory()->create(['user_id' => $this->employee->id, 'spent_on' => '2026-10-15', 'description' => 'Lokakuun hankinta']);
$this->get(route('jobs.show', $this->job->id))->assertSee(route('expenses.job', $this->job->id), false);
$this->get(route('expenses.mine', ['kuukausi' => '2026-10']))
->assertOk()
->assertSee('Lokakuu 2026')
->assertSee('Lokakuun hankinta');
});
@@ -0,0 +1,143 @@
<?php
use App\Modules\Expenses\Application\DTOs\ExpenseData;
use App\Modules\Expenses\Application\UseCases\ExpenseDetailsFactory;
use App\Modules\Expenses\Application\UseCases\RecordExpense;
use App\Modules\Expenses\Application\UseCases\RemoveExpense;
use App\Modules\Expenses\Application\UseCases\UpdateExpense;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
use App\Modules\Expenses\Domain\Exceptions\ExpenseCostRequired;
use App\Modules\Expenses\Domain\Exceptions\ExpenseDescriptionRequired;
use App\Modules\Expenses\Domain\Exceptions\ExpenseJobNotFound;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Expenses\Domain\Exceptions\InvalidKilometers;
use App\Modules\Expenses\Domain\Exceptions\InvalidMarkup;
use App\Modules\Expenses\Domain\Exceptions\MileageDetailsRequired;
use App\Modules\Expenses\Domain\Exceptions\MileageRateMissing;
use App\Modules\Expenses\Domain\ValueObjects\Kilometers;
use App\Modules\Expenses\Domain\ValueObjects\MarkupPercentage;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use Tests\Fakes\FakeExpenseJobs;
use Tests\Fakes\FakeExpensePricing;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryExpenseRepository;
beforeEach(function () {
$this->expenses = new InMemoryExpenseRepository;
$this->jobs = new FakeExpenseJobs;
$this->pricing = new FakeExpensePricing;
$transactions = new FakeTransactionManager;
$factory = new ExpenseDetailsFactory($this->pricing);
$this->record = new RecordExpense($this->expenses, $this->jobs, $factory, $transactions);
$this->update = new UpdateExpense($this->expenses, $this->jobs, $factory, $transactions);
$this->remove = new RemoveExpense($this->expenses, $this->jobs, $transactions);
$this->jobs->add(1);
$this->jobs->add(2, locked: true);
});
function purchase(array $fields = []): ExpenseData
{
return new ExpenseData(...array_merge([
'userId' => 5,
'category' => ExpenseCategory::Materials,
'paidBy' => ExpensePayer::Company,
'spentOn' => '2026-11-20',
'description' => 'Tulostuspaperi',
'cost' => '100',
], $fields));
}
function mileage(array $fields = []): ExpenseData
{
return purchase(array_merge([
'category' => ExpenseCategory::Mileage,
'description' => '',
'cost' => '',
'kilometers' => '42,5',
'destination' => 'Tampere',
'purpose' => 'Kuvaukset',
], $fields));
}
it('records a purchase billed at cost plus markup', function () {
$id = $this->record->execute(1, purchase(['markup' => '15', 'paidBy' => ExpensePayer::Employee]), recordedBy: 9);
$expense = $this->expenses->findById($id);
expect($expense?->userId())->toBe(5)
->and($expense?->recordedBy())->toBe(9)
->and($expense?->details()->cost->cents)->toBe(10000)
->and($expense?->details()->billing?->amount->cents)->toBe(11500)
->and($expense?->details()->paidBy)->toBe(ExpensePayer::Employee);
});
it('bills a given amount instead of cost plus markup', function () {
$id = $this->record->execute(1, purchase(['markup' => '15', 'billedAmount' => '130']), 5);
expect($this->expenses->findById($id)?->details()->billing?->amount->cents)->toBe(13000);
});
it('keeps no billed amount for an expense that is not billed', function () {
$id = $this->record->execute(1, purchase(['isBillable' => false, 'markup' => '15', 'billedAmount' => '130']), 5);
expect($this->expenses->findById($id)?->details()->billing)->toBeNull();
});
it('prices kilometres with the mileage rate', function () {
$id = $this->record->execute(1, mileage(), 5);
$details = $this->expenses->findById($id)?->details();
expect($details?->cost->cents)->toBe(2508)
->and($details?->kilometers?->tenths)->toBe(425)
->and($details?->billing?->amount->cents)->toBe(2508);
});
it('enforces expense rules', function (Closure $record, string $exception) {
expect(fn () => $record->call($this))->toThrow($exception);
})->with([
'description' => [fn () => $this->record->execute(1, purchase(['description' => ' ']), 5), ExpenseDescriptionRequired::class],
'cost' => [fn () => $this->record->execute(1, purchase(['cost' => '']), 5), ExpenseCostRequired::class],
'cost format' => [fn () => $this->record->execute(1, purchase(['cost' => '10,999']), 5), InvalidMoneyAmount::class],
'mileage details' => [fn () => $this->record->execute(1, mileage(['purpose' => '']), 5), MileageDetailsRequired::class],
'kilometres format' => [fn () => $this->record->execute(1, mileage(['kilometers' => '4,25']), 5), InvalidKilometers::class],
'markup format' => [fn () => $this->record->execute(1, purchase(['markup' => 'paljon']), 5), InvalidMarkup::class],
'locked job' => [fn () => $this->record->execute(2, purchase(), 5), ExpenseLocked::class],
'unknown job' => [fn () => $this->record->execute(99, purchase(), 5), ExpenseJobNotFound::class],
]);
it('needs a mileage rate for kilometres', function () {
$this->pricing->mileageRateCents = null;
$this->record->execute(1, mileage(), 5);
})->throws(MileageRateMissing::class);
it('changes and removes expenses only while the job is open', function () {
$id = $this->record->execute(1, purchase(), 5);
$this->update->execute($id, purchase(['userId' => 6, 'cost' => '80']));
expect($this->expenses->findById($id)?->userId())->toBe(6)
->and($this->expenses->findById($id)?->details()->cost->cents)->toBe(8000);
$this->jobs->add(1, locked: true);
expect(fn () => $this->update->execute($id, purchase()))->toThrow(ExpenseLocked::class)
->and(fn () => $this->remove->execute($id))->toThrow(ExpenseLocked::class);
$this->jobs->add(1);
$this->remove->execute($id);
expect($this->expenses->items)->toBe([]);
});
it('parses kilometres, markups and percentages', function () {
expect(Kilometers::parse('42,5 km')?->tenths)->toBe(425)
->and(Kilometers::parse('')?->tenths)->toBeNull()
->and((new Kilometers(400))->format())->toBe('40')
->and(MarkupPercentage::parse('12,5 %')?->basisPoints)->toBe(1250)
->and(Money::fromCents(1999)->addPercent(1500)->cents)->toBe(2299);
});