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
@@ -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');
});