Add the price list: hourly rates, products and mileage rate

- Work types get an hourly rate (VAT 0), set on the work type form or in
  the hourly rate grid of the new Hinnasto page (/catalog/prices), which
  saves a cell when focus leaves it.
- Fixed-price products with a unit from a list, consumer product flag and
  automatic hours, which need a work type. Products are moved and
  deactivated, never deleted.
- The mileage rate is stored in a new settings table through the shared
  Settings contract.
- Shared Money value object keeps amounts in cents, parses "85,50" and
  formats "85,50 €".
- Prices are read only through PriceListQueries, not CatalogQueries, so
  personal money permissions can be added in one place next.
- Only admins and management can open the pages for now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 07:30:49 +02:00
co-authored by Claude Opus 5.5
parent 1acdaa5b19
commit dc2612cf46
58 changed files with 2577 additions and 32 deletions
+20 -1
View File
@@ -1,6 +1,7 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -15,12 +16,18 @@ it('has no accessibility issues on the catalog pages', function (string $page, s
$media = ServiceUnitModel::query()->where('name', 'Mediatuotanto')->sole();
WorkTypeModel::query()->where('name', 'animointi')->update(['is_active' => false]);
$workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole();
$workType->update(['hourly_rate_cents' => 9500]);
$product = ProductModel::factory()->consumer()->create(['name' => 'Passikuvat', 'auto_hours' => 0.25, 'work_type_id' => WorkTypeModel::query()->where('name', 'passikuvat')->sole()->id]);
ProductModel::factory()->inactive()->create(['name' => 'Vanha tuloste']);
$url = match ($page) {
'catalog' => route('catalog.index'),
'new service unit' => route('catalog.service-units.create'),
'new service' => route('catalog.services.create', $media->id),
'edit work type' => route('catalog.work-types.edit', $workType->id),
'price list' => route('catalog.prices'),
'new product' => route('catalog.products.create'),
'edit product' => route('catalog.products.edit', $product->id),
};
$visit = visit($url);
@@ -29,7 +36,7 @@ it('has no accessibility issues on the catalog pages', function (string $page, s
$visit->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['catalog', 'new service unit', 'new service', 'edit work type'])->with([
})->with(['catalog', 'new service unit', 'new service', 'edit work type', 'price list', 'new product', 'edit product'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
@@ -56,3 +63,15 @@ it('takes a row out of use with the keyboard', function () {
->assertSee('(Ei käytössä)')
->assertNoAccessibilityIssues(level: 2);
});
it('saves an hourly rate with the keyboard and announces it', function () {
$workType = WorkTypeModel::query()->where('name', 'painotyö')->sole();
visit(route('catalog.prices'))
->type('#rate-'.$workType->id, '85,50')
->keys('#rate-'.$workType->id, 'Tab')
->assertSee('painotyö: tuntihinta 85,50')
->assertNoAccessibilityIssues(level: 2);
expect($workType->refresh()->hourly_rate_cents)->toBe(8550);
});
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Tests\Fakes;
use App\Modules\Shared\Application\Contracts\Settings;
class FakeSettings implements Settings
{
/** @var array<string, string> */
public array $values = [];
public function get(string $key): ?string
{
return $this->values[$key] ?? null;
}
public function put(string $key, ?string $value): void
{
if ($value === null) {
unset($this->values[$key]);
return;
}
$this->values[$key] = $value;
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace Tests\Fakes;
use App\Modules\Catalog\Domain\Contracts\ProductRepository;
use App\Modules\Catalog\Domain\Entities\Product;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
class InMemoryProductRepository implements ProductRepository
{
/** @var array<int, Product> */
public array $items = [];
private int $nextId = 1;
public function findById(int $id): ?Product
{
return isset($this->items[$id]) ? clone $this->items[$id] : null;
}
public function save(Product $product): Product
{
$id = $product->id() ?? $this->nextId++;
$this->items[$id] = Product::reconstitute(
$id,
$product->name(),
$product->unit(),
$product->price(),
$product->isConsumerProduct(),
$product->duration(),
$product->workTypeId(),
$product->isActive(),
$product->sortOrder(),
);
return clone $this->items[$id];
}
public function isNameTaken(string $name, ?int $exceptId = null): bool
{
foreach ($this->items as $id => $product) {
if ($id !== $exceptId && mb_strtolower($product->name()->value) === mb_strtolower($name)) {
return true;
}
}
return false;
}
public function nextSortOrder(): int
{
return array_reduce($this->items, fn (int $max, Product $product): int => max($max, $product->sortOrder()), 0) + 1;
}
public function neighbour(Product $product, MoveDirection $direction): ?Product
{
$candidates = array_values(array_filter($this->items, fn (Product $other): bool => $direction === MoveDirection::Up
? $other->sortOrder() < $product->sortOrder()
: $other->sortOrder() > $product->sortOrder()));
usort($candidates, fn (Product $a, Product $b): int => $direction === MoveDirection::Up
? $b->sortOrder() <=> $a->sortOrder()
: $a->sortOrder() <=> $b->sortOrder());
return isset($candidates[0]) ? clone $candidates[0] : null;
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ class InMemoryWorkTypeRepository implements WorkTypeRepository
public function save(WorkType $workType): WorkType
{
$id = $workType->id() ?? $this->nextId++;
$this->items[$id] = WorkType::reconstitute($id, $workType->serviceUnitId(), $workType->serviceId(), $workType->name(), $workType->isActive(), $workType->sortOrder());
$this->items[$id] = WorkType::reconstitute($id, $workType->serviceUnitId(), $workType->serviceId(), $workType->name(), $workType->isActive(), $workType->sortOrder(), $workType->hourlyRate());
return clone $this->items[$id];
}
@@ -0,0 +1,180 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->management()->create());
$this->workType = fn (string $name) => WorkTypeModel::query()->where('name', $name)->firstOrFail();
});
it('shows the price list pages to admins and management only', function (string $role, int $status) {
$product = ProductModel::factory()->create();
$user = User::factory()->{$role}()->create();
foreach ([route('catalog.prices'), route('catalog.products.create'), route('catalog.products.edit', $product->id)] as $url) {
$this->actingAs($user)->get($url)->assertStatus($status);
}
})->with([
'admin' => ['admin', 200],
'management' => ['management', 200],
'employee' => ['employee', 403],
'intern' => ['intern', 403],
'subcontractor' => ['subcontractor', 403],
]);
it('shows the price list menu link only to those who may manage it', function () {
$this->get(route('customers.index'))->assertSee('Hinnasto');
$this->actingAs(User::factory()->create())->get(route('customers.index'))->assertDontSee('Hinnasto');
});
it('saves and removes hourly rates from the grid', function () {
$programming = ($this->workType)('ohjelmointityö');
Livewire::test('catalog::prices')
->call('saveRate', $programming->id, '85,50')
->assertHasNoErrors()
->assertSet('statusMessage', "ohjelmointityö: tuntihinta 85,50\u{00A0}€ tallennettu.");
expect($programming->refresh()->hourly_rate_cents)->toBe(8550);
Livewire::test('catalog::prices')
->assertSee('value="85,50"', false)
->call('saveRate', $programming->id, '')
->assertSet('statusMessage', 'ohjelmointityö: tuntihinta poistettu.');
expect($programming->refresh()->hourly_rate_cents)->toBeNull();
});
it('shows an invalid hourly rate as a cell error and keeps the typed value', function () {
$editing = WorkTypeModel::factory()->create(['name' => 'leikkaus', 'hourly_rate_cents' => 5000]);
Livewire::test('catalog::prices')
->call('saveRate', $editing->id, '50,123')
->assertHasErrors("rates.{$editing->id}")
->assertSet('errorMessage', 'leikkaus: '.__('catalog.errors.invalid_price'))
->assertSee('value="50,123"', false);
expect($editing->refresh()->hourly_rate_cents)->toBe(5000);
});
it('does not let others save prices through the page actions', function () {
$component = Livewire::test('catalog::prices');
$programming = ($this->workType)('ohjelmointityö');
$this->actingAs(User::factory()->create());
$component->call('saveRate', $programming->id, '85')->assertForbidden();
expect($programming->refresh()->hourly_rate_cents)->toBeNull();
});
it('sets the hourly rate on the work type form', function () {
$programming = ($this->workType)('ohjelmointityö');
Livewire::test('catalog::work-type-form', ['workType' => $programming->id])
->set('form.hourly_rate', '110')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('catalog.index'));
expect($programming->refresh()->hourly_rate_cents)->toBe(11000);
Livewire::test('catalog::work-type-form', ['workType' => $programming->id])
->assertSet('form.hourly_rate', '110,00')
->set('form.hourly_rate', 'paljon')
->call('save')
->assertHasErrors(['form.hourly_rate']);
});
it('adds and edits a product with automatic hours', function () {
$passPhotos = ($this->workType)('passikuvat');
Livewire::test('catalog::product-form')
->set('form.name', 'Passikuvat (4 kpl)')
->set('form.unit', 'package')
->set('form.price', '18,50')
->set('form.is_consumer_product', true)
->set('form.duration', '0,25')
->set('form.work_type_id', (string) $passPhotos->id)
->call('save')
->assertHasNoErrors()
->assertRedirect(route('catalog.prices'));
$product = ProductModel::query()->sole();
expect($product->only(['name', 'unit', 'price_cents', 'is_consumer_product', 'work_type_id']))->toBe([
'name' => 'Passikuvat (4 kpl)',
'unit' => 'package',
'price_cents' => 1850,
'is_consumer_product' => true,
'work_type_id' => $passPhotos->id,
])->and((float) $product->auto_hours)->toBe(0.25);
Livewire::test('catalog::product-form', ['product' => $product->id])
->assertSet('form.price', '18,50')
->assertSet('form.duration', '0,25')
->set('form.price', '20')
->set('form.duration', '')
->set('form.work_type_id', '')
->call('save')
->assertHasNoErrors();
expect($product->refresh()->price_cents)->toBe(2000)
->and($product->work_type_id)->toBeNull();
});
it('shows product rule violations as Finnish field errors', function (array $fields, string $field, string $message) {
ProductModel::factory()->create(['name' => 'Tuloste A4']);
$component = Livewire::test('catalog::product-form')
->set('form.name', 'Tuloste A3')
->set('form.price', '2');
foreach ($fields as $name => $value) {
$component->set("form.{$name}", $value);
}
$component->call('save')->assertHasErrors(["form.{$field}" => [__($message)]]);
})->with([
'name taken' => [['name' => 'tuloste a4'], 'name', 'catalog.errors.product_name_taken'],
'invalid price' => [['price' => '2,555'], 'price', 'catalog.errors.invalid_price'],
'missing price' => [['price' => ''], 'price', 'catalog.errors.price_required'],
'unknown unit' => [['unit' => 'litre'], 'unit', 'catalog.errors.invalid_unit'],
'duration without work type' => [['duration' => '1'], 'work_type_id', 'catalog.errors.work_type_required'],
'invalid duration' => [['duration' => '25'], 'duration', 'catalog.errors.invalid_duration'],
]);
it('moves and deactivates products on the price list page', function () {
$first = ProductModel::factory()->create(['name' => 'Passikuvat', 'sort_order' => 1]);
$second = ProductModel::factory()->create(['name' => 'Tuloste', 'sort_order' => 2]);
Livewire::test('catalog::prices')
->call('move', 'product', $second->id, 'up')
->assertSet('statusMessage', 'Tuloste siirretty ylöspäin.')
->call('toggleActive', 'product', $first->id)
->assertSet('statusMessage', 'Passikuvat poistettu käytöstä. Sitä ei voi enää myydä.');
expect(array_map(fn ($product) => [$product->name, $product->isActive], app(PriceListQueries::class)->products()))
->toBe([['Tuloste', true], ['Passikuvat', false]]);
});
it('saves the mileage rate', function () {
Livewire::test('catalog::prices')
->set('mileageRate', '0,59')
->call('saveMileageRate')
->assertHasNoErrors()
->assertSet('statusMessage', "Km-hinta 0,59\u{00A0}€ tallennettu.");
expect(app(PriceListQueries::class)->mileageRateCents())->toBe(59);
Livewire::test('catalog::prices')
->assertSet('mileageRate', '0,59')
->set('mileageRate', '-1')
->call('saveMileageRate')
->assertHasErrors(['mileageRate']);
});
@@ -71,7 +71,7 @@ it('moves a work type to another service, last there', function () {
$this->addWorkType->execute($this->media, $this->photo, 'kuvaus');
$editing = $this->addWorkType->execute($this->media, $this->video, 'editointi');
$this->updateWorkType->execute($editing, $this->photo, 'editointi');
$this->updateWorkType->execute($editing, $this->photo, 'editointi', '');
$workType = $this->workTypes->findById($editing);
expect($workType?->serviceId())->toBe($this->photo)
@@ -0,0 +1,126 @@
<?php
use App\Modules\Catalog\Application\DTOs\ProductInput;
use App\Modules\Catalog\Application\UseCases\AddProduct;
use App\Modules\Catalog\Application\UseCases\AddServiceUnit;
use App\Modules\Catalog\Application\UseCases\AddWorkType;
use App\Modules\Catalog\Application\UseCases\MoveProduct;
use App\Modules\Catalog\Application\UseCases\SetCatalogItemActive;
use App\Modules\Catalog\Application\UseCases\SetHourlyRate;
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
use App\Modules\Catalog\Application\UseCases\SetProductActive;
use App\Modules\Catalog\Application\UseCases\UpdateProduct;
use App\Modules\Catalog\Application\UseCases\UpdateWorkType;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration;
use App\Modules\Catalog\Domain\Exceptions\ProductNameTaken;
use App\Modules\Catalog\Domain\Exceptions\ProductNeedsWorkType;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use Tests\Fakes\FakeSettings;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryProductRepository;
use Tests\Fakes\InMemoryServiceRepository;
use Tests\Fakes\InMemoryServiceUnitRepository;
use Tests\Fakes\InMemoryWorkTypeRepository;
beforeEach(function () {
$units = new InMemoryServiceUnitRepository;
$services = new InMemoryServiceRepository;
$this->workTypes = new InMemoryWorkTypeRepository;
$this->products = new InMemoryProductRepository;
$this->settings = new FakeSettings;
$transactions = new FakeTransactionManager;
$this->addWorkType = new AddWorkType($units, $services, $this->workTypes, $transactions);
$this->updateWorkType = new UpdateWorkType($units, $services, $this->workTypes, $transactions);
$this->setWorkTypeActive = new SetCatalogItemActive($units, $services, $this->workTypes, $transactions);
$this->setHourlyRate = new SetHourlyRate($this->workTypes, $transactions);
$this->setMileageRate = new SetMileageRate($this->settings);
$this->addProduct = new AddProduct($this->products, $this->workTypes, $transactions);
$this->updateProduct = new UpdateProduct($this->products, $this->workTypes, $transactions);
$this->setProductActive = new SetProductActive($this->products, $transactions);
$this->moveProduct = new MoveProduct($this->products, $transactions);
$consumer = (new AddServiceUnit($units, $transactions))->execute('Kuluttajapalvelut');
$this->passPhotos = $this->addWorkType->execute($consumer, null, 'passikuvat');
});
function productInput(string $name, string $price = '15', string $duration = '', ?int $workTypeId = null): ProductInput
{
return new ProductInput($name, ProductUnit::Piece, $price, true, $duration, $workTypeId);
}
it('sets, changes and removes a work type hourly rate', function () {
$rate = $this->addWorkType->execute(1, null, 'ohjelmointityö', '85');
expect($this->workTypes->findById($rate)?->hourlyRate()?->cents)->toBe(8500);
$this->updateWorkType->execute($rate, null, 'ohjelmointityö', '110,50');
expect($this->workTypes->findById($rate)?->hourlyRate()?->cents)->toBe(11050);
expect($this->setHourlyRate->execute($rate, ''))->toBeNull()
->and($this->workTypes->findById($rate)?->hourlyRate())->toBeNull();
});
it('rejects an invalid hourly rate without saving it', function () {
$this->setHourlyRate->execute($this->passPhotos, '12,345');
})->throws(InvalidMoneyAmount::class);
it('stores and removes the mileage rate', function () {
expect($this->setMileageRate->execute('0,59')?->cents)->toBe(59)
->and($this->settings->get(SetMileageRate::SETTING_KEY))->toBe('59');
$this->setMileageRate->execute('');
expect($this->settings->get(SetMileageRate::SETTING_KEY))->toBeNull();
});
it('adds products last with their price and automatic hours', function () {
$this->addProduct->execute(productInput('Tuloste A4', '1,50'));
$id = $this->addProduct->execute(productInput('Passikuvat', '18', '0,25', $this->passPhotos));
$saved = $this->products->findById($id);
expect($saved?->sortOrder())->toBe(2)
->and($saved?->price()->cents)->toBe(1800)
->and($saved?->duration()->quarters)->toBe(1)
->and($saved?->workTypeId())->toBe($this->passPhotos);
});
it('enforces product rules', function (Closure $add, string $exception) {
$this->addProduct->execute(productInput('Passikuvat'));
expect(fn () => $add->call($this))->toThrow($exception);
})->with([
'name taken, ignoring case' => [fn () => $this->addProduct->execute(productInput('passikuvat')), ProductNameTaken::class],
'price required' => [fn () => $this->addProduct->execute(productInput('Tuloste', '')), InvalidMoneyAmount::class],
'duration needs a work type' => [fn () => $this->addProduct->execute(productInput('Tuloste', '1', '0,5')), ProductNeedsWorkType::class],
'duration in quarters' => [fn () => $this->addProduct->execute(productInput('Tuloste', '1', '0,1', $this->passPhotos)), InvalidProductDuration::class],
'unknown work type' => [fn () => $this->addProduct->execute(productInput('Tuloste', '1', '0,5', 999)), CatalogItemNotFound::class],
]);
it('keeps an inactive work type on update but does not let it be chosen anew', function () {
$id = $this->addProduct->execute(productInput('Passikuvat', '18', '0,25', $this->passPhotos));
$this->setWorkTypeActive->execute(CatalogLevel::WorkType, $this->passPhotos, false);
$this->updateProduct->execute($id, productInput('Passikuvat', '20', '0,25', $this->passPhotos));
expect($this->products->findById($id)?->price()->cents)->toBe(2000);
$other = $this->addProduct->execute(productInput('Tuloste'));
expect(fn () => $this->updateProduct->execute($other, productInput('Tuloste', '1', '0,25', $this->passPhotos)))
->toThrow(CatalogItemNotFound::class);
});
it('moves and deactivates products', function () {
$first = $this->addProduct->execute(productInput('Passikuvat'));
$second = $this->addProduct->execute(productInput('Tuloste'));
expect($this->moveProduct->execute($second, MoveDirection::Up))->toBeTrue()
->and($this->products->findById($second)?->sortOrder())->toBe(1)
->and($this->moveProduct->execute($second, MoveDirection::Up))->toBeFalse();
$this->setProductActive->execute($first, false);
expect($this->products->findById($first)?->isActive())->toBeFalse();
});
+30
View File
@@ -0,0 +1,30 @@
<?php
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
it('parses euro amounts typed in Finnish or English notation', function (string $typed, int $cents) {
expect(Money::parse($typed)?->cents)->toBe($cents);
})->with([
'whole euros' => ['85', 8500],
'comma decimals' => ['85,50', 8550],
'one decimal' => ['85.5', 8550],
'thousands with a space' => ['1 200,00', 120000],
'with the euro sign' => ['0,59 €', 59],
'zero' => ['0', 0],
]);
it('treats an empty value as no amount', function () {
expect(Money::parse(' '))->toBeNull();
});
it('rejects amounts that are not euros with at most two decimals', function (string $typed) {
Money::parse($typed);
})->throws(InvalidMoneyAmount::class)->with(['-5', '1,234', 'abc', '1.000,00', '1000001']);
it('formats with a no-break space and the currency', function () {
$money = Money::fromCents(120050);
expect($money->format())->toBe("1\u{00A0}200,50\u{00A0}€")
->and($money->inputValue())->toBe('1200,50');
});