diff --git a/CLAUDE.md b/CLAUDE.md index a8ec161..5b551a9 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) `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) 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). - **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. @@ -25,6 +25,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **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`). 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, VAT 0, `parse()` accepts "85,50", `format()` gives "85,50 €"); store it in `*_cents` integer columns. App-wide settings go through `Shared\Application\Contracts\Settings` (`settings` table) with keys prefixed by the owning module. - `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`. - Generate module files with Artisan, then edit them: `php artisan make:class Modules////` for classes, `make:test --pest [--unit] Modules//Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files. - When writing PHP through a bash heredoc, `\\` can collapse to `\`, and `"App\Modules\{$x}"` then stops interpolating. Write PHP files with the Write tool. diff --git a/app/Modules/Catalog/Application/Contracts/PriceListQueries.php b/app/Modules/Catalog/Application/Contracts/PriceListQueries.php new file mode 100644 index 0000000..5e4ca6a --- /dev/null +++ b/app/Modules/Catalog/Application/Contracts/PriceListQueries.php @@ -0,0 +1,38 @@ + + */ + public function hourlyRates(bool $includeInactive = true): array; + + public function hourlyRateCentsOf(int $workTypeId): ?int; + + /** + * @return list + */ + public function products(bool $includeInactive = true): array; + + public function findProduct(int $id): ?ProductSummary; + + /** + * Price of a driven kilometre in cents (VAT 0), null when not set. + */ + public function mileageRateCents(): ?int; +} diff --git a/app/Modules/Catalog/Application/DTOs/HourlyRateGroup.php b/app/Modules/Catalog/Application/DTOs/HourlyRateGroup.php new file mode 100644 index 0000000..5fabfa3 --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/HourlyRateGroup.php @@ -0,0 +1,21 @@ + $rows + */ + public function __construct( + public int $serviceUnitId, + public string $serviceUnitName, + public bool $isActive, + public array $rows, + ) {} +} diff --git a/app/Modules/Catalog/Application/DTOs/HourlyRateRow.php b/app/Modules/Catalog/Application/DTOs/HourlyRateRow.php new file mode 100644 index 0000000..7ce1db8 --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/HourlyRateRow.php @@ -0,0 +1,19 @@ +transactions->run(function () use ($fields): int { + $fields->ensureWorkTypeIsUsable($this->workTypes); + + if ($this->products->isNameTaken($fields->name->value)) { + throw new ProductNameTaken; + } + + $product = Product::create( + $fields->name, + $fields->unit, + $fields->price, + $fields->isConsumerProduct, + $fields->duration, + $fields->workTypeId, + $this->products->nextSortOrder(), + ); + + return (int) $this->products->save($product)->id(); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/AddWorkType.php b/app/Modules/Catalog/Application/UseCases/AddWorkType.php index 3bfa553..5518dc5 100644 --- a/app/Modules/Catalog/Application/UseCases/AddWorkType.php +++ b/app/Modules/Catalog/Application/UseCases/AddWorkType.php @@ -14,6 +14,8 @@ use App\Modules\Catalog\Domain\Exceptions\CatalogNameTaken; use App\Modules\Catalog\Domain\Exceptions\ServiceNotInUnit; use App\Modules\Catalog\Domain\ValueObjects\CatalogName; use App\Modules\Shared\Application\Contracts\TransactionManager; +use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; +use App\Modules\Shared\Domain\ValueObjects\Money; final class AddWorkType { @@ -29,13 +31,15 @@ final class AddWorkType * * @throws CatalogItemNotFound * @throws CatalogNameTaken + * @throws InvalidMoneyAmount * @throws ServiceNotInUnit */ - public function execute(int $serviceUnitId, ?int $serviceId, string $name): int + public function execute(int $serviceUnitId, ?int $serviceId, string $name, string $hourlyRate = ''): int { $name = new CatalogName($name); + $rate = Money::parse($hourlyRate); - return $this->transactions->run(function () use ($serviceUnitId, $serviceId, $name): int { + return $this->transactions->run(function () use ($serviceUnitId, $serviceId, $name, $rate): int { $serviceUnit = $this->serviceUnits->findById($serviceUnitId) ?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $serviceUnitId); $service = $serviceId === null ? null : ($this->services->findById($serviceId) @@ -45,7 +49,7 @@ final class AddWorkType throw new CatalogNameTaken; } - $workType = WorkType::create($serviceUnit, $service, $name, $this->workTypes->nextSortOrder($serviceUnitId, $serviceId)); + $workType = WorkType::create($serviceUnit, $service, $name, $this->workTypes->nextSortOrder($serviceUnitId, $serviceId), $rate); return (int) $this->workTypes->save($workType)->id(); }); diff --git a/app/Modules/Catalog/Application/UseCases/MoveProduct.php b/app/Modules/Catalog/Application/UseCases/MoveProduct.php new file mode 100644 index 0000000..a4c8044 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/MoveProduct.php @@ -0,0 +1,44 @@ +transactions->run(function () use ($productId, $direction): bool { + $product = $this->products->findById($productId) ?? throw new ProductNotFound($productId); + $neighbour = $this->products->neighbour($product, $direction); + + if ($neighbour === null) { + return false; + } + + $product->swapOrderWith($neighbour); + $this->products->save($product); + $this->products->save($neighbour); + + return true; + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/ProductFields.php b/app/Modules/Catalog/Application/UseCases/ProductFields.php new file mode 100644 index 0000000..b35fb0e --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/ProductFields.php @@ -0,0 +1,69 @@ +name), + $input->unit, + Money::parse($input->price) ?? throw new InvalidMoneyAmount, + $input->isConsumerProduct, + ProductDuration::parse($input->duration), + $input->workTypeId, + ); + } + + /** + * A newly chosen work type must exist and be in use. + * + * @throws CatalogItemNotFound + */ + public function ensureWorkTypeIsUsable(WorkTypeRepository $workTypes): void + { + if ($this->workTypeId === null) { + return; + } + + $workType = $workTypes->findById($this->workTypeId); + + if ($workType === null || ! $workType->isActive()) { + throw new CatalogItemNotFound(CatalogLevel::WorkType, $this->workTypeId); + } + } +} diff --git a/app/Modules/Catalog/Application/UseCases/SetHourlyRate.php b/app/Modules/Catalog/Application/UseCases/SetHourlyRate.php new file mode 100644 index 0000000..b3005b5 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/SetHourlyRate.php @@ -0,0 +1,45 @@ +transactions->run(function () use ($workTypeId, $rate): void { + $workType = $this->workTypes->findById($workTypeId) + ?? throw new CatalogItemNotFound(CatalogLevel::WorkType, $workTypeId); + + $workType->changeHourlyRate($rate); + $this->workTypes->save($workType); + }); + + return $rate; + } +} diff --git a/app/Modules/Catalog/Application/UseCases/SetMileageRate.php b/app/Modules/Catalog/Application/UseCases/SetMileageRate.php new file mode 100644 index 0000000..9abe35f --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/SetMileageRate.php @@ -0,0 +1,33 @@ +settings->put(self::SETTING_KEY, $rate === null ? null : (string) $rate->cents); + + return $rate; + } +} diff --git a/app/Modules/Catalog/Application/UseCases/SetProductActive.php b/app/Modules/Catalog/Application/UseCases/SetProductActive.php new file mode 100644 index 0000000..d73f257 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/SetProductActive.php @@ -0,0 +1,34 @@ +transactions->run(function () use ($productId, $active): void { + $product = $this->products->findById($productId) ?? throw new ProductNotFound($productId); + + $active ? $product->activate() : $product->deactivate(); + $this->products->save($product); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/UpdateProduct.php b/app/Modules/Catalog/Application/UseCases/UpdateProduct.php new file mode 100644 index 0000000..d4b0bd2 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/UpdateProduct.php @@ -0,0 +1,60 @@ +transactions->run(function () use ($productId, $fields): void { + $product = $this->products->findById($productId) ?? throw new ProductNotFound($productId); + + // An inactive work type may stay, but it cannot be newly chosen. + if ($fields->workTypeId !== $product->workTypeId()) { + $fields->ensureWorkTypeIsUsable($this->workTypes); + } + + if ($this->products->isNameTaken($fields->name->value, $productId)) { + throw new ProductNameTaken; + } + + $product->update($fields->name, $fields->unit, $fields->price, $fields->isConsumerProduct, $fields->duration, $fields->workTypeId); + $this->products->save($product); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/UpdateWorkType.php b/app/Modules/Catalog/Application/UseCases/UpdateWorkType.php index c32b43c..21c7339 100644 --- a/app/Modules/Catalog/Application/UseCases/UpdateWorkType.php +++ b/app/Modules/Catalog/Application/UseCases/UpdateWorkType.php @@ -13,10 +13,12 @@ use App\Modules\Catalog\Domain\Exceptions\CatalogNameTaken; use App\Modules\Catalog\Domain\Exceptions\ServiceNotInUnit; use App\Modules\Catalog\Domain\ValueObjects\CatalogName; use App\Modules\Shared\Application\Contracts\TransactionManager; +use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; +use App\Modules\Shared\Domain\ValueObjects\Money; /** - * Renames a work type and moves it under another service of its unit (or - * under no service). + * Renames a work type, sets its hourly rate (empty removes it) and moves it + * under another service of its unit (or under no service). */ final class UpdateWorkType { @@ -30,13 +32,15 @@ final class UpdateWorkType /** * @throws CatalogItemNotFound * @throws CatalogNameTaken + * @throws InvalidMoneyAmount * @throws ServiceNotInUnit */ - public function execute(int $workTypeId, ?int $serviceId, string $name): void + public function execute(int $workTypeId, ?int $serviceId, string $name, string $hourlyRate): void { $name = new CatalogName($name); + $rate = Money::parse($hourlyRate); - $this->transactions->run(function () use ($workTypeId, $serviceId, $name): void { + $this->transactions->run(function () use ($workTypeId, $serviceId, $name, $rate): void { $workType = $this->workTypes->findById($workTypeId) ?? throw new CatalogItemNotFound(CatalogLevel::WorkType, $workTypeId); @@ -54,6 +58,7 @@ final class UpdateWorkType } $workType->rename($name); + $workType->changeHourlyRate($rate); $this->workTypes->save($workType); }); } diff --git a/app/Modules/Catalog/Domain/Contracts/ProductRepository.php b/app/Modules/Catalog/Domain/Contracts/ProductRepository.php new file mode 100644 index 0000000..9f708d0 --- /dev/null +++ b/app/Modules/Catalog/Domain/Contracts/ProductRepository.php @@ -0,0 +1,33 @@ +name = $name; + $this->unit = $unit; + $this->price = $price; + $this->consumerProduct = $consumerProduct; + $this->duration = $duration; + $this->workTypeId = $workTypeId; + } + + public function unit(): ProductUnit + { + return $this->unit; + } + + public function price(): Money + { + return $this->price; + } + + public function isConsumerProduct(): bool + { + return $this->consumerProduct; + } + + public function duration(): ProductDuration + { + return $this->duration; + } + + public function workTypeId(): ?int + { + return $this->workTypeId; + } + + private static function ensureWorkTypeForDuration(ProductDuration $duration, ?int $workTypeId): void + { + if (! $duration->isNone() && $workTypeId === null) { + throw new ProductNeedsWorkType; + } + } +} diff --git a/app/Modules/Catalog/Domain/Entities/WorkType.php b/app/Modules/Catalog/Domain/Entities/WorkType.php index d595bf5..0d361a2 100644 --- a/app/Modules/Catalog/Domain/Entities/WorkType.php +++ b/app/Modules/Catalog/Domain/Entities/WorkType.php @@ -6,10 +6,11 @@ namespace App\Modules\Catalog\Domain\Entities; use App\Modules\Catalog\Domain\Exceptions\ServiceNotInUnit; use App\Modules\Catalog\Domain\ValueObjects\CatalogName; +use App\Modules\Shared\Domain\ValueObjects\Money; /** * A work type (työtehtävä), e.g. editointi. Tasks and time entries are - * recorded against work types, and hourly rates (phase 2) belong to them. + * recorded against work types, and the hourly rate (VAT 0) belongs to them. */ final class WorkType extends CatalogItem { @@ -20,6 +21,7 @@ final class WorkType extends CatalogItem CatalogName $name, bool $active, int $sortOrder, + private ?Money $hourlyRate = null, ) { parent::__construct($id, $name, $active, $sortOrder); } @@ -27,16 +29,29 @@ final class WorkType extends CatalogItem /** * @throws ServiceNotInUnit */ - public static function create(ServiceUnit $serviceUnit, ?Service $service, CatalogName $name, int $sortOrder): self + public static function create(ServiceUnit $serviceUnit, ?Service $service, CatalogName $name, int $sortOrder, ?Money $hourlyRate = null): self { self::ensureServiceInUnit($serviceUnit, $service); - return new self(null, (int) $serviceUnit->id(), $service?->id(), $name, true, $sortOrder); + return new self(null, (int) $serviceUnit->id(), $service?->id(), $name, true, $sortOrder, $hourlyRate); } - public static function reconstitute(int $id, int $serviceUnitId, ?int $serviceId, CatalogName $name, bool $active, int $sortOrder): self + public static function reconstitute(int $id, int $serviceUnitId, ?int $serviceId, CatalogName $name, bool $active, int $sortOrder, ?Money $hourlyRate = null): self { - return new self($id, $serviceUnitId, $serviceId, $name, $active, $sortOrder); + return new self($id, $serviceUnitId, $serviceId, $name, $active, $sortOrder, $hourlyRate); + } + + /** + * Null means the work type has no price yet. + */ + public function hourlyRate(): ?Money + { + return $this->hourlyRate; + } + + public function changeHourlyRate(?Money $hourlyRate): void + { + $this->hourlyRate = $hourlyRate; } /** diff --git a/app/Modules/Catalog/Domain/Enums/ProductUnit.php b/app/Modules/Catalog/Domain/Enums/ProductUnit.php new file mode 100644 index 0000000..37afa88 --- /dev/null +++ b/app/Modules/Catalog/Domain/Enums/ProductUnit.php @@ -0,0 +1,18 @@ + self::MAX_QUARTERS) { + throw new InvalidProductDuration; + } + + $this->quarters = $quarters; + } + + public static function none(): self + { + return new self(0); + } + + /** + * Parses "0,5", "0.25" or "1"; an empty value is zero. + * + * @throws InvalidProductDuration + */ + public static function parse(string $value): self + { + $value = str_replace(',', '.', trim($value)); + + if ($value === '') { + return self::none(); + } + + if (preg_match('/^\d{1,2}(?:\.\d{1,2})?$/', $value) !== 1) { + throw new InvalidProductDuration; + } + + $quarters = (float) $value * 4; + + if (abs($quarters - round($quarters)) > 1e-9) { + throw new InvalidProductDuration; + } + + return new self((int) round($quarters)); + } + + public static function fromDecimal(float $hours): self + { + return new self((int) round($hours * 4)); + } + + public function isNone(): bool + { + return $this->quarters === 0; + } + + public function decimal(): float + { + return $this->quarters / 4; + } + + /** + * Finnish notation without trailing zeros, e.g. "0,25" or "1". + */ + public function format(): string + { + return str_replace('.', ',', rtrim(rtrim(number_format($this->quarters / 4, 2, '.', ''), '0'), '.')); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ProductModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ProductModel.php new file mode 100644 index 0000000..2935514 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ProductModel.php @@ -0,0 +1,57 @@ + */ + use HasFactory; + + /** + * @return BelongsTo + */ + public function workType(): BelongsTo + { + return $this->belongsTo(WorkTypeModel::class, 'work_type_id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'price_cents' => 'integer', + 'is_consumer_product' => 'boolean', + 'auto_hours' => 'decimal:2', + 'work_type_id' => 'integer', + 'is_active' => 'boolean', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkTypeModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkTypeModel.php index 480570d..9ae883e 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkTypeModel.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkTypeModel.php @@ -16,11 +16,12 @@ use Illuminate\Database\Eloquent\Model; * @property int $service_unit_id * @property int|null $service_id * @property string $name + * @property int|null $hourly_rate_cents * @property bool $is_active * @property int $sort_order */ #[Table('work_types')] -#[Fillable(['service_unit_id', 'service_id', 'name', 'is_active', 'sort_order'])] +#[Fillable(['service_unit_id', 'service_id', 'name', 'hourly_rate_cents', 'is_active', 'sort_order'])] #[UseFactory(WorkTypeFactory::class)] class WorkTypeModel extends Model { @@ -35,6 +36,7 @@ class WorkTypeModel extends Model return [ 'service_unit_id' => 'integer', 'service_id' => 'integer', + 'hourly_rate_cents' => 'integer', 'is_active' => 'boolean', 'sort_order' => 'integer', ]; diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php new file mode 100644 index 0000000..f49962a --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php @@ -0,0 +1,99 @@ + $rates */ + $rates = WorkTypeModel::query()->pluck('hourly_rate_cents', 'id')->all(); + + return array_map(function (ServiceUnitNode $node) use ($rates): HourlyRateGroup { + $row = fn (WorkTypeSummary $workType, ?string $serviceName, bool $parentActive): HourlyRateRow => new HourlyRateRow( + $workType->id, + $workType->name, + $serviceName, + $workType->isActive && $parentActive, + $rates[$workType->id] ?? null, + ); + + $rows = array_map(fn (WorkTypeSummary $workType): HourlyRateRow => $row($workType, null, true), $node->workTypes); + + foreach ($node->services as $serviceNode) { + foreach ($serviceNode->workTypes as $workType) { + $rows[] = $row($workType, $serviceNode->service->name, $serviceNode->service->isActive); + } + } + + return new HourlyRateGroup($node->serviceUnit->id, $node->serviceUnit->name, $node->serviceUnit->isActive, $rows); + }, $this->catalogQueries->tree($includeInactive)); + } + + public function hourlyRateCentsOf(int $workTypeId): ?int + { + $cents = WorkTypeModel::query()->whereKey($workTypeId)->value('hourly_rate_cents'); + + return $cents === null ? null : (int) $cents; + } + + public function products(bool $includeInactive = true): array + { + return ProductModel::query() + ->with('workType') + ->when(! $includeInactive, fn ($query) => $query->where('is_active', true)) + ->orderBy('sort_order') + ->get() + ->map(fn (ProductModel $model): ProductSummary => $this->toSummary($model)) + ->values() + ->all(); + } + + public function findProduct(int $id): ?ProductSummary + { + $model = ProductModel::query()->with('workType')->find($id); + + return $model === null ? null : $this->toSummary($model); + } + + public function mileageRateCents(): ?int + { + $value = $this->settings->get(SetMileageRate::SETTING_KEY); + + return $value === null ? null : (int) $value; + } + + private function toSummary(ProductModel $model): ProductSummary + { + return new ProductSummary( + $model->id, + $model->name, + ProductUnit::from($model->unit), + $model->price_cents, + $model->is_consumer_product, + ProductDuration::fromDecimal((float) $model->auto_hours)->quarters, + $model->work_type_id, + $model->workType?->name, + $model->is_active, + ); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentProductRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentProductRepository.php new file mode 100644 index 0000000..8fcac0a --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentProductRepository.php @@ -0,0 +1,78 @@ +find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function save(Product $product): Product + { + $model = $product->id() === null ? new ProductModel : ProductModel::query()->findOrFail($product->id()); + + $model->fill([ + 'name' => $product->name()->value, + 'unit' => $product->unit()->value, + 'price_cents' => $product->price()->cents, + 'is_consumer_product' => $product->isConsumerProduct(), + 'auto_hours' => $product->duration()->decimal(), + 'work_type_id' => $product->workTypeId(), + 'is_active' => $product->isActive(), + 'sort_order' => $product->sortOrder(), + ])->save(); + + return $this->toEntity($model); + } + + public function isNameTaken(string $name, ?int $exceptId = null): bool + { + return ProductModel::query() + ->whereRaw('LOWER(name) = ?', [mb_strtolower($name)]) + ->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId)) + ->exists(); + } + + public function nextSortOrder(): int + { + return (int) ProductModel::query()->max('sort_order') + 1; + } + + public function neighbour(Product $product, MoveDirection $direction): ?Product + { + $model = ProductModel::query() + ->where('sort_order', $direction === MoveDirection::Up ? '<' : '>', $product->sortOrder()) + ->orderBy('sort_order', $direction === MoveDirection::Up ? 'desc' : 'asc') + ->first(); + + return $model === null ? null : $this->toEntity($model); + } + + private function toEntity(ProductModel $model): Product + { + return Product::reconstitute( + $model->id, + new CatalogName($model->name), + ProductUnit::from($model->unit), + Money::fromCents($model->price_cents), + $model->is_consumer_product, + ProductDuration::fromDecimal((float) $model->auto_hours), + $model->work_type_id, + $model->is_active, + $model->sort_order, + ); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkTypeRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkTypeRepository.php index 8008603..1c53d11 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkTypeRepository.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkTypeRepository.php @@ -7,6 +7,7 @@ use App\Modules\Catalog\Domain\Entities\WorkType; use App\Modules\Catalog\Domain\Enums\MoveDirection; use App\Modules\Catalog\Domain\ValueObjects\CatalogName; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; +use App\Modules\Shared\Domain\ValueObjects\Money; use Illuminate\Database\Eloquent\Builder; class EloquentWorkTypeRepository implements WorkTypeRepository @@ -26,6 +27,7 @@ class EloquentWorkTypeRepository implements WorkTypeRepository 'service_unit_id' => $workType->serviceUnitId(), 'service_id' => $workType->serviceId(), 'name' => $workType->name()->value, + 'hourly_rate_cents' => $workType->hourlyRate()?->cents, 'is_active' => $workType->isActive(), 'sort_order' => $workType->sortOrder(), ])->save(); @@ -79,6 +81,7 @@ class EloquentWorkTypeRepository implements WorkTypeRepository new CatalogName($model->name), $model->is_active, $model->sort_order, + $model->hourly_rate_cents === null ? null : Money::fromCents($model->hourly_rate_cents), ); } } diff --git a/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php b/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php index 818e731..36fb3fd 100644 --- a/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php +++ b/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php @@ -4,10 +4,14 @@ namespace App\Modules\Catalog\Infrastructure\Providers; use App\Models\User; use App\Modules\Catalog\Application\Contracts\CatalogQueries; +use App\Modules\Catalog\Application\Contracts\PriceListQueries; +use App\Modules\Catalog\Domain\Contracts\ProductRepository; use App\Modules\Catalog\Domain\Contracts\ServiceRepository; use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository; use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentCatalogQueries; +use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentPriceListQueries; +use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentProductRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceUnitRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkTypeRepository; @@ -17,7 +21,7 @@ use Illuminate\Support\ServiceProvider; use Livewire\Livewire; /** - * Wires the Catalog module (service units, services, work types) into + * Wires the Catalog module (service units, services, work types, price list) into * Laravel: bindings, routes, the `catalog::` Livewire namespace and the * `catalog.manage` ability. */ @@ -31,6 +35,8 @@ class CatalogServiceProvider extends ServiceProvider ServiceRepository::class => EloquentServiceRepository::class, WorkTypeRepository::class => EloquentWorkTypeRepository::class, CatalogQueries::class => EloquentCatalogQueries::class, + ProductRepository::class => EloquentProductRepository::class, + PriceListQueries::class => EloquentPriceListQueries::class, ]; public function boot(): void @@ -43,7 +49,7 @@ class CatalogServiceProvider extends ServiceProvider $this->loadRoutesFrom($presentationPath.'/Routes/web.php'); } - // Catalog data (pohjatiedot) is managed by admins and management. + // Catalog data (pohjatiedot) and the price list are managed by admins and management. Gate::define('catalog.manage', fn (User $user): bool => in_array($user->role, [Role::Admin, Role::Management], true)); } } diff --git a/app/Modules/Catalog/Presentation/Livewire/Forms/CatalogItemForm.php b/app/Modules/Catalog/Presentation/Livewire/Forms/CatalogItemForm.php index 962b8e7..d638ee8 100644 --- a/app/Modules/Catalog/Presentation/Livewire/Forms/CatalogItemForm.php +++ b/app/Modules/Catalog/Presentation/Livewire/Forms/CatalogItemForm.php @@ -7,10 +7,11 @@ use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName; use App\Modules\Catalog\Domain\Exceptions\ServiceNotInUnit; use App\Modules\Catalog\Domain\Exceptions\SharedUnitHasNoServices; use App\Modules\Shared\Domain\Exceptions\DomainException; +use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; use Livewire\Form; /** - * Name (and for work types, service) of a service unit, service or work type. + * Name (and for work types, service and hourly rate) of a service unit, service or work type. */ class CatalogItemForm extends Form { @@ -21,6 +22,11 @@ class CatalogItemForm extends Form */ public string $service_id = ''; + /** + * Only for work types, as typed ("85,50"); '' means no rate. + */ + public string $hourly_rate = ''; + public function validatedName(): string { $this->validate(); @@ -43,6 +49,7 @@ class CatalogItemForm extends Form CatalogNameTaken::class => ['name', 'catalog.errors.name_taken'], ServiceNotInUnit::class => ['service_id', 'catalog.errors.service_not_in_unit'], SharedUnitHasNoServices::class => ['name', 'catalog.errors.shared_unit_has_no_services'], + InvalidMoneyAmount::class => ['hourly_rate', 'catalog.errors.invalid_price'], default => throw $exception, }; @@ -57,6 +64,7 @@ class CatalogItemForm extends Form return [ 'name' => ['required', 'string', 'max:100'], 'service_id' => ['nullable', 'integer'], + 'hourly_rate' => ['nullable', 'string', 'max:20'], ]; } @@ -69,6 +77,7 @@ class CatalogItemForm extends Form 'name.required' => __('catalog.errors.name_required'), 'name.max' => __('catalog.errors.invalid_name'), 'service_id.integer' => __('catalog.errors.service_not_in_unit'), + 'hourly_rate.max' => __('catalog.errors.invalid_price'), ]; } } diff --git a/app/Modules/Catalog/Presentation/Livewire/Forms/ProductForm.php b/app/Modules/Catalog/Presentation/Livewire/Forms/ProductForm.php new file mode 100644 index 0000000..d0d8d60 --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/Forms/ProductForm.php @@ -0,0 +1,114 @@ +name = $product->name; + $this->unit = $product->unit->value; + $this->price = Money::fromCents($product->priceCents)->inputValue(); + $this->is_consumer_product = $product->isConsumerProduct; + $this->duration = $product->durationQuarters === 0 ? '' : (new ProductDuration($product->durationQuarters))->format(); + $this->work_type_id = $product->workTypeId === null ? '' : (string) $product->workTypeId; + } + + public function toInput(): ProductInput + { + $this->validate(); + + return new ProductInput( + $this->name, + ProductUnit::from($this->unit), + $this->price, + $this->is_consumer_product, + $this->duration, + $this->work_type_id === '' ? null : (int) $this->work_type_id, + ); + } + + /** + * Shows a broken business rule as an error on the field it concerns. + */ + public function showDomainError(DomainException $exception): void + { + [$field, $key] = match ($exception::class) { + InvalidCatalogName::class => ['name', 'catalog.errors.invalid_name'], + ProductNameTaken::class => ['name', 'catalog.errors.product_name_taken'], + InvalidMoneyAmount::class => ['price', 'catalog.errors.invalid_price'], + InvalidProductDuration::class => ['duration', 'catalog.errors.invalid_duration'], + ProductNeedsWorkType::class => ['work_type_id', 'catalog.errors.work_type_required'], + CatalogItemNotFound::class => ['work_type_id', 'catalog.errors.work_type_unavailable'], + default => throw $exception, + }; + + $this->addError($field, __($key)); + } + + /** + * @return array> + */ + protected function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:100'], + 'unit' => ['required', Rule::enum(ProductUnit::class)], + 'price' => ['required', 'string', 'max:20'], + 'is_consumer_product' => ['boolean'], + 'duration' => ['nullable', 'string', 'max:10'], + 'work_type_id' => ['nullable', 'integer'], + ]; + } + + /** + * @return array + */ + protected function messages(): array + { + return [ + 'name.required' => __('catalog.errors.name_required'), + 'name.max' => __('catalog.errors.invalid_name'), + 'unit.required' => __('catalog.errors.invalid_unit'), + 'unit.enum' => __('catalog.errors.invalid_unit'), + 'price.required' => __('catalog.errors.price_required'), + 'price.max' => __('catalog.errors.invalid_price'), + 'duration.max' => __('catalog.errors.invalid_duration'), + 'work_type_id.integer' => __('catalog.errors.work_type_unavailable'), + ]; + } +} diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php index 128b56d..7b62f6d 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php @@ -119,7 +119,10 @@ new class extends Component -

{{ __('catalog.intro') }}

+
+

{{ __('catalog.intro') }}

+

{{ __('catalog.prices_link') }}

+
@if (session('status')) diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php new file mode 100644 index 0000000..a2ec4df --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php @@ -0,0 +1,371 @@ + + */ + #[Locked] + public array $rejected = []; + + public string $mileageRate = ''; + + protected PriceListQueries $priceList; + + public function boot(PriceListQueries $priceList): void + { + $this->priceList = $priceList; + } + + public function mount(): void + { + $this->authorize('catalog.manage'); + + $this->mileageRate = $this->inputValue($this->priceList->mileageRateCents()); + } + + /** + * @return list + */ + #[Computed] + public function hourlyRates(): array + { + return $this->priceList->hourlyRates($this->showInactive); + } + + /** + * @return list + */ + #[Computed] + public function products(): array + { + return $this->priceList->products($this->showInactive); + } + + public function saveRate(int $workTypeId, string $value, SetHourlyRate $setHourlyRate): void + { + $this->authorize('catalog.manage'); + + $row = $this->rateRow($workTypeId); + + if ($row === null) { + return; + } + + $this->resetErrorBag("rates.{$workTypeId}"); + unset($this->rejected[$workTypeId]); + $this->errorMessage = ''; + + try { + $rate = $setHourlyRate->execute($workTypeId, $value); + } catch (InvalidMoneyAmount|CatalogItemNotFound $exception) { + $message = __($exception instanceof InvalidMoneyAmount ? 'catalog.errors.invalid_price' : 'catalog.status.not_found'); + $this->addError("rates.{$workTypeId}", $message); + $this->errorMessage = $row->name.': '.$message; + $this->rejected[$workTypeId] = $value; + + return; + } + + unset($this->hourlyRates); + + $this->statusMessage = $rate === null + ? __('catalog.prices.rate_removed', ['name' => $row->name]) + : __('catalog.prices.rate_saved', ['name' => $row->name, 'rate' => $rate->format()]); + } + + /** + * Called by the row actions shared with the catalog page, so the level is always "product". + */ + public function move(string $level, int $id, string $direction, MoveProduct $moveProduct): void + { + $this->authorize('catalog.manage'); + + $moveDirection = MoveDirection::from($direction); + $name = $this->priceList->findProduct($id)?->name ?? ''; + + try { + $moved = $moveProduct->execute($id, $moveDirection); + } catch (ProductNotFound) { + $this->statusMessage = __('catalog.status.not_found'); + + return; + } + + unset($this->products); + + $this->statusMessage = __(match (true) { + $moved && $moveDirection === MoveDirection::Up => 'catalog.status.moved_up', + $moved => 'catalog.status.moved_down', + $moveDirection === MoveDirection::Up => 'catalog.status.already_first', + default => 'catalog.status.already_last', + }, ['name' => $name]); + + // The row moved in the DOM: keep focus on the same button. + $this->js("document.getElementById('move-{$moveDirection->value}-product-{$id}')?.focus()"); + } + + public function toggleActive(string $level, int $id, SetProductActive $setActive): void + { + $this->authorize('catalog.manage'); + + $product = $this->priceList->findProduct($id); + + if ($product === null) { + $this->statusMessage = __('catalog.status.not_found'); + + return; + } + + $setActive->execute($id, ! $product->isActive); + unset($this->products); + + $this->statusMessage = __($product->isActive ? 'catalog.products.deactivated' : 'catalog.status.activated', ['name' => $product->name]); + } + + public function saveMileageRate(SetMileageRate $setMileageRate): void + { + $this->authorize('catalog.manage'); + + $this->resetErrorBag('mileageRate'); + + try { + $rate = $setMileageRate->execute($this->mileageRate); + } catch (InvalidMoneyAmount) { + $this->addError('mileageRate', __('catalog.errors.invalid_price')); + + return; + } + + $this->mileageRate = $rate?->inputValue() ?? ''; + $this->statusMessage = $rate === null + ? __('catalog.mileage.removed') + : __('catalog.mileage.saved', ['rate' => $rate->format()]); + } + + /** + * @return list + */ + public function productHeaders(): array + { + return [ + ['index' => 'name', 'label' => __('catalog.fields.name'), 'sortable' => false], + ['index' => 'unit', 'label' => __('catalog.products.unit'), 'sortable' => false], + ['index' => 'price', 'label' => __('catalog.products.price_column'), 'sortable' => false, 'align' => 'right'], + ['index' => 'consumer', 'label' => __('catalog.products.consumer_column'), 'sortable' => false], + ['index' => 'duration', 'label' => __('catalog.products.duration_column'), 'sortable' => false], + ['index' => 'actions', 'label' => __('catalog.products.actions'), 'sortable' => false], + ]; + } + + public function money(?int $cents): string + { + return $cents === null ? '' : Money::fromCents($cents)->format(); + } + + public function inputValue(?int $cents): string + { + return $cents === null ? '' : Money::fromCents($cents)->inputValue(); + } + + public function duration(int $quarters): string + { + return (new ProductDuration($quarters))->format(); + } + + public function render(): mixed + { + return $this->view()->title(__('catalog.prices.title')); + } + + private function rateRow(int $workTypeId): ?HourlyRateRow + { + foreach ($this->priceList->hourlyRates() as $group) { + foreach ($group->rows as $row) { + if ($row->workTypeId === $workTypeId) { + return $row; + } + } + } + + return null; + } +}; +?> + +
+
+

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

+

{{ __('catalog.prices.intro') }}

+
+ + @if (session('status')) + + @endif + + + +
+

{{ $statusMessage }}

+ +
+ +
+
+

{{ __('catalog.prices.hourly_rates') }}

+

{{ __('catalog.prices.hourly_rates_help') }}

+
+ + @foreach ($this->hourlyRates as $group) + @if ($group->rows !== []) + {{-- An input grid is a form, so a native table rather than . --}} + + + + + + + + + + @foreach ($group->rows as $row) + + + + + @endforeach + +
+ {{ $group->serviceUnitName }} + @unless ($group->isActive) + ({{ __('catalog.inactive') }}) + @endunless +
{{ __('catalog.prices.work_type') }}{{ __('catalog.prices.hourly_rate') }}
+ @if ($row->serviceName !== null) + {{ $row->serviceName }}: + @endif + {{ $row->name }} + @unless ($row->isActive) + ({{ __('catalog.inactive') }}) + @endunless + + workTypeId) aria-invalid="true" aria-describedby="rate-{{ $row->workTypeId }}-error" @enderror + class="w-24 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400" + /> + @error('rates.'.$row->workTypeId) +

{{ $message }}

+ @enderror +
+ @endif + @endforeach +
+ +
+
+

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

+ +
+

{{ __('catalog.products.help') }}

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

{{ __('catalog.products.none') }}

+ @else + + @interact('column_name', $product) + {{ $product->name }} + @unless ($product->isActive) + ({{ __('catalog.inactive') }}) + @endunless + @endinteract + + @interact('column_unit', $product) + {{ __('catalog.units.'.$product->unit->value) }} + @endinteract + + @interact('column_price', $product) + {{ $this->money($product->priceCents) }} + @endinteract + + @interact('column_consumer', $product) + {{ $product->isConsumerProduct ? __('catalog.yes') : __('catalog.no') }} + @endinteract + + @interact('column_duration', $product) + @if ($product->durationQuarters > 0) + {{ __('catalog.products.duration_value', ['hours' => $this->duration($product->durationQuarters)]) }} + @if ($product->workTypeName !== null) + {{ $product->workTypeName }} + @endif + @else + {{ __('catalog.products.no_duration') }} + @endif + @endinteract + + @interact('column_actions', $product) + + @endinteract + + @endif +
+ +
+

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

+ +
+
+ +
+ + +
+
diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php new file mode 100644 index 0000000..c3497fa --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php @@ -0,0 +1,185 @@ +authorize('catalog.manage'); + + if ($product !== null) { + $summary = $priceList->findProduct($product); + + abort_if($summary === null, 404); + + $this->productId = $summary->id; + $this->storedWorkTypeId = $summary->workTypeId; + $this->form->fillFrom($summary); + } + } + + /** + * Work types to choose from, grouped by service unit (and service). + * + * @return array> + */ + #[Computed] + public function workTypeGroups(): array + { + $catalogQueries = app(CatalogQueries::class); + $groups = []; + $listed = []; + + foreach ($catalogQueries->tree(includeInactive: false) as $node) { + if ($node->workTypes !== []) { + $groups[$node->serviceUnit->name] = $node->workTypes; + } + + foreach ($node->services as $serviceNode) { + if ($serviceNode->workTypes !== []) { + $groups[$node->serviceUnit->name.' – '.$serviceNode->service->name] = $serviceNode->workTypes; + } + } + } + + foreach ($groups as $workTypes) { + foreach ($workTypes as $workType) { + $listed[] = $workType->id; + } + } + + if ($this->storedWorkTypeId !== null && ! in_array($this->storedWorkTypeId, $listed, true)) { + $stored = $catalogQueries->findWorkType($this->storedWorkTypeId); + + if ($stored !== null) { + $groups[__('catalog.inactive')] = [$stored]; + } + } + + return $groups; + } + + public function save(AddProduct $addProduct, UpdateProduct $updateProduct): void + { + $this->authorize('catalog.manage'); + + $input = $this->form->toInput(); + + try { + if ($this->productId === null) { + $addProduct->execute($input); + session()->flash('status', __('catalog.status.created', ['name' => trim($input->name)])); + } else { + $updateProduct->execute($this->productId, $input); + session()->flash('status', __('catalog.status.updated', ['name' => trim($input->name)])); + } + } catch (ProductNotFound) { + abort(404); + } catch (DomainException $exception) { + $this->form->showDomainError($exception); + + return; + } + + $this->redirectRoute('catalog.prices', navigate: true); + } + + public function heading(): string + { + return __($this->productId === null ? 'catalog.products.create_title' : 'catalog.products.edit_title'); + } + + public function render(): mixed + { + return $this->view()->title($this->heading()); + } +}; +?> + +
+

{{ $this->heading() }}

+ +
+ + + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + @foreach (ProductUnit::cases() as $unit) + + @endforeach + + + + +
+ +

{{ __('catalog.products.consumer_help') }}

+
+ +
+ {{ __('catalog.products.auto_booking') }} + + + + + + @foreach ($this->workTypeGroups as $groupName => $workTypes) + + @foreach ($workTypes as $workType) + + @endforeach + + @endforeach + +
+ +
+ + +
+ +
diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡work-type-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡work-type-form.blade.php index d9bcb95..1a22560 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡work-type-form.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡work-type-form.blade.php @@ -1,12 +1,14 @@ authorize('catalog.manage'); @@ -40,6 +42,9 @@ new class extends Component $this->form->name = $summary->name; $this->form->service_id = $summary->serviceId === null ? '' : (string) $summary->serviceId; $serviceUnit = $summary->serviceUnitId; + + $rateCents = $priceList->hourlyRateCentsOf($summary->id); + $this->form->hourly_rate = $rateCents === null ? '' : Money::fromCents($rateCents)->inputValue(); } $unit = $serviceUnit === null ? null : $catalogQueries->findServiceUnit($serviceUnit); @@ -68,10 +73,10 @@ new class extends Component try { if ($this->workTypeId === null) { - $addWorkType->execute((int) $this->serviceUnitId, $serviceId, $name); + $addWorkType->execute((int) $this->serviceUnitId, $serviceId, $name, $this->form->hourly_rate); session()->flash('status', __('catalog.status.created', ['name' => trim($name)])); } else { - $updateWorkType->execute($this->workTypeId, $serviceId, $name); + $updateWorkType->execute($this->workTypeId, $serviceId, $name, $this->form->hourly_rate); session()->flash('status', __('catalog.status.updated', ['name' => trim($name)])); } } catch (CatalogItemNotFound) { @@ -127,6 +132,14 @@ new class extends Component @endif + +
diff --git a/app/Modules/Catalog/Presentation/Routes/web.php b/app/Modules/Catalog/Presentation/Routes/web.php index 8d2b31b..a72dc4d 100644 --- a/app/Modules/Catalog/Presentation/Routes/web.php +++ b/app/Modules/Catalog/Presentation/Routes/web.php @@ -26,4 +26,10 @@ Route::middleware(['web', 'auth', 'can:catalog.manage']) Route::livewire('/work-types/{workType}/edit', 'catalog::work-type-form') ->whereNumber('workType') ->name('work-types.edit'); + + Route::livewire('/prices', 'catalog::prices')->name('prices'); + Route::livewire('/products/create', 'catalog::product-form')->name('products.create'); + Route::livewire('/products/{product}/edit', 'catalog::product-form') + ->whereNumber('product') + ->name('products.edit'); }); diff --git a/app/Modules/Shared/Application/Contracts/Settings.php b/app/Modules/Shared/Application/Contracts/Settings.php new file mode 100644 index 0000000..05ba591 --- /dev/null +++ b/app/Modules/Shared/Application/Contracts/Settings.php @@ -0,0 +1,19 @@ + self::MAX_CENTS) { + throw new InvalidMoneyAmount; + } + + $this->cents = $cents; + } + + public static function fromCents(int $cents): self + { + return new self($cents); + } + + /** + * Parses "85", "85,50", "85.5", "1 200,00" or "85 €"; null for an empty value. + * + * @throws InvalidMoneyAmount + */ + public static function parse(string $value): ?self + { + $value = preg_replace('/[\s\x{00A0}\x{202F}€]+/u', '', $value) ?? ''; + $value = str_replace(',', '.', $value); + + if ($value === '') { + return null; + } + + if (preg_match('/^(\d{1,9})(?:\.(\d{1,2}))?$/', $value, $matches) !== 1) { + throw new InvalidMoneyAmount; + } + + $fraction = str_pad($matches[2] ?? '', 2, '0'); + + return new self((int) $matches[1] * 100 + (int) $fraction); + } + + /** + * Finnish notation with the currency, e.g. "1 200,50 €". + */ + public function format(): string + { + return $this->amount(self::NO_BREAK_SPACE).self::NO_BREAK_SPACE.'€'; + } + + /** + * The amount for an input field, e.g. "1200,50". + */ + public function inputValue(): string + { + return $this->amount(''); + } + + private function amount(string $thousandsSeparator): string + { + return number_format($this->cents / 100, 2, ',', $thousandsSeparator); + } +} diff --git a/app/Modules/Shared/Infrastructure/Persistence/DatabaseSettings.php b/app/Modules/Shared/Infrastructure/Persistence/DatabaseSettings.php new file mode 100644 index 0000000..6c871bd --- /dev/null +++ b/app/Modules/Shared/Infrastructure/Persistence/DatabaseSettings.php @@ -0,0 +1,36 @@ +where('key', $key)->value('value'); + + return $value === null ? null : (string) $value; + } + + public function put(string $key, ?string $value): void + { + if ($value === null) { + DB::table('settings')->where('key', $key)->delete(); + + return; + } + + $now = now(); + + DB::table('settings')->upsert( + [['key' => $key, 'value' => $value, 'created_at' => $now, 'updated_at' => $now]], + ['key'], + ['value', 'updated_at'], + ); + } +} diff --git a/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php b/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php index 4a91163..fbfa643 100644 --- a/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php +++ b/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php @@ -3,8 +3,10 @@ namespace App\Modules\Shared\Infrastructure\Providers; use App\Modules\Shared\Application\Contracts\EventDispatcher; +use App\Modules\Shared\Application\Contracts\Settings; use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Shared\Infrastructure\Events\LaravelEventDispatcher; +use App\Modules\Shared\Infrastructure\Persistence\DatabaseSettings; use App\Modules\Shared\Infrastructure\Persistence\LaravelTransactionManager; use App\Modules\Shared\Presentation\Http\Middleware\SetSecurityHeaders; use Illuminate\Contracts\Http\Kernel; @@ -18,6 +20,7 @@ class SharedServiceProvider extends ServiceProvider public array $bindings = [ TransactionManager::class => LaravelTransactionManager::class, EventDispatcher::class => LaravelEventDispatcher::class, + Settings::class => DatabaseSettings::class, ]; public function boot(): void diff --git a/database/factories/ProductFactory.php b/database/factories/ProductFactory.php new file mode 100644 index 0000000..b5c731f --- /dev/null +++ b/database/factories/ProductFactory.php @@ -0,0 +1,51 @@ + + */ +class ProductFactory extends Factory +{ + protected $model = ProductModel::class; + + /** + * @return array + */ + public function definition(): array + { + return [ + 'name' => fake()->unique()->words(2, true), + 'unit' => ProductUnit::Piece->value, + 'price_cents' => fake()->numberBetween(100, 10000), + 'is_consumer_product' => false, + 'auto_hours' => 0, + 'work_type_id' => null, + 'is_active' => true, + 'sort_order' => fake()->unique()->numberBetween(100, 100000), + ]; + } + + public function consumer(): static + { + return $this->state(fn (): array => ['is_consumer_product' => true]); + } + + public function inactive(): static + { + return $this->state(fn (): array => ['is_active' => false]); + } + + public function withAutoHours(float $hours = 0.25): static + { + return $this->state(fn (): array => [ + 'auto_hours' => $hours, + 'work_type_id' => WorkTypeModel::factory(), + ]); + } +} diff --git a/database/migrations/2026_11_24_051626_add_hourly_rate_to_work_types_table.php b/database/migrations/2026_11_24_051626_add_hourly_rate_to_work_types_table.php new file mode 100644 index 0000000..a839f34 --- /dev/null +++ b/database/migrations/2026_11_24_051626_add_hourly_rate_to_work_types_table.php @@ -0,0 +1,25 @@ +unsignedInteger('hourly_rate_cents')->nullable()->after('name'); + }); + } + + public function down(): void + { + Schema::table('work_types', function (Blueprint $table) { + $table->dropColumn('hourly_rate_cents'); + }); + } +}; diff --git a/database/migrations/2026_11_24_051627_create_products_table.php b/database/migrations/2026_11_24_051627_create_products_table.php new file mode 100644 index 0000000..3f0997f --- /dev/null +++ b/database/migrations/2026_11_24_051627_create_products_table.php @@ -0,0 +1,35 @@ +id(); + $table->string('name', 100); + $table->string('unit', 20); + $table->unsignedInteger('price_cents'); + $table->boolean('is_consumer_product')->default(false); + $table->decimal('auto_hours', 6, 2)->default(0); + $table->foreignId('work_type_id')->nullable()->constrained()->restrictOnDelete(); + $table->boolean('is_active')->default(true); + $table->unsignedInteger('sort_order'); + $table->timestamps(); + + $table->index('sort_order'); + }); + } + + public function down(): void + { + Schema::dropIfExists('products'); + } +}; diff --git a/database/migrations/2026_11_24_051628_create_settings_table.php b/database/migrations/2026_11_24_051628_create_settings_table.php new file mode 100644 index 0000000..74bf3f8 --- /dev/null +++ b/database/migrations/2026_11_24_051628_create_settings_table.php @@ -0,0 +1,26 @@ +id(); + $table->string('key', 100)->unique(); + $table->text('value')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('settings'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index a99f334..c5af9f4 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -288,9 +288,10 @@ Hierarkiaa muokataan pohjatietojen hallinnasta. ### 11.2 Hinnat - **Tuntihinnasto**: tuntihinta on työtehtäväkohtainen (esim. ohjelmointityö 85 €/h, vaativa 110 €/h). Ei asiakas- eikä tekijäkohtaisia hintoja. -- **Tuotteet**: kiinteähintaiset kappaletuotteet (passikuvat, tulosteet); hinta, yksikkö, kuluttajatuote-merkintä (näkyy kaikille) ja automaattisen tuntikirjauksen kesto. -- **Km-hinta**. -- Kaikki hinnat verottomina. +- **Tuotteet**: kiinteähintaiset kappaletuotteet (passikuvat, tulosteet); hinta, yksikkö, kuluttajatuote-merkintä (näkyy kaikille) ja automaattisen tuntikirjauksen kesto. Yksikkö valitaan listasta: kpl, sivu, m², m, h, paketti. Jos kesto on annettu (0,25 h tarkkuudella, enintään 24 h), tuotteelle valitaan työtehtävä, jolle tunnit kirjataan. Tuotteita ei poisteta, vaan ne poistetaan käytöstä. +- **Km-hinta** (asetus). +- Kaikki hinnat verottomina, enintään kaksi desimaalia. +- Hinnoilla ei ole historiaa: laskuaineiston rivi tallentaa yksikköhinnan muodostushetkellä, joten hinnan muutos koskee vain myöhempiä aineistoja ja myyntejä. ## 12. Laskuaineisto *(K48–K51)* @@ -325,10 +326,10 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up **Catalog** (palveluyksiköt ja hinnasto) - `service_units`: `name`, `is_shared` (kaikille yhteiset), `is_active`, `sort_order` *(olemassa)* - `services`: `service_unit_id`, `name`, `is_active`, `sort_order` *(olemassa)* -- `work_types`: `service_unit_id`, `service_id` (nullable), `name`, `is_active`, `sort_order` *(olemassa)*, `hourly_rate_cents` *(V2)* +- `work_types`: `service_unit_id`, `service_id` (nullable), `name`, `is_active`, `sort_order` *(olemassa)*, `hourly_rate_cents` (nullable) *(V2, olemassa)* - Nimi on yksilöllinen saman tason sisällä (kirjainkoosta riippumatta). Rivejä ei poisteta, vaan ne poistetaan käytöstä; viiteavaimet estävät poiston. -- `products` *(V2)*: `name`, `unit`, `price_cents`, `is_consumer_product`, `auto_hours`, `work_type_id`, `is_active` -- `settings` *(V2)*: `key`, `value` (esim. km-hinta, työajanseuranta päällä) +- `products` *(V2, olemassa)*: `name`, `unit` (`piece`/`page`/`square_metre`/`metre`/`hour`/`package`), `price_cents`, `is_consumer_product`, `auto_hours`, `work_type_id` (nullable, pakollinen jos `auto_hours` > 0), `is_active`, `sort_order` +- `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, työajanseuranta päällä) **Jobs** (asiakastyöt) - `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by` *(olemassa)*; `quoted_amount_cents`, `completed_at` *(V2)* @@ -434,7 +435,13 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t - Kirjauksen voi lisätä myös tehtävän sivulta (pvm + kesto + selite). - Valmiin työn tehtäville ei voi kirjata eikä niiden kirjauksia muuttaa. -## 17. Avoimet kysymykset +## 17. Vaiheen 2 tarkka sisältö + +### 17.1 Hinnasto ja tuotteet *(valmis)* +- Pääkäyttäjä ja johto hallitsevat Hinnasto-sivua (`/catalog/prices`, valikossa Hinnasto): tuntihinnat työtehtävittäin palveluyksiköiden mukaan ryhmiteltynä (kenttä tallentuu, kun siitä siirrytään pois; tyhjä poistaa hinnan), tuotteet (lisäys, muokkaus, järjestys, käytöstä poisto) ja km-hinta. Tuntihinnan voi asettaa myös työtehtävän lomakkeella Pohjatiedoissa. +- Muut eivät vielä näe hintoja; henkilökohtaiset rahaoikeudet ja työntekijöiden hinnastonäkymä tehdään seuraavaksi (2.3). + +## 18. Avoimet kysymykset 1. **Lukitus**: voiko johto avata valmiin työn tunti- ja kululukituksen, jos jotain unohtui? (Ehdotus: kyllä, ja avaus kirjataan muutoshistoriaan.) 2. **Alihankkijayritys**: onko yrityksellä useita käyttäjätunnuksia, ja tarvitaanko yritys omana tietonaan (nimi, Y-tunnus)? diff --git a/lang/fi/catalog.php b/lang/fi/catalog.php index 689dfa4..1151721 100644 --- a/lang/fi/catalog.php +++ b/lang/fi/catalog.php @@ -9,6 +9,9 @@ return [ 'no_work_types' => 'Ei työtehtäviä.', 'save' => 'Tallenna', 'cancel' => 'Peruuta', + 'yes' => 'Kyllä', + 'no' => 'Ei', + 'prices_link' => 'Hinnasto: tuntihinnat, tuotteet ja km-hinta', 'actions' => [ 'edit' => 'Muokkaa', @@ -52,6 +55,64 @@ return [ 'service' => 'Palvelu', 'service_description' => 'Työtehtävä voi kuulua palveluun tai suoraan palveluyksikköön.', 'no_service' => 'Ei palvelua (suoraan palveluyksikön alla)', + 'hourly_rate' => 'Tuntihinta (€/h, ALV 0)', + 'hourly_rate_help' => 'Esim. 85 tai 85,50. Jätä tyhjäksi, jos työtehtävällä ei ole hintaa.', + ], + + 'prices' => [ + 'title' => 'Hinnasto', + 'intro' => 'Kaikki hinnat ovat verottomia (ALV 0). Hinnan muutos koskee laskuaineistoja ja myyntejä, jotka tehdään muutoksen jälkeen; jo muodostetut aineistot säilyttävät hintansa.', + 'hourly_rates' => 'Tuntihinnat', + 'hourly_rates_help' => 'Tuntihinta on työtehtäväkohtainen. Hinta tallentuu, kun siirryt pois kentästä. Tyhjä kenttä poistaa hinnan.', + 'work_type' => 'Työtehtävä', + 'hourly_rate' => 'Tuntihinta (€/h)', + 'rate_label' => 'Tuntihinta €/h: :name, :unit', + 'rate_saved' => ':name: tuntihinta :rate tallennettu.', + 'rate_removed' => ':name: tuntihinta poistettu.', + ], + + 'products' => [ + 'title' => 'Tuotteet', + 'help' => 'Kiinteähintaiset kappaletuotteet, esim. passikuvat ja tulosteet. Kuluttajatuotteiden hinnat näkyvät kaikille käyttäjille.', + 'none' => 'Ei tuotteita.', + 'add' => 'Lisää tuote', + 'create_title' => 'Uusi tuote', + 'edit_title' => 'Muokkaa tuotetta', + 'unit' => 'Yksikkö', + 'price' => 'Hinta (€ / yksikkö, ALV 0)', + 'price_help' => 'Esim. 12 tai 12,50.', + 'price_column' => 'Hinta (ALV 0)', + 'consumer' => 'Kuluttajatuote', + 'consumer_help' => 'Kuluttajatuotteen hinta näkyy kaikille käyttäjille, myös niille, joilla ei ole oikeutta muihin hintoihin.', + 'consumer_column' => 'Kuluttajatuote', + 'auto_booking' => 'Automaattinen tuntikirjaus', + 'duration' => 'Kesto (h)', + 'duration_help' => 'Myyjälle kirjattava aika tunteina 0,25 h tarkkuudella, esim. 0,25. Jätä tyhjäksi, jos tunteja ei kirjata.', + 'duration_column' => 'Tuntikirjaus', + 'duration_value' => ':hours h', + 'no_duration' => 'Ei', + 'work_type' => 'Työtehtävä', + 'work_type_help' => 'Työtehtävä, jolle kesto kirjataan. Pakollinen, jos kesto on annettu.', + 'no_work_type' => 'Ei työtehtävää', + 'actions' => 'Toiminnot', + 'deactivated' => ':name poistettu käytöstä. Sitä ei voi enää myydä.', + ], + + 'units' => [ + 'piece' => 'kpl', + 'page' => 'sivu', + 'square_metre' => 'm²', + 'metre' => 'm', + 'hour' => 'h', + 'package' => 'paketti', + ], + + 'mileage' => [ + 'title' => 'Km-hinta', + 'rate' => 'Km-hinta (€/km, ALV 0)', + 'help' => 'Kilometrikulujen hinta, esim. 0,59. Tyhjä kenttä poistaa hinnan.', + 'saved' => 'Km-hinta :rate tallennettu.', + 'removed' => 'Km-hinta poistettu.', ], 'fields' => [ @@ -65,5 +126,12 @@ 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_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.', + 'product_name_taken' => 'Tämänniminen tuote on jo olemassa.', + 'invalid_duration' => 'Anna kesto tunteina 0,25 h tarkkuudella, enintään 24 h (esim. 0,25 tai 1,5).', + 'work_type_required' => 'Valitse työtehtävä, jolle kesto kirjataan.', + 'work_type_unavailable' => 'Valittu työtehtävä ei ole käytössä. Valitse toinen.', ], ]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index efcd3d4..9e6db1b 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -11,6 +11,7 @@ return [ 'customers' => 'Asiakkaat', 'users' => 'Käyttäjät', 'catalog' => 'Pohjatiedot', + 'prices' => 'Hinnasto', 'signed_in_as' => 'Kirjautuneena: :name', 'logout' => 'Kirjaudu ulos', 'theme_toggle' => 'Tumma teema', diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 2b672f1..5ac7d65 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -70,7 +70,9 @@ @endcan @can('catalog.manage') - @include('partials.nav-item', ['route' => 'catalog.index', 'pattern' => 'catalog.*', 'label' => __('layout.catalog')]) + @include('partials.nav-item', ['route' => 'catalog.index', 'pattern' => ['catalog.index', 'catalog.service-units.*', 'catalog.services.*', 'catalog.work-types.*'], 'label' => __('layout.catalog')]) + + @include('partials.nav-item', ['route' => 'catalog.prices', 'pattern' => ['catalog.prices', 'catalog.products.*'], 'label' => __('layout.prices')]) @endcan @can('users.manage') diff --git a/tests/Browser/CatalogAccessibilityTest.php b/tests/Browser/CatalogAccessibilityTest.php index 8b51180..d9bbad4 100644 --- a/tests/Browser/CatalogAccessibilityTest.php +++ b/tests/Browser/CatalogAccessibilityTest.php @@ -1,6 +1,7 @@ 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); +}); diff --git a/tests/Fakes/FakeSettings.php b/tests/Fakes/FakeSettings.php new file mode 100644 index 0000000..9704150 --- /dev/null +++ b/tests/Fakes/FakeSettings.php @@ -0,0 +1,27 @@ + */ + 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; + } +} diff --git a/tests/Fakes/InMemoryProductRepository.php b/tests/Fakes/InMemoryProductRepository.php new file mode 100644 index 0000000..c5e0700 --- /dev/null +++ b/tests/Fakes/InMemoryProductRepository.php @@ -0,0 +1,67 @@ + */ + 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; + } +} diff --git a/tests/Fakes/InMemoryWorkTypeRepository.php b/tests/Fakes/InMemoryWorkTypeRepository.php index d78038a..569364f 100644 --- a/tests/Fakes/InMemoryWorkTypeRepository.php +++ b/tests/Fakes/InMemoryWorkTypeRepository.php @@ -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]; } diff --git a/tests/Feature/Modules/Catalog/PriceListTest.php b/tests/Feature/Modules/Catalog/PriceListTest.php new file mode 100644 index 0000000..857d6d4 --- /dev/null +++ b/tests/Feature/Modules/Catalog/PriceListTest.php @@ -0,0 +1,180 @@ +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']); +}); diff --git a/tests/Unit/Modules/Catalog/Application/CatalogUseCasesTest.php b/tests/Unit/Modules/Catalog/Application/CatalogUseCasesTest.php index 70f3a57..ddf1d3e 100644 --- a/tests/Unit/Modules/Catalog/Application/CatalogUseCasesTest.php +++ b/tests/Unit/Modules/Catalog/Application/CatalogUseCasesTest.php @@ -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) diff --git a/tests/Unit/Modules/Catalog/Application/PriceListUseCasesTest.php b/tests/Unit/Modules/Catalog/Application/PriceListUseCasesTest.php new file mode 100644 index 0000000..a10eda0 --- /dev/null +++ b/tests/Unit/Modules/Catalog/Application/PriceListUseCasesTest.php @@ -0,0 +1,126 @@ +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(); +}); diff --git a/tests/Unit/Modules/Shared/MoneyTest.php b/tests/Unit/Modules/Shared/MoneyTest.php new file mode 100644 index 0000000..0999676 --- /dev/null +++ b/tests/Unit/Modules/Shared/MoneyTest.php @@ -0,0 +1,30 @@ +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'); +});