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
+2 -1
View File
@@ -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: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) and `TimeTracking` (hours on tasks: weekly sheet and task booking page)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) 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/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>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.
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\Contracts;
use App\Modules\Catalog\Application\DTOs\HourlyRateGroup;
use App\Modules\Catalog\Application\DTOs\ProductSummary;
/**
* Read side of the price list: hourly rates, products and the mileage rate.
* Money lives here and not in CatalogQueries, so that the visibility of
* prices is decided in one place.
*/
interface PriceListQueries
{
/**
* Work types with their hourly rates, grouped by service unit; the
* shared unit comes last.
*
* @return list<HourlyRateGroup>
*/
public function hourlyRates(bool $includeInactive = true): array;
public function hourlyRateCentsOf(int $workTypeId): ?int;
/**
* @return list<ProductSummary>
*/
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;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* The work types of one service unit with their hourly rates, in catalog order.
*/
final readonly class HourlyRateGroup
{
/**
* @param list<HourlyRateRow> $rows
*/
public function __construct(
public int $serviceUnitId,
public string $serviceUnitName,
public bool $isActive,
public array $rows,
) {}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A work type and its hourly rate in cents (VAT 0), null when not priced.
*/
final readonly class HourlyRateRow
{
public function __construct(
public int $workTypeId,
public string $name,
public ?string $serviceName,
public bool $isActive,
public ?int $hourlyRateCents,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
/**
* A product's fields as the user typed them: price "12,50", duration "0,25".
*/
final readonly class ProductInput
{
public function __construct(
public string $name,
public ProductUnit $unit,
public string $price,
public bool $isConsumerProduct,
public string $duration = '',
public ?int $workTypeId = null,
) {}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
/**
* A product with its price in cents (VAT 0) and the hours its sale books.
*/
final readonly class ProductSummary
{
public function __construct(
public int $id,
public string $name,
public ProductUnit $unit,
public int $priceCents,
public bool $isConsumerProduct,
public int $durationQuarters,
public ?int $workTypeId,
public ?string $workTypeName,
public bool $isActive,
) {}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Application\DTOs\ProductInput;
use App\Modules\Catalog\Domain\Contracts\ProductRepository;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Entities\Product;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
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\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
/**
* Adds a product last in the product list.
*/
final class AddProduct
{
public function __construct(
private ProductRepository $products,
private WorkTypeRepository $workTypes,
private TransactionManager $transactions,
) {}
/**
* @return int The new product's id.
*
* @throws CatalogItemNotFound
* @throws InvalidCatalogName
* @throws InvalidMoneyAmount
* @throws InvalidProductDuration
* @throws ProductNameTaken
* @throws ProductNeedsWorkType
*/
public function execute(ProductInput $input): int
{
$fields = ProductFields::from($input);
return $this->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();
});
}
}
@@ -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();
});
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\ProductRepository;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\Exceptions\ProductNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Moves a product one place up or down in the product list.
*/
final class MoveProduct
{
public function __construct(
private ProductRepository $products,
private TransactionManager $transactions,
) {}
/**
* @return bool False when the product already was first (up) or last (down).
*
* @throws ProductNotFound
*/
public function execute(int $productId, MoveDirection $direction): bool
{
return $this->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;
});
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Application\DTOs\ProductInput;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
/**
* A product's input parsed into value objects, shared by AddProduct and UpdateProduct.
*
* @internal
*/
final readonly class ProductFields
{
private function __construct(
public CatalogName $name,
public ProductUnit $unit,
public Money $price,
public bool $isConsumerProduct,
public ProductDuration $duration,
public ?int $workTypeId,
) {}
/**
* @throws InvalidCatalogName
* @throws InvalidMoneyAmount
* @throws InvalidProductDuration
*/
public static function from(ProductInput $input): self
{
return new self(
new CatalogName($input->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);
}
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
/**
* Sets a work type's hourly rate (VAT 0); an empty value removes it. The
* rate applies to billing exports made after the change.
*/
final class SetHourlyRate
{
public function __construct(
private WorkTypeRepository $workTypes,
private TransactionManager $transactions,
) {}
/**
* @return Money|null The stored rate.
*
* @throws CatalogItemNotFound
* @throws InvalidMoneyAmount
*/
public function execute(int $workTypeId, string $hourlyRate): ?Money
{
$rate = Money::parse($hourlyRate);
$this->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;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Shared\Application\Contracts\Settings;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
/**
* Sets the price of a driven kilometre (VAT 0); an empty value removes it.
*/
final class SetMileageRate
{
public const string SETTING_KEY = 'catalog.mileage_rate_cents';
public function __construct(private Settings $settings) {}
/**
* @return Money|null The stored rate.
*
* @throws InvalidMoneyAmount
*/
public function execute(string $mileageRate): ?Money
{
$rate = Money::parse($mileageRate);
$this->settings->put(self::SETTING_KEY, $rate === null ? null : (string) $rate->cents);
return $rate;
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\ProductRepository;
use App\Modules\Catalog\Domain\Exceptions\ProductNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes a product out of sale or back into sale. Products are never
* deleted, so old sales that refer to them keep working.
*/
final class SetProductActive
{
public function __construct(
private ProductRepository $products,
private TransactionManager $transactions,
) {}
/**
* @throws ProductNotFound
*/
public function execute(int $productId, bool $active): void
{
$this->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);
});
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Application\DTOs\ProductInput;
use App\Modules\Catalog\Domain\Contracts\ProductRepository;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration;
use App\Modules\Catalog\Domain\Exceptions\ProductNameTaken;
use App\Modules\Catalog\Domain\Exceptions\ProductNeedsWorkType;
use App\Modules\Catalog\Domain\Exceptions\ProductNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
/**
* Changes a product's fields. A price change applies to sales and billing
* exports made after it.
*/
final class UpdateProduct
{
public function __construct(
private ProductRepository $products,
private WorkTypeRepository $workTypes,
private TransactionManager $transactions,
) {}
/**
* @throws CatalogItemNotFound
* @throws InvalidCatalogName
* @throws InvalidMoneyAmount
* @throws InvalidProductDuration
* @throws ProductNameTaken
* @throws ProductNeedsWorkType
* @throws ProductNotFound
*/
public function execute(int $productId, ProductInput $input): void
{
$fields = ProductFields::from($input);
$this->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);
});
}
}
@@ -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);
});
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Contracts;
use App\Modules\Catalog\Domain\Entities\Product;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
interface ProductRepository
{
public function findById(int $id): ?Product;
/**
* Inserts a new product or updates a stored one, and returns the stored product.
*/
public function save(Product $product): Product;
/**
* Whether a product other than $exceptId has this name, ignoring case.
*/
public function isNameTaken(string $name, ?int $exceptId = null): bool;
/**
* The sort order that puts a new product last.
*/
public function nextSortOrder(): int;
/**
* The product just before or after this one, or null at either end.
*/
public function neighbour(Product $product, MoveDirection $direction): ?Product;
}
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
use App\Modules\Catalog\Domain\Exceptions\ProductNeedsWorkType;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
use App\Modules\Shared\Domain\ValueObjects\Money;
/**
* A fixed-price product (passikuvat, tulosteet). Consumer products' prices
* are visible to every user. Selling a product with a duration books those
* hours for the seller on the product's work type.
*/
final class Product extends CatalogItem
{
private function __construct(
?int $id,
CatalogName $name,
private ProductUnit $unit,
private Money $price,
private bool $consumerProduct,
private ProductDuration $duration,
private ?int $workTypeId,
bool $active,
int $sortOrder,
) {
parent::__construct($id, $name, $active, $sortOrder);
}
/**
* @throws ProductNeedsWorkType
*/
public static function create(CatalogName $name, ProductUnit $unit, Money $price, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId, int $sortOrder): self
{
self::ensureWorkTypeForDuration($duration, $workTypeId);
return new self(null, $name, $unit, $price, $consumerProduct, $duration, $workTypeId, true, $sortOrder);
}
public static function reconstitute(int $id, CatalogName $name, ProductUnit $unit, Money $price, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId, bool $active, int $sortOrder): self
{
return new self($id, $name, $unit, $price, $consumerProduct, $duration, $workTypeId, $active, $sortOrder);
}
/**
* @throws ProductNeedsWorkType
*/
public function update(CatalogName $name, ProductUnit $unit, Money $price, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId): void
{
self::ensureWorkTypeForDuration($duration, $workTypeId);
$this->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;
}
}
}
@@ -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;
}
/**
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Enums;
/**
* Unit in which a product is sold. Finnish labels are in `catalog.units`.
*/
enum ProductUnit: string
{
case Piece = 'piece';
case Page = 'page';
case SquareMetre = 'square_metre';
case Metre = 'metre';
case Hour = 'hour';
case Package = 'package';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidProductDuration extends DomainException
{
public function __construct()
{
parent::__construct('A product duration must be 0–24 hours to the nearest quarter of an hour.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ProductNameTaken extends DomainException
{
public function __construct()
{
parent::__construct('Another product already has this name.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ProductNeedsWorkType extends DomainException
{
public function __construct()
{
parent::__construct('A product with automatic hours needs a work type.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ProductNotFound extends DomainException
{
public function __construct(public readonly int $productId)
{
parent::__construct("Product {$productId} was not found.");
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\ValueObjects;
use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration;
/**
* Hours booked for the seller automatically when a product is sold,
* 0–24 to the nearest quarter of an hour. Zero means no booking.
*/
final readonly class ProductDuration
{
public const int MAX_QUARTERS = 96;
public int $quarters;
public function __construct(int $quarters)
{
if ($quarters < 0 || $quarters > 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'), '.'));
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Database\Factories\ProductFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
*
* @property int $id
* @property string $name
* @property string $unit
* @property int $price_cents
* @property bool $is_consumer_product
* @property string $auto_hours
* @property int|null $work_type_id
* @property bool $is_active
* @property int $sort_order
* @property-read WorkTypeModel|null $workType
*/
#[Table('products')]
#[Fillable(['name', 'unit', 'price_cents', 'is_consumer_product', 'auto_hours', 'work_type_id', 'is_active', 'sort_order'])]
#[UseFactory(ProductFactory::class)]
class ProductModel extends Model
{
/** @use HasFactory<ProductFactory> */
use HasFactory;
/**
* @return BelongsTo<WorkTypeModel, $this>
*/
public function workType(): BelongsTo
{
return $this->belongsTo(WorkTypeModel::class, 'work_type_id');
}
/**
* @return array<string, string>
*/
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',
];
}
}
@@ -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',
];
@@ -0,0 +1,99 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\DTOs\HourlyRateGroup;
use App\Modules\Catalog\Application\DTOs\HourlyRateRow;
use App\Modules\Catalog\Application\DTOs\ProductSummary;
use App\Modules\Catalog\Application\DTOs\ServiceUnitNode;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Shared\Application\Contracts\Settings;
class EloquentPriceListQueries implements PriceListQueries
{
public function __construct(
private CatalogQueries $catalogQueries,
private Settings $settings,
) {}
public function hourlyRates(bool $includeInactive = true): array
{
/** @var array<int, int|null> $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,
);
}
}
@@ -0,0 +1,78 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Domain\Contracts\ProductRepository;
use App\Modules\Catalog\Domain\Entities\Product;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Shared\Domain\ValueObjects\Money;
class EloquentProductRepository implements ProductRepository
{
public function findById(int $id): ?Product
{
$model = ProductModel::query()->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,
);
}
}
@@ -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),
);
}
}
@@ -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));
}
}
@@ -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'),
];
}
}
@@ -0,0 +1,114 @@
<?php
namespace App\Modules\Catalog\Presentation\Livewire\Forms;
use App\Modules\Catalog\Application\DTOs\ProductInput;
use App\Modules\Catalog\Application\DTOs\ProductSummary;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration;
use App\Modules\Catalog\Domain\Exceptions\ProductNameTaken;
use App\Modules\Catalog\Domain\Exceptions\ProductNeedsWorkType;
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use Illuminate\Validation\Rule;
use Livewire\Form;
/**
* Fields of a product. Price and duration are kept as typed ("12,50") and
* parsed by the use case.
*/
class ProductForm extends Form
{
public string $name = '';
public string $unit = 'piece';
public string $price = '';
public bool $is_consumer_product = false;
public string $duration = '';
/**
* '' means no work type.
*/
public string $work_type_id = '';
public function fillFrom(ProductSummary $product): void
{
$this->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<string, array<int, mixed>>
*/
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<string, string>
*/
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'),
];
}
}
@@ -119,7 +119,10 @@ new class extends Component
<x-button :href="route('catalog.service-units.create')" wire:navigate icon="plus" :text="__('catalog.actions.add_service_unit')" />
</div>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.intro') }}</p>
<div class="space-y-1 text-sm">
<p class="text-zinc-600 dark:text-zinc-300">{{ __('catalog.intro') }}</p>
<p><x-link :href="route('catalog.prices')" navigate>{{ __('catalog.prices_link') }}</x-link></p>
</div>
@if (session('status'))
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@@ -0,0 +1,371 @@
<?php
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\DTOs\HourlyRateGroup;
use App\Modules\Catalog\Application\DTOs\HourlyRateRow;
use App\Modules\Catalog\Application\DTOs\ProductSummary;
use App\Modules\Catalog\Application\UseCases\MoveProduct;
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\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\ProductNotFound;
use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Price list (hinnasto): hourly rates of work types, products and the
* mileage rate. All prices are without VAT.
*/
new class extends Component
{
public bool $showInactive = true;
public string $statusMessage = '';
public string $errorMessage = '';
/**
* Hourly rates that were not saved, shown back in their cell with the error.
*
* @var array<int, string>
*/
#[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<HourlyRateGroup>
*/
#[Computed]
public function hourlyRates(): array
{
return $this->priceList->hourlyRates($this->showInactive);
}
/**
* @return list<ProductSummary>
*/
#[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<array{index: string, label: string, sortable: bool, align?: string}>
*/
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;
}
};
?>
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('catalog.prices.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.prices.intro') }}</p>
</div>
@if (session('status'))
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@endif
<x-checkbox id="show-inactive" wire:model.live="showInactive" :label="__('catalog.show_inactive')" />
<div class="space-y-1">
<p role="status" aria-live="polite" class="min-h-5 text-sm">{{ $statusMessage }}</p>
<p role="alert" class="text-sm font-medium text-red-700 dark:text-red-400">{{ $errorMessage }}</p>
</div>
<section aria-labelledby="hourly-rates-heading" class="space-y-4">
<div class="space-y-1">
<h2 id="hourly-rates-heading" class="text-xl font-semibold">{{ __('catalog.prices.hourly_rates') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.prices.hourly_rates_help') }}</p>
</div>
@foreach ($this->hourlyRates as $group)
@if ($group->rows !== [])
{{-- An input grid is a form, so a native table rather than <x-table>. --}}
<table wire:key="rates-{{ $group->serviceUnitId }}" class="w-full border-collapse text-sm">
<caption class="pb-2 text-left text-lg font-medium break-words">
{{ $group->serviceUnitName }}
@unless ($group->isActive)
<span class="ml-2 text-sm font-normal">({{ __('catalog.inactive') }})</span>
@endunless
</caption>
<thead>
<tr class="border-b border-zinc-300 dark:border-zinc-600">
<th scope="col" class="py-2 pr-3 text-left font-semibold">{{ __('catalog.prices.work_type') }}</th>
<th scope="col" class="w-32 py-2 text-left font-semibold">{{ __('catalog.prices.hourly_rate') }}</th>
</tr>
</thead>
<tbody>
@foreach ($group->rows as $row)
<tr wire:key="rate-{{ $row->workTypeId }}" class="border-b border-zinc-200 align-top dark:border-zinc-700">
<th scope="row" class="py-2 pr-3 text-left font-normal break-words">
@if ($row->serviceName !== null)
<span class="text-zinc-600 dark:text-zinc-300">{{ $row->serviceName }}:</span>
@endif
{{ $row->name }}
@unless ($row->isActive)
<span class="ml-1">({{ __('catalog.inactive') }})</span>
@endunless
</th>
<td class="py-2">
<input
id="rate-{{ $row->workTypeId }}"
type="text"
inputmode="decimal"
autocomplete="off"
value="{{ $rejected[$row->workTypeId] ?? $this->inputValue($row->hourlyRateCents) }}"
wire:change="saveRate({{ $row->workTypeId }}, $event.target.value)"
aria-label="{{ __('catalog.prices.rate_label', ['name' => ($row->serviceName !== null ? $row->serviceName.': ' : '').$row->name, 'unit' => $group->serviceUnitName]) }}"
@error('rates.'.$row->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)
<p id="rate-{{ $row->workTypeId }}-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</td>
</tr>
@endforeach
</tbody>
</table>
@endif
@endforeach
</section>
<section aria-labelledby="products-heading" class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="products-heading" class="text-xl font-semibold">{{ __('catalog.products.title') }}</h2>
<x-button :href="route('catalog.products.create')" wire:navigate icon="plus" :text="__('catalog.products.add')" />
</div>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.help') }}</p>
@if ($this->products === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p>
@else
<x-table :headers="$this->productHeaders()" :rows="$this->products">
@interact('column_name', $product)
<span class="font-medium break-words">{{ $product->name }}</span>
@unless ($product->isActive)
<span class="ml-1 text-sm">({{ __('catalog.inactive') }})</span>
@endunless
@endinteract
@interact('column_unit', $product)
{{ __('catalog.units.'.$product->unit->value) }}
@endinteract
@interact('column_price', $product)
<span class="whitespace-nowrap">{{ $this->money($product->priceCents) }}</span>
@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)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $product->workTypeName }}</span>
@endif
@else
{{ __('catalog.products.no_duration') }}
@endif
@endinteract
@interact('column_actions', $product)
<x-catalog.item-actions
level="product"
:id="$product->id"
:name="$product->name"
:active="$product->isActive"
:edit-url="route('catalog.products.edit', $product->id)"
/>
@endinteract
</x-table>
@endif
</section>
<section aria-labelledby="mileage-heading" class="space-y-4">
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.mileage.title') }}</h2>
<form wire:submit="saveMileageRate" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
<div class="min-w-40 flex-1">
<x-input
wire:model="mileageRate"
:label="__('catalog.mileage.rate')"
:hint="__('catalog.mileage.help')"
inputmode="decimal"
autocomplete="off"
/>
</div>
<x-button submit :text="__('catalog.save')" />
</form>
</section>
</div>
@@ -0,0 +1,185 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
use App\Modules\Catalog\Application\UseCases\AddProduct;
use App\Modules\Catalog\Application\UseCases\UpdateProduct;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
use App\Modules\Catalog\Domain\Exceptions\ProductNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\ProductForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (no {product}) and edit page (with {product}) of a product.
*/
new class extends Component
{
#[Locked]
public ?int $productId = null;
/**
* The stored work type, listed even when it is no longer in use.
*/
#[Locked]
public ?int $storedWorkTypeId = null;
public ProductForm $form;
public function mount(PriceListQueries $priceList, ?int $product = null): void
{
$this->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<string, list<WorkTypeSummary>>
*/
#[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());
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model="form.unit" :label="__('catalog.products.unit')" :aria-label="__('catalog.products.unit')">
@foreach (ProductUnit::cases() as $unit)
<option wire:key="unit-{{ $unit->value }}" value="{{ $unit->value }}">{{ __('catalog.units.'.$unit->value) }}</option>
@endforeach
</x-select.native>
<x-input
wire:model="form.price"
:label="__('catalog.products.price')"
:hint="__('catalog.products.price_help')"
inputmode="decimal"
autocomplete="off"
required
/>
<div class="space-y-1">
<x-checkbox id="product-consumer" wire:model="form.is_consumer_product" :label="__('catalog.products.consumer')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.consumer_help') }}</p>
</div>
<fieldset class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
<legend class="px-1 font-medium">{{ __('catalog.products.auto_booking') }}</legend>
<x-input
wire:model="form.duration"
:label="__('catalog.products.duration')"
:hint="__('catalog.products.duration_help')"
inputmode="decimal"
autocomplete="off"
/>
<x-select.native
wire:model="form.work_type_id"
:label="__('catalog.products.work_type')"
:aria-label="__('catalog.products.work_type')"
:hint="__('catalog.products.work_type_help')"
>
<option value="">{{ __('catalog.products.no_work_type') }}</option>
@foreach ($this->workTypeGroups as $groupName => $workTypes)
<optgroup wire:key="work-type-group-{{ $loop->index }}" label="{{ $groupName }}">
@foreach ($workTypes as $workType)
<option wire:key="work-type-option-{{ $workType->id }}" value="{{ $workType->id }}">{{ $workType->name }}</option>
@endforeach
</optgroup>
@endforeach
</x-select.native>
</fieldset>
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('catalog.save')" />
<x-button :href="route('catalog.prices')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
</div>
</form>
</div>
@@ -1,12 +1,14 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\DTOs\ServiceSummary;
use App\Modules\Catalog\Application\UseCases\AddWorkType;
use App\Modules\Catalog\Application\UseCases\UpdateWorkType;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\CatalogItemForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\ValueObjects\Money;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
@@ -27,7 +29,7 @@ new class extends Component
public CatalogItemForm $form;
public function mount(CatalogQueries $catalogQueries, ?int $serviceUnit = null, ?int $workType = null): void
public function mount(CatalogQueries $catalogQueries, PriceListQueries $priceList, ?int $serviceUnit = null, ?int $workType = null): void
{
$this->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
</x-select.native>
@endif
<x-input
wire:model="form.hourly_rate"
:label="__('catalog.work_types.hourly_rate')"
:hint="__('catalog.work_types.hourly_rate_help')"
inputmode="decimal"
autocomplete="off"
/>
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('catalog.save')" />
<x-button :href="route('catalog.index')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
@@ -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');
});
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Application\Contracts;
/**
* Application-wide settings as key–value pairs (e.g. the mileage rate).
* Each key belongs to one module, which prefixes it with its own name.
*/
interface Settings
{
public function get(string $key): ?string;
/**
* Stores a value; null removes the setting.
*/
public function put(string $key, ?string $value): void;
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\Exceptions;
final class InvalidMoneyAmount extends DomainException
{
public function __construct()
{
parent::__construct('An amount must be 0–1 000 000 euros with at most two decimals.');
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\ValueObjects;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
/**
* A price or amount in euros without VAT, stored as whole cents so sums
* stay exact. Never negative.
*/
final readonly class Money
{
public const int MAX_CENTS = 100_000_000;
private const string NO_BREAK_SPACE = "\u{00A0}";
public int $cents;
public function __construct(int $cents)
{
if ($cents < 0 || $cents > 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);
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Modules\Shared\Infrastructure\Persistence;
use App\Modules\Shared\Application\Contracts\Settings;
use Illuminate\Support\Facades\DB;
/**
* Settings in the `settings` table.
*/
class DatabaseSettings implements Settings
{
public function get(string $key): ?string
{
$value = DB::table('settings')->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'],
);
}
}
@@ -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
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace Database\Factories;
use App\Modules\Catalog\Domain\Enums\ProductUnit;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<ProductModel>
*/
class ProductFactory extends Factory
{
protected $model = ProductModel::class;
/**
* @return array<string, mixed>
*/
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(),
]);
}
}
@@ -0,0 +1,25 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Hourly rate of a work type in cents, VAT 0; null when not priced.
*/
public function up(): void
{
Schema::table('work_types', function (Blueprint $table) {
$table->unsignedInteger('hourly_rate_cents')->nullable()->after('name');
});
}
public function down(): void
{
Schema::table('work_types', function (Blueprint $table) {
$table->dropColumn('hourly_rate_cents');
});
}
};
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Fixed-price products (passikuvat, tulosteet). Prices in cents, VAT 0.
* Products are never deleted, only deactivated.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Application-wide settings, e.g. the mileage rate.
*/
public function up(): void
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key', 100)->unique();
$table->text('value')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('settings');
}
};
+14 -7
View File
@@ -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)?
+68
View File
@@ -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.',
],
];
+1
View File
@@ -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',
+3 -1
View File
@@ -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')
+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');
});