Add catalog module for service units, services and work types

Phase 1, item 3: the hierarchy customer jobs, tasks and time entries
will refer to.

- New Catalog module: service unit > optional service > work type.
  Names are unique per level (case-insensitive); items are never
  deleted, only deactivated, and foreign keys restrict deletes.
- Pohjatiedot page (/catalog, admins and management): add, rename,
  reorder with move up/down buttons (keyboard-friendly, focus kept and
  announced) and an "in use" checkbox per row. Work types can move to
  another service of the same unit.
- A migration inserts the starting catalog from the specification when
  the tables are empty, so every installation has it.
- CatalogQueries gives other modules the active service units and the
  work types of chosen units plus the shared ones.
- Spec and CLAUDE.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-23 18:27:58 +02:00
co-authored by Claude Opus 5.5
parent e0b8f4970f
commit 51b2d4a252
62 changed files with 3196 additions and 7 deletions
+2 -2
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` and `Customers`); `/` 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` and `Catalog`: service units, services and work types, managed on the Pohjatiedot 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.
@@ -22,7 +22,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`). 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]`.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`). 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`).
- `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.
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\Contracts;
use App\Modules\Catalog\Application\DTOs\ServiceSummary;
use App\Modules\Catalog\Application\DTOs\ServiceUnitNode;
use App\Modules\Catalog\Application\DTOs\ServiceUnitSummary;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
/**
* Read side of the catalog. Other modules (customer jobs, tasks, time
* entries) use this contract, never the module's Eloquent models.
*/
interface CatalogQueries
{
/**
* The whole hierarchy in order, for the catalog management page.
*
* @return list<ServiceUnitNode>
*/
public function tree(bool $includeInactive = true): array;
/**
* Active service units a customer job can be assigned to (not the shared unit).
*
* @return list<ServiceUnitSummary>
*/
public function activeServiceUnits(): array;
/**
* Active work types of the given service units plus the shared work
* types, grouped by unit and service.
*
* @param list<int> $serviceUnitIds
* @return list<ServiceUnitNode>
*/
public function activeWorkTypesFor(array $serviceUnitIds): array;
public function findServiceUnit(int $id): ?ServiceUnitSummary;
public function findService(int $id): ?ServiceSummary;
public function findWorkType(int $id): ?WorkTypeSummary;
/**
* The services of a unit in order, for choosing a work type's service.
*
* @return list<ServiceSummary>
*/
public function servicesOf(int $serviceUnitId): array;
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A service with its work types, in order.
*/
final readonly class ServiceNode
{
/**
* @param list<WorkTypeSummary> $workTypes
*/
public function __construct(
public ServiceSummary $service,
public array $workTypes,
) {}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
final readonly class ServiceSummary
{
public function __construct(
public int $id,
public int $serviceUnitId,
public string $name,
public bool $isActive,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A service unit with its services and the work types directly under it,
* in order.
*/
final readonly class ServiceUnitNode
{
/**
* @param list<ServiceNode> $services
* @param list<WorkTypeSummary> $workTypes Work types under no service.
*/
public function __construct(
public ServiceUnitSummary $serviceUnit,
public array $services,
public array $workTypes,
) {}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
final readonly class ServiceUnitSummary
{
public function __construct(
public int $id,
public string $name,
public bool $isShared,
public bool $isActive,
) {}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
final readonly class WorkTypeSummary
{
public function __construct(
public int $id,
public int $serviceUnitId,
public ?int $serviceId,
public string $name,
public bool $isActive,
) {}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\ServiceRepository;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Entities\Service;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\CatalogNameTaken;
use App\Modules\Catalog\Domain\Exceptions\SharedUnitHasNoServices;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class AddService
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private ServiceRepository $services,
private TransactionManager $transactions,
) {}
/**
* @return int The new service's id.
*
* @throws CatalogItemNotFound
* @throws CatalogNameTaken
* @throws SharedUnitHasNoServices
*/
public function execute(int $serviceUnitId, string $name): int
{
$name = new CatalogName($name);
return $this->transactions->run(function () use ($serviceUnitId, $name): int {
$serviceUnit = $this->serviceUnits->findById($serviceUnitId)
?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $serviceUnitId);
if ($this->services->isNameTaken($serviceUnitId, $name->value)) {
throw new CatalogNameTaken;
}
$service = Service::create($serviceUnit, $name, $this->services->nextSortOrder($serviceUnitId));
return (int) $this->services->save($service)->id();
});
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Entities\ServiceUnit;
use App\Modules\Catalog\Domain\Exceptions\CatalogNameTaken;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class AddServiceUnit
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private TransactionManager $transactions,
) {}
/**
* @return int The new service unit's id.
*
* @throws CatalogNameTaken
*/
public function execute(string $name): int
{
$name = new CatalogName($name);
return $this->transactions->run(function () use ($name): int {
if ($this->serviceUnits->isNameTaken($name->value)) {
throw new CatalogNameTaken;
}
$serviceUnit = ServiceUnit::create($name, $this->serviceUnits->nextSortOrder());
return (int) $this->serviceUnits->save($serviceUnit)->id();
});
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
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\Domain\Entities\WorkType;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
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;
final class AddWorkType
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private ServiceRepository $services,
private WorkTypeRepository $workTypes,
private TransactionManager $transactions,
) {}
/**
* @return int The new work type's id.
*
* @throws CatalogItemNotFound
* @throws CatalogNameTaken
* @throws ServiceNotInUnit
*/
public function execute(int $serviceUnitId, ?int $serviceId, string $name): int
{
$name = new CatalogName($name);
return $this->transactions->run(function () use ($serviceUnitId, $serviceId, $name): int {
$serviceUnit = $this->serviceUnits->findById($serviceUnitId)
?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $serviceUnitId);
$service = $serviceId === null ? null : ($this->services->findById($serviceId)
?? throw new CatalogItemNotFound(CatalogLevel::Service, $serviceId));
if ($this->workTypes->isNameTaken($serviceUnitId, $serviceId, $name->value)) {
throw new CatalogNameTaken;
}
$workType = WorkType::create($serviceUnit, $service, $name, $this->workTypes->nextSortOrder($serviceUnitId, $serviceId));
return (int) $this->workTypes->save($workType)->id();
});
}
}
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
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\Domain\Entities\Service;
use App\Modules\Catalog\Domain\Entities\ServiceUnit;
use App\Modules\Catalog\Domain\Entities\WorkType;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Moves an item one place up or down among its siblings.
*/
final class MoveCatalogItem
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private ServiceRepository $services,
private WorkTypeRepository $workTypes,
private TransactionManager $transactions,
) {}
/**
* @return bool False when the item already was first (up) or last (down).
*
* @throws CatalogItemNotFound
*/
public function execute(CatalogLevel $level, int $id, MoveDirection $direction): bool
{
return $this->transactions->run(fn (): bool => match ($level) {
CatalogLevel::ServiceUnit => $this->moveServiceUnit($id, $direction),
CatalogLevel::Service => $this->moveService($id, $direction),
CatalogLevel::WorkType => $this->moveWorkType($id, $direction),
});
}
private function moveServiceUnit(int $id, MoveDirection $direction): bool
{
$item = $this->serviceUnits->findById($id) ?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $id);
$neighbour = $this->serviceUnits->neighbour($item, $direction);
return $neighbour !== null && $this->swap($item, $neighbour, fn (ServiceUnit $unit) => $this->serviceUnits->save($unit));
}
private function moveService(int $id, MoveDirection $direction): bool
{
$item = $this->services->findById($id) ?? throw new CatalogItemNotFound(CatalogLevel::Service, $id);
$neighbour = $this->services->neighbour($item, $direction);
return $neighbour !== null && $this->swap($item, $neighbour, fn (Service $service) => $this->services->save($service));
}
private function moveWorkType(int $id, MoveDirection $direction): bool
{
$item = $this->workTypes->findById($id) ?? throw new CatalogItemNotFound(CatalogLevel::WorkType, $id);
$neighbour = $this->workTypes->neighbour($item, $direction);
return $neighbour !== null && $this->swap($item, $neighbour, fn (WorkType $workType) => $this->workTypes->save($workType));
}
/**
* @template T of ServiceUnit|Service|WorkType
*
* @param T $item
* @param T $neighbour
* @param callable(T): mixed $save
*/
private function swap(ServiceUnit|Service|WorkType $item, ServiceUnit|Service|WorkType $neighbour, callable $save): bool
{
$item->swapOrderWith($neighbour);
$save($item);
$save($neighbour);
return true;
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\ServiceRepository;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\CatalogNameTaken;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use InvalidArgumentException;
/**
* Renames a service unit or a service. Work types change with UpdateWorkType,
* which can also move them to another service.
*/
final class RenameCatalogItem
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private ServiceRepository $services,
private TransactionManager $transactions,
) {}
/**
* @throws CatalogItemNotFound
* @throws CatalogNameTaken
*/
public function execute(CatalogLevel $level, int $id, string $name): void
{
$name = new CatalogName($name);
$this->transactions->run(function () use ($level, $id, $name): void {
match ($level) {
CatalogLevel::ServiceUnit => $this->renameServiceUnit($id, $name),
CatalogLevel::Service => $this->renameService($id, $name),
CatalogLevel::WorkType => throw new InvalidArgumentException('Use UpdateWorkType for work types.'),
};
});
}
private function renameServiceUnit(int $id, CatalogName $name): void
{
$serviceUnit = $this->serviceUnits->findById($id) ?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $id);
if ($this->serviceUnits->isNameTaken($name->value, $id)) {
throw new CatalogNameTaken;
}
$serviceUnit->rename($name);
$this->serviceUnits->save($serviceUnit);
}
private function renameService(int $id, CatalogName $name): void
{
$service = $this->services->findById($id) ?? throw new CatalogItemNotFound(CatalogLevel::Service, $id);
if ($this->services->isNameTaken($service->serviceUnitId(), $name->value, $id)) {
throw new CatalogNameTaken;
}
$service->rename($name);
$this->services->save($service);
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
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\Domain\Entities\CatalogItem;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes an item out of use or back into use. Items are never deleted, so
* customer jobs and time entries that refer to them keep working.
*/
final class SetCatalogItemActive
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private ServiceRepository $services,
private WorkTypeRepository $workTypes,
private TransactionManager $transactions,
) {}
/**
* @throws CatalogItemNotFound
*/
public function execute(CatalogLevel $level, int $id, bool $active): void
{
$this->transactions->run(function () use ($level, $id, $active): void {
match ($level) {
CatalogLevel::ServiceUnit => $this->serviceUnits->save($this->toggled($this->serviceUnits->findById($id), $level, $id, $active)),
CatalogLevel::Service => $this->services->save($this->toggled($this->services->findById($id), $level, $id, $active)),
CatalogLevel::WorkType => $this->workTypes->save($this->toggled($this->workTypes->findById($id), $level, $id, $active)),
};
});
}
/**
* @template T of CatalogItem
*
* @param T|null $item
* @return T
*/
private function toggled(?CatalogItem $item, CatalogLevel $level, int $id, bool $active): CatalogItem
{
if ($item === null) {
throw new CatalogItemNotFound($level, $id);
}
$active ? $item->activate() : $item->deactivate();
return $item;
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
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\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
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;
/**
* Renames a work type and moves it under another service of its unit (or
* under no service).
*/
final class UpdateWorkType
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private ServiceRepository $services,
private WorkTypeRepository $workTypes,
private TransactionManager $transactions,
) {}
/**
* @throws CatalogItemNotFound
* @throws CatalogNameTaken
* @throws ServiceNotInUnit
*/
public function execute(int $workTypeId, ?int $serviceId, string $name): void
{
$name = new CatalogName($name);
$this->transactions->run(function () use ($workTypeId, $serviceId, $name): void {
$workType = $this->workTypes->findById($workTypeId)
?? throw new CatalogItemNotFound(CatalogLevel::WorkType, $workTypeId);
if ($this->workTypes->isNameTaken($workType->serviceUnitId(), $serviceId, $name->value, $workTypeId)) {
throw new CatalogNameTaken;
}
if ($serviceId !== $workType->serviceId()) {
$serviceUnit = $this->serviceUnits->findById($workType->serviceUnitId())
?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $workType->serviceUnitId());
$service = $serviceId === null ? null : ($this->services->findById($serviceId)
?? throw new CatalogItemNotFound(CatalogLevel::Service, $serviceId));
$workType->moveToService($serviceUnit, $service, $this->workTypes->nextSortOrder($workType->serviceUnitId(), $serviceId));
}
$workType->rename($name);
$this->workTypes->save($workType);
});
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Contracts;
use App\Modules\Catalog\Domain\Entities\Service;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
/**
* Siblings are the services of one unit.
*/
interface ServiceRepository
{
public function findById(int $id): ?Service;
/**
* Inserts a new item or updates a stored one, and returns the stored item.
*/
public function save(Service $service): Service;
/**
* Whether a sibling other than $exceptId has this name, ignoring case.
*/
public function isNameTaken(int $serviceUnitId, string $name, ?int $exceptId = null): bool;
/**
* The sort order that puts a new item last among its siblings.
*/
public function nextSortOrder(int $serviceUnitId): int;
/**
* The sibling just before or after the item, or null at either end.
*/
public function neighbour(Service $service, MoveDirection $direction): ?Service;
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Contracts;
use App\Modules\Catalog\Domain\Entities\ServiceUnit;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
/**
* Siblings are all service units.
*/
interface ServiceUnitRepository
{
public function findById(int $id): ?ServiceUnit;
/**
* Inserts a new item or updates a stored one, and returns the stored item.
*/
public function save(ServiceUnit $serviceUnit): ServiceUnit;
/**
* Whether a sibling other than $exceptId has this name, ignoring case.
*/
public function isNameTaken(string $name, ?int $exceptId = null): bool;
/**
* The sort order that puts a new item last among its siblings.
*/
public function nextSortOrder(): int;
/**
* The sibling just before or after the item, or null at either end.
*/
public function neighbour(ServiceUnit $serviceUnit, MoveDirection $direction): ?ServiceUnit;
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Contracts;
use App\Modules\Catalog\Domain\Entities\WorkType;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
/**
* Siblings are the work types under one service, or directly under the unit when $serviceId is null.
*/
interface WorkTypeRepository
{
public function findById(int $id): ?WorkType;
/**
* Inserts a new item or updates a stored one, and returns the stored item.
*/
public function save(WorkType $workType): WorkType;
/**
* Whether a sibling other than $exceptId has this name, ignoring case.
*/
public function isNameTaken(int $serviceUnitId, ?int $serviceId, string $name, ?int $exceptId = null): bool;
/**
* The sort order that puts a new item last among its siblings.
*/
public function nextSortOrder(int $serviceUnitId, ?int $serviceId): int;
/**
* The sibling just before or after the item, or null at either end.
*/
public function neighbour(WorkType $workType, MoveDirection $direction): ?WorkType;
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
/**
* What service units, services and work types share: a name that is unique
* among its siblings, an order among them, and an active flag. Items are
* never deleted, only deactivated, so old references keep working.
*/
abstract class CatalogItem
{
public function __construct(
protected ?int $id,
protected CatalogName $name,
protected bool $active,
protected int $sortOrder,
) {}
public function id(): ?int
{
return $this->id;
}
public function name(): CatalogName
{
return $this->name;
}
public function isActive(): bool
{
return $this->active;
}
public function sortOrder(): int
{
return $this->sortOrder;
}
public function rename(CatalogName $name): void
{
$this->name = $name;
}
public function activate(): void
{
$this->active = true;
}
public function deactivate(): void
{
$this->active = false;
}
/**
* Swaps places with a sibling.
*/
public function swapOrderWith(self $sibling): void
{
[$this->sortOrder, $sibling->sortOrder] = [$sibling->sortOrder, $this->sortOrder];
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\Exceptions\SharedUnitHasNoServices;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
/**
* A service (palvelu) inside a service unit, e.g. Videotuotanto in
* Mediatuotanto. Optional level: most units have work types directly.
*/
final class Service extends CatalogItem
{
private function __construct(?int $id, private int $serviceUnitId, CatalogName $name, bool $active, int $sortOrder)
{
parent::__construct($id, $name, $active, $sortOrder);
}
/**
* @throws SharedUnitHasNoServices
*/
public static function create(ServiceUnit $serviceUnit, CatalogName $name, int $sortOrder): self
{
if ($serviceUnit->isShared()) {
throw new SharedUnitHasNoServices;
}
return new self(null, (int) $serviceUnit->id(), $name, true, $sortOrder);
}
public static function reconstitute(int $id, int $serviceUnitId, CatalogName $name, bool $active, int $sortOrder): self
{
return new self($id, $serviceUnitId, $name, $active, $sortOrder);
}
public function serviceUnitId(): int
{
return $this->serviceUnitId;
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
/**
* A service unit (palveluyksikkö), e.g. Mediatuotanto. The shared unit
* ("Kaikille yhteiset") holds work types offered in every unit and has no
* services.
*/
final class ServiceUnit extends CatalogItem
{
private function __construct(?int $id, CatalogName $name, private bool $shared, bool $active, int $sortOrder)
{
parent::__construct($id, $name, $active, $sortOrder);
}
public static function create(CatalogName $name, int $sortOrder, bool $shared = false): self
{
return new self(null, $name, $shared, true, $sortOrder);
}
public static function reconstitute(int $id, CatalogName $name, bool $shared, bool $active, int $sortOrder): self
{
return new self($id, $name, $shared, $active, $sortOrder);
}
public function isShared(): bool
{
return $this->shared;
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\Exceptions\ServiceNotInUnit;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
/**
* 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.
*/
final class WorkType extends CatalogItem
{
private function __construct(
?int $id,
private int $serviceUnitId,
private ?int $serviceId,
CatalogName $name,
bool $active,
int $sortOrder,
) {
parent::__construct($id, $name, $active, $sortOrder);
}
/**
* @throws ServiceNotInUnit
*/
public static function create(ServiceUnit $serviceUnit, ?Service $service, CatalogName $name, int $sortOrder): self
{
self::ensureServiceInUnit($serviceUnit, $service);
return new self(null, (int) $serviceUnit->id(), $service?->id(), $name, true, $sortOrder);
}
public static function reconstitute(int $id, int $serviceUnitId, ?int $serviceId, CatalogName $name, bool $active, int $sortOrder): self
{
return new self($id, $serviceUnitId, $serviceId, $name, $active, $sortOrder);
}
/**
* Moves the work type under another service of the same unit (or under
* no service), last among its new siblings.
*
* @throws ServiceNotInUnit
*/
public function moveToService(ServiceUnit $serviceUnit, ?Service $service, int $sortOrder): void
{
if ($serviceUnit->id() !== $this->serviceUnitId) {
throw new ServiceNotInUnit;
}
self::ensureServiceInUnit($serviceUnit, $service);
$this->serviceId = $service?->id();
$this->sortOrder = $sortOrder;
}
public function serviceUnitId(): int
{
return $this->serviceUnitId;
}
public function serviceId(): ?int
{
return $this->serviceId;
}
private static function ensureServiceInUnit(ServiceUnit $serviceUnit, ?Service $service): void
{
if ($service !== null && $service->serviceUnitId() !== $serviceUnit->id()) {
throw new ServiceNotInUnit;
}
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Enums;
/**
* The three levels of the catalog: service unit > (service) > work type.
*/
enum CatalogLevel: string
{
case ServiceUnit = 'service_unit';
case Service = 'service';
case WorkType = 'work_type';
}
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Enums;
enum MoveDirection: string
{
case Up = 'up';
case Down = 'down';
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class CatalogItemNotFound extends DomainException
{
public function __construct(public readonly CatalogLevel $level, public readonly int $id)
{
parent::__construct("Catalog {$level->value} {$id} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class CatalogNameTaken extends DomainException
{
public function __construct()
{
parent::__construct('Another item on the same level 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 InvalidCatalogName extends DomainException
{
public function __construct()
{
parent::__construct('The name must be 1–100 characters.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ServiceNotInUnit extends DomainException
{
public function __construct()
{
parent::__construct('The service belongs to another service unit.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class SharedUnitHasNoServices extends DomainException
{
public function __construct()
{
parent::__construct('The shared service unit cannot have services.');
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\ValueObjects;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
/**
* Name of a service unit, service or work type, e.g. "Videotuotanto".
*/
final readonly class CatalogName
{
public const int MAX_LENGTH = 100;
public string $value;
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidCatalogName;
}
$this->value = $value;
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Database\Factories\ServiceFactory;
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;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
*
* @property int $id
* @property int $service_unit_id
* @property string $name
* @property bool $is_active
* @property int $sort_order
*/
#[Table('services')]
#[Fillable(['service_unit_id', 'name', 'is_active', 'sort_order'])]
#[UseFactory(ServiceFactory::class)]
class ServiceModel extends Model
{
/** @use HasFactory<ServiceFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'service_unit_id' => 'integer',
'is_active' => 'boolean',
'sort_order' => 'integer',
];
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Database\Factories\ServiceUnitFactory;
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;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
*
* @property int $id
* @property string $name
* @property bool $is_shared
* @property bool $is_active
* @property int $sort_order
*/
#[Table('service_units')]
#[Fillable(['name', 'is_shared', 'is_active', 'sort_order'])]
#[UseFactory(ServiceUnitFactory::class)]
class ServiceUnitModel extends Model
{
/** @use HasFactory<ServiceUnitFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_shared' => 'boolean',
'is_active' => 'boolean',
'sort_order' => 'integer',
];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Database\Factories\WorkTypeFactory;
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;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
*
* @property int $id
* @property int $service_unit_id
* @property int|null $service_id
* @property string $name
* @property bool $is_active
* @property int $sort_order
*/
#[Table('work_types')]
#[Fillable(['service_unit_id', 'service_id', 'name', 'is_active', 'sort_order'])]
#[UseFactory(WorkTypeFactory::class)]
class WorkTypeModel extends Model
{
/** @use HasFactory<WorkTypeFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'service_unit_id' => 'integer',
'service_id' => 'integer',
'is_active' => 'boolean',
'sort_order' => 'integer',
];
}
}
@@ -0,0 +1,149 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\DTOs\ServiceNode;
use App\Modules\Catalog\Application\DTOs\ServiceSummary;
use App\Modules\Catalog\Application\DTOs\ServiceUnitNode;
use App\Modules\Catalog\Application\DTOs\ServiceUnitSummary;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
class EloquentCatalogQueries implements CatalogQueries
{
public function tree(bool $includeInactive = true): array
{
return $this->buildTree(ServiceUnitModel::query(), $includeInactive);
}
public function activeServiceUnits(): array
{
return ServiceUnitModel::query()
->where('is_active', true)
->where('is_shared', false)
->orderBy('sort_order')
->get()
->map(fn (ServiceUnitModel $model): ServiceUnitSummary => $this->toServiceUnitSummary($model))
->values()
->all();
}
public function activeWorkTypesFor(array $serviceUnitIds): array
{
$units = ServiceUnitModel::query()->where(fn (Builder $query) => $query
->whereIn('id', $serviceUnitIds)
->orWhere('is_shared', true));
return $this->buildTree($units, includeInactive: false);
}
public function findServiceUnit(int $id): ?ServiceUnitSummary
{
$model = ServiceUnitModel::query()->find($id);
return $model === null ? null : $this->toServiceUnitSummary($model);
}
public function findService(int $id): ?ServiceSummary
{
$model = ServiceModel::query()->find($id);
return $model === null ? null : $this->toServiceSummary($model);
}
public function findWorkType(int $id): ?WorkTypeSummary
{
$model = WorkTypeModel::query()->find($id);
return $model === null ? null : $this->toWorkTypeSummary($model);
}
public function servicesOf(int $serviceUnitId): array
{
return ServiceModel::query()
->where('service_unit_id', $serviceUnitId)
->orderBy('sort_order')
->get()
->map(fn (ServiceModel $model): ServiceSummary => $this->toServiceSummary($model))
->values()
->all();
}
/**
* Three queries for the whole tree, grouped in memory. The shared unit
* always comes last, after the units it serves.
*
* @param Builder<ServiceUnitModel> $units
* @return list<ServiceUnitNode>
*/
private function buildTree(Builder $units, bool $includeInactive): array
{
$unitModels = $units
->when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true))
->orderBy('is_shared')
->orderBy('sort_order')
->get();
$unitIds = $unitModels->pluck('id')->all();
/** @var Collection<int, Collection<int, ServiceModel>> $services */
$services = ServiceModel::query()
->whereIn('service_unit_id', $unitIds)
->when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true))
->orderBy('sort_order')
->get()
->groupBy('service_unit_id');
/** @var Collection<string, Collection<int, WorkTypeModel>> $workTypes Keyed by "unitId-serviceId" or "unitId-none". */
$workTypes = WorkTypeModel::query()
->whereIn('service_unit_id', $unitIds)
->when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true))
->orderBy('sort_order')
->get()
->groupBy(fn (WorkTypeModel $model): string => $model->service_unit_id.'-'.($model->service_id ?? 'none'));
return $unitModels->map(fn (ServiceUnitModel $unit): ServiceUnitNode => new ServiceUnitNode(
$this->toServiceUnitSummary($unit),
($services->get($unit->id) ?? collect())
->map(fn (ServiceModel $service): ServiceNode => new ServiceNode(
$this->toServiceSummary($service),
$this->workTypeSummaries($workTypes->get($unit->id.'-'.$service->id)),
))
->values()
->all(),
$this->workTypeSummaries($workTypes->get($unit->id.'-none')),
))->values()->all();
}
/**
* @param Collection<int, WorkTypeModel>|null $models
* @return list<WorkTypeSummary>
*/
private function workTypeSummaries(?Collection $models): array
{
return ($models ?? collect())
->map(fn (WorkTypeModel $model): WorkTypeSummary => $this->toWorkTypeSummary($model))
->values()
->all();
}
private function toServiceUnitSummary(ServiceUnitModel $model): ServiceUnitSummary
{
return new ServiceUnitSummary($model->id, $model->name, $model->is_shared, $model->is_active);
}
private function toServiceSummary(ServiceModel $model): ServiceSummary
{
return new ServiceSummary($model->id, $model->service_unit_id, $model->name, $model->is_active);
}
private function toWorkTypeSummary(WorkTypeModel $model): WorkTypeSummary
{
return new WorkTypeSummary($model->id, $model->service_unit_id, $model->service_id, $model->name, $model->is_active);
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Domain\Contracts\ServiceRepository;
use App\Modules\Catalog\Domain\Entities\Service;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceModel;
class EloquentServiceRepository implements ServiceRepository
{
public function findById(int $id): ?Service
{
$model = ServiceModel::query()->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(Service $service): Service
{
$model = $service->id() === null ? new ServiceModel : ServiceModel::query()->findOrFail($service->id());
$model->fill([
'service_unit_id' => $service->serviceUnitId(),
'name' => $service->name()->value,
'is_active' => $service->isActive(),
'sort_order' => $service->sortOrder(),
])->save();
return $this->toEntity($model);
}
public function isNameTaken(int $serviceUnitId, string $name, ?int $exceptId = null): bool
{
return ServiceModel::query()
->where('service_unit_id', $serviceUnitId)
->whereRaw('LOWER(name) = ?', [mb_strtolower($name)])
->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId))
->exists();
}
public function nextSortOrder(int $serviceUnitId): int
{
return (int) ServiceModel::query()->where('service_unit_id', $serviceUnitId)->max('sort_order') + 1;
}
public function neighbour(Service $service, MoveDirection $direction): ?Service
{
$model = ServiceModel::query()
->where('service_unit_id', $service->serviceUnitId())
->where('sort_order', $direction === MoveDirection::Up ? '<' : '>', $service->sortOrder())
->orderBy('sort_order', $direction === MoveDirection::Up ? 'desc' : 'asc')
->first();
return $model === null ? null : $this->toEntity($model);
}
private function toEntity(ServiceModel $model): Service
{
return Service::reconstitute($model->id, $model->service_unit_id, new CatalogName($model->name), $model->is_active, $model->sort_order);
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Entities\ServiceUnit;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
class EloquentServiceUnitRepository implements ServiceUnitRepository
{
public function findById(int $id): ?ServiceUnit
{
$model = ServiceUnitModel::query()->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(ServiceUnit $serviceUnit): ServiceUnit
{
$model = $serviceUnit->id() === null ? new ServiceUnitModel : ServiceUnitModel::query()->findOrFail($serviceUnit->id());
$model->fill([
'name' => $serviceUnit->name()->value,
'is_shared' => $serviceUnit->isShared(),
'is_active' => $serviceUnit->isActive(),
'sort_order' => $serviceUnit->sortOrder(),
])->save();
return $this->toEntity($model);
}
public function isNameTaken(string $name, ?int $exceptId = null): bool
{
return ServiceUnitModel::query()
->whereRaw('LOWER(name) = ?', [mb_strtolower($name)])
->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId))
->exists();
}
public function nextSortOrder(): int
{
return (int) ServiceUnitModel::query()->max('sort_order') + 1;
}
public function neighbour(ServiceUnit $serviceUnit, MoveDirection $direction): ?ServiceUnit
{
$model = ServiceUnitModel::query()
->where('sort_order', $direction === MoveDirection::Up ? '<' : '>', $serviceUnit->sortOrder())
->orderBy('sort_order', $direction === MoveDirection::Up ? 'desc' : 'asc')
->first();
return $model === null ? null : $this->toEntity($model);
}
private function toEntity(ServiceUnitModel $model): ServiceUnit
{
return ServiceUnit::reconstitute($model->id, new CatalogName($model->name), $model->is_shared, $model->is_active, $model->sort_order);
}
}
@@ -0,0 +1,84 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
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 Illuminate\Database\Eloquent\Builder;
class EloquentWorkTypeRepository implements WorkTypeRepository
{
public function findById(int $id): ?WorkType
{
$model = WorkTypeModel::query()->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(WorkType $workType): WorkType
{
$model = $workType->id() === null ? new WorkTypeModel : WorkTypeModel::query()->findOrFail($workType->id());
$model->fill([
'service_unit_id' => $workType->serviceUnitId(),
'service_id' => $workType->serviceId(),
'name' => $workType->name()->value,
'is_active' => $workType->isActive(),
'sort_order' => $workType->sortOrder(),
])->save();
return $this->toEntity($model);
}
public function isNameTaken(int $serviceUnitId, ?int $serviceId, string $name, ?int $exceptId = null): bool
{
return $this->siblings($serviceUnitId, $serviceId)
->whereRaw('LOWER(name) = ?', [mb_strtolower($name)])
->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId))
->exists();
}
public function nextSortOrder(int $serviceUnitId, ?int $serviceId): int
{
return (int) $this->siblings($serviceUnitId, $serviceId)->max('sort_order') + 1;
}
public function neighbour(WorkType $workType, MoveDirection $direction): ?WorkType
{
$model = $this->siblings($workType->serviceUnitId(), $workType->serviceId())
->where('sort_order', $direction === MoveDirection::Up ? '<' : '>', $workType->sortOrder())
->orderBy('sort_order', $direction === MoveDirection::Up ? 'desc' : 'asc')
->first();
return $model === null ? null : $this->toEntity($model);
}
/**
* @return Builder<WorkTypeModel>
*/
private function siblings(int $serviceUnitId, ?int $serviceId): Builder
{
return WorkTypeModel::query()
->where('service_unit_id', $serviceUnitId)
->when(
$serviceId === null,
fn (Builder $query) => $query->whereNull('service_id'),
fn (Builder $query) => $query->where('service_id', $serviceId),
);
}
private function toEntity(WorkTypeModel $model): WorkType
{
return WorkType::reconstitute(
$model->id,
$model->service_unit_id,
$model->service_id,
new CatalogName($model->name),
$model->is_active,
$model->sort_order,
);
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
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\EloquentServiceRepository;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceUnitRepository;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkTypeRepository;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Catalog module (service units, services, work types) into
* Laravel: bindings, routes, the `catalog::` Livewire namespace and the
* `catalog.manage` ability.
*/
class CatalogServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
ServiceUnitRepository::class => EloquentServiceUnitRepository::class,
ServiceRepository::class => EloquentServiceRepository::class,
WorkTypeRepository::class => EloquentWorkTypeRepository::class,
CatalogQueries::class => EloquentCatalogQueries::class,
];
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('catalog', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
// Catalog data (pohjatiedot) is managed by admins and management.
Gate::define('catalog.manage', fn (User $user): bool => in_array($user->role, [Role::Admin, Role::Management], true));
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Modules\Catalog\Presentation\Livewire\Forms;
use App\Modules\Catalog\Domain\Exceptions\CatalogNameTaken;
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 Livewire\Form;
/**
* Name (and for work types, service) of a service unit, service or work type.
*/
class CatalogItemForm extends Form
{
public string $name = '';
/**
* Only for work types: '' means directly under the service unit.
*/
public string $service_id = '';
public function validatedName(): string
{
$this->validate();
return $this->name;
}
public function serviceId(): ?int
{
return $this->service_id === '' ? null : (int) $this->service_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'],
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'],
default => throw $exception,
};
$this->addError($field, __($key));
}
/**
* @return array<string, array<int, string>>
*/
protected function rules(): array
{
return [
'name' => ['required', 'string', 'max:100'],
'service_id' => ['nullable', 'integer'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'name.required' => __('catalog.errors.name_required'),
'name.max' => __('catalog.errors.invalid_name'),
'service_id.integer' => __('catalog.errors.service_not_in_unit'),
];
}
}
@@ -0,0 +1,216 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\DTOs\ServiceUnitNode;
use App\Modules\Catalog\Application\UseCases\MoveCatalogItem;
use App\Modules\Catalog\Application\UseCases\SetCatalogItemActive;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use Livewire\Attributes\Computed;
use Livewire\Component;
/**
* Catalog management (pohjatiedot): service units, services and work types.
*/
new class extends Component
{
public bool $showInactive = true;
public string $statusMessage = '';
protected CatalogQueries $catalogQueries;
public function boot(CatalogQueries $catalogQueries): void
{
$this->catalogQueries = $catalogQueries;
}
public function mount(): void
{
$this->authorize('catalog.manage');
}
/**
* @return list<ServiceUnitNode>
*/
#[Computed]
public function tree(): array
{
return $this->catalogQueries->tree($this->showInactive);
}
public function move(string $level, int $id, string $direction, MoveCatalogItem $moveItem): void
{
$this->authorize('catalog.manage');
$catalogLevel = CatalogLevel::from($level);
$moveDirection = MoveDirection::from($direction);
$name = $this->nameOf($catalogLevel, $id);
try {
$moved = $moveItem->execute($catalogLevel, $id, $moveDirection);
} catch (CatalogItemNotFound) {
$this->statusMessage = __('catalog.status.not_found');
return;
}
$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-{$direction}-{$level}-{$id}')?.focus()");
}
public function toggleActive(string $level, int $id, SetCatalogItemActive $setActive): void
{
$this->authorize('catalog.manage');
$catalogLevel = CatalogLevel::from($level);
$active = ! $this->isActive($catalogLevel, $id);
try {
$setActive->execute($catalogLevel, $id, $active);
} catch (CatalogItemNotFound) {
$this->statusMessage = __('catalog.status.not_found');
return;
}
$this->statusMessage = __($active ? 'catalog.status.activated' : 'catalog.status.deactivated', [
'name' => $this->nameOf($catalogLevel, $id),
]);
}
public function render(): mixed
{
return $this->view()->title(__('catalog.title'));
}
private function nameOf(CatalogLevel $level, int $id): string
{
return match ($level) {
CatalogLevel::ServiceUnit => $this->catalogQueries->findServiceUnit($id)?->name,
CatalogLevel::Service => $this->catalogQueries->findService($id)?->name,
CatalogLevel::WorkType => $this->catalogQueries->findWorkType($id)?->name,
} ?? '';
}
private function isActive(CatalogLevel $level, int $id): bool
{
return match ($level) {
CatalogLevel::ServiceUnit => $this->catalogQueries->findServiceUnit($id)?->isActive,
CatalogLevel::Service => $this->catalogQueries->findService($id)?->isActive,
CatalogLevel::WorkType => $this->catalogQueries->findWorkType($id)?->isActive,
} ?? false;
}
};
?>
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold">{{ __('catalog.title') }}</h1>
<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>
@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')" />
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
@foreach ($this->tree as $node)
@php($unit = $node->serviceUnit)
<section
wire:key="service-unit-{{ $unit->id }}"
aria-labelledby="service-unit-{{ $unit->id }}-heading"
class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<h2 id="service-unit-{{ $unit->id }}-heading" class="text-xl font-semibold break-words">
{{ $unit->name }}
@unless ($unit->isActive)
<span class="ml-2 text-sm font-normal">({{ __('catalog.inactive') }})</span>
@endunless
</h2>
<x-catalog.item-actions
level="service_unit"
:id="$unit->id"
:name="$unit->name"
:active="$unit->isActive"
:edit-url="route('catalog.service-units.edit', $unit->id)"
/>
</div>
@if ($unit->isShared)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.shared') }}</p>
@endif
@foreach ($node->services as $serviceNode)
@php($service = $serviceNode->service)
<div wire:key="service-{{ $service->id }}" class="space-y-2 border-l-2 border-zinc-200 pl-4 dark:border-zinc-700">
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 class="text-lg font-medium break-words">
{{ $service->name }}
@unless ($service->isActive)
<span class="ml-2 text-sm font-normal">({{ __('catalog.inactive') }})</span>
@endunless
</h3>
<x-catalog.item-actions
level="service"
:id="$service->id"
:name="$service->name"
:active="$service->isActive"
:edit-url="route('catalog.services.edit', $service->id)"
/>
</div>
<x-catalog.work-type-list :work-types="$serviceNode->workTypes" />
</div>
@endforeach
@if ($node->workTypes !== [] || $node->services === [])
<x-catalog.work-type-list :work-types="$node->workTypes" />
@endif
<div class="flex flex-wrap gap-2">
@unless ($unit->isShared)
<x-button
:href="route('catalog.services.create', $unit->id)"
wire:navigate
subtle
color="black"
sm
icon="plus"
:text="__('catalog.actions.add_service')"
:aria-label="__('catalog.actions.add_service_to', ['name' => $unit->name])"
/>
@endunless
<x-button
:href="route('catalog.work-types.create', $unit->id)"
wire:navigate
subtle
color="black"
sm
icon="plus"
:text="__('catalog.actions.add_work_type')"
:aria-label="__('catalog.actions.add_work_type_to', ['name' => $unit->name])"
/>
</div>
</section>
@endforeach
</div>
@@ -0,0 +1,104 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\UseCases\AddService;
use App\Modules\Catalog\Application\UseCases\RenameCatalogItem;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\CatalogItemForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (with {serviceUnit}) and edit page (with {service}) of a service.
*/
new class extends Component
{
#[Locked]
public ?int $serviceUnitId = null;
#[Locked]
public ?int $serviceId = null;
#[Locked]
public string $unitName = '';
public CatalogItemForm $form;
public function mount(CatalogQueries $catalogQueries, ?int $serviceUnit = null, ?int $service = null): void
{
$this->authorize('catalog.manage');
if ($service !== null) {
$summary = $catalogQueries->findService($service);
abort_if($summary === null, 404);
$this->serviceId = $summary->id;
$this->form->name = $summary->name;
$serviceUnit = $summary->serviceUnitId;
}
$unit = $serviceUnit === null ? null : $catalogQueries->findServiceUnit($serviceUnit);
abort_if($unit === null || ($unit->isShared && $this->serviceId === null), 404);
$this->serviceUnitId = $unit->id;
$this->unitName = $unit->name;
}
public function save(AddService $addService, RenameCatalogItem $renameItem): void
{
$this->authorize('catalog.manage');
$name = $this->form->validatedName();
try {
if ($this->serviceId === null) {
$addService->execute((int) $this->serviceUnitId, $name);
session()->flash('status', __('catalog.status.created', ['name' => trim($name)]));
} else {
$renameItem->execute(CatalogLevel::Service, $this->serviceId, $name);
session()->flash('status', __('catalog.status.updated', ['name' => trim($name)]));
}
} catch (CatalogItemNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('catalog.index', navigate: true);
}
public function heading(): string
{
return __($this->serviceId === null ? 'catalog.services.create_title' : 'catalog.services.edit_title');
}
public function render(): mixed
{
return $this->view()->title($this->heading().' – '.$this->unitName);
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
@if ($unitName !== '')
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p>
@endif
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
<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')" />
</div>
</form>
</div>
@@ -0,0 +1,93 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\UseCases\AddServiceUnit;
use App\Modules\Catalog\Application\UseCases\RenameCatalogItem;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\CatalogItemForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (no {serviceUnit}) and edit page (with {serviceUnit}) of a service unit.
*/
new class extends Component
{
#[Locked]
public ?int $serviceUnitId = null;
#[Locked]
public string $unitName = '';
public CatalogItemForm $form;
public function mount(CatalogQueries $catalogQueries, ?int $serviceUnit = null): void
{
$this->authorize('catalog.manage');
if ($serviceUnit === null) {
return;
}
$summary = $catalogQueries->findServiceUnit($serviceUnit);
abort_if($summary === null, 404);
$this->serviceUnitId = $summary->id;
$this->form->name = $summary->name;
}
public function save(AddServiceUnit $addServiceUnit, RenameCatalogItem $renameItem): void
{
$this->authorize('catalog.manage');
$name = $this->form->validatedName();
try {
if ($this->serviceUnitId === null) {
$addServiceUnit->execute($name);
session()->flash('status', __('catalog.status.created', ['name' => trim($name)]));
} else {
$renameItem->execute(CatalogLevel::ServiceUnit, $this->serviceUnitId, $name);
session()->flash('status', __('catalog.status.updated', ['name' => trim($name)]));
}
} catch (CatalogItemNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('catalog.index', navigate: true);
}
public function heading(): string
{
return __($this->serviceUnitId === null ? 'catalog.service_units.create_title' : 'catalog.service_units.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">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
<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')" />
</div>
</form>
</div>
@@ -0,0 +1,135 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
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 Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (with {serviceUnit}) and edit page (with {workType}) of a work type.
*/
new class extends Component
{
#[Locked]
public ?int $serviceUnitId = null;
#[Locked]
public ?int $workTypeId = null;
#[Locked]
public string $unitName = '';
public CatalogItemForm $form;
public function mount(CatalogQueries $catalogQueries, ?int $serviceUnit = null, ?int $workType = null): void
{
$this->authorize('catalog.manage');
if ($workType !== null) {
$summary = $catalogQueries->findWorkType($workType);
abort_if($summary === null, 404);
$this->workTypeId = $summary->id;
$this->form->name = $summary->name;
$this->form->service_id = $summary->serviceId === null ? '' : (string) $summary->serviceId;
$serviceUnit = $summary->serviceUnitId;
}
$unit = $serviceUnit === null ? null : $catalogQueries->findServiceUnit($serviceUnit);
abort_if($unit === null, 404);
$this->serviceUnitId = $unit->id;
$this->unitName = $unit->name;
}
/**
* @return list<ServiceSummary>
*/
#[Computed]
public function services(): array
{
return app(CatalogQueries::class)->servicesOf((int) $this->serviceUnitId);
}
public function save(AddWorkType $addWorkType, UpdateWorkType $updateWorkType): void
{
$this->authorize('catalog.manage');
$name = $this->form->validatedName();
$serviceId = $this->form->serviceId();
try {
if ($this->workTypeId === null) {
$addWorkType->execute((int) $this->serviceUnitId, $serviceId, $name);
session()->flash('status', __('catalog.status.created', ['name' => trim($name)]));
} else {
$updateWorkType->execute($this->workTypeId, $serviceId, $name);
session()->flash('status', __('catalog.status.updated', ['name' => trim($name)]));
}
} catch (CatalogItemNotFound) {
$this->form->addError('form.service_id', __('catalog.errors.service_not_in_unit'));
return;
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('catalog.index', navigate: true);
}
public function heading(): string
{
return __($this->workTypeId === null ? 'catalog.work_types.create_title' : 'catalog.work_types.edit_title');
}
public function render(): mixed
{
return $this->view()->title($this->heading().' – '.$this->unitName);
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
@if ($unitName !== '')
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p>
@endif
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
@if ($this->services !== [])
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native
wire:model="form.service_id"
:label="__('catalog.work_types.service')"
:aria-label="__('catalog.work_types.service')"
:hint="__('catalog.work_types.service_description')"
>
<option value="">{{ __('catalog.work_types.no_service') }}</option>
@foreach ($this->services as $service)
<option wire:key="service-option-{{ $service->id }}" value="{{ $service->id }}">
{{ $service->name }}@unless ($service->isActive) ({{ __('catalog.inactive') }})@endunless
</option>
@endforeach
</x-select.native>
@endif
<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')" />
</div>
</form>
</div>
@@ -0,0 +1,29 @@
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:catalog.manage'])
->prefix('catalog')
->name('catalog.')
->group(function () {
Route::livewire('/', 'catalog::index')->name('index');
Route::livewire('/service-units/create', 'catalog::service-unit-form')->name('service-units.create');
Route::livewire('/service-units/{serviceUnit}/edit', 'catalog::service-unit-form')
->whereNumber('serviceUnit')
->name('service-units.edit');
Route::livewire('/service-units/{serviceUnit}/services/create', 'catalog::service-form')
->whereNumber('serviceUnit')
->name('services.create');
Route::livewire('/services/{service}/edit', 'catalog::service-form')
->whereNumber('service')
->name('services.edit');
Route::livewire('/service-units/{serviceUnit}/work-types/create', 'catalog::work-type-form')
->whereNumber('serviceUnit')
->name('work-types.create');
Route::livewire('/work-types/{workType}/edit', 'catalog::work-type-form')
->whereNumber('workType')
->name('work-types.edit');
});
+2
View File
@@ -1,5 +1,6 @@
<?php
use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider;
use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider;
use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider;
use App\Modules\Users\Infrastructure\Providers\UsersServiceProvider;
@@ -10,4 +11,5 @@ return [
SharedServiceProvider::class,
UsersServiceProvider::class,
CustomersServiceProvider::class,
CatalogServiceProvider::class,
];
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace Database\Factories;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<ServiceModel>
*/
class ServiceFactory extends Factory
{
protected $model = ServiceModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'service_unit_id' => ServiceUnitModel::factory(),
'name' => fake()->unique()->words(2, true),
'is_active' => true,
'sort_order' => fake()->unique()->numberBetween(100, 100000),
];
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Database\Factories;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<ServiceUnitModel>
*/
class ServiceUnitFactory extends Factory
{
protected $model = ServiceUnitModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->unique()->words(2, true),
'is_shared' => false,
'is_active' => true,
'sort_order' => fake()->unique()->numberBetween(100, 100000),
];
}
public function inactive(): static
{
return $this->state(fn (): array => ['is_active' => false]);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace Database\Factories;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<WorkTypeModel>
*/
class WorkTypeFactory extends Factory
{
protected $model = WorkTypeModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'service_unit_id' => ServiceUnitModel::factory(),
'service_id' => null,
'name' => fake()->unique()->words(2, true),
'is_active' => true,
'sort_order' => fake()->unique()->numberBetween(100, 100000),
];
}
public function inactive(): static
{
return $this->state(fn (): array => ['is_active' => false]);
}
}
@@ -0,0 +1,59 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Service units > services > work types. Rows are never deleted, only
* deactivated, so the foreign keys restrict deletes.
*/
public function up(): void
{
Schema::create('service_units', function (Blueprint $table) {
$table->id();
$table->string('name', 100);
$table->boolean('is_shared')->default(false);
$table->boolean('is_active')->default(true);
$table->unsignedInteger('sort_order');
$table->timestamps();
$table->index('sort_order');
});
Schema::create('services', function (Blueprint $table) {
$table->id();
$table->foreignId('service_unit_id')->constrained()->restrictOnDelete();
$table->string('name', 100);
$table->boolean('is_active')->default(true);
$table->unsignedInteger('sort_order');
$table->timestamps();
$table->index(['service_unit_id', 'sort_order']);
});
Schema::create('work_types', function (Blueprint $table) {
$table->id();
$table->foreignId('service_unit_id')->constrained()->restrictOnDelete();
$table->foreignId('service_id')->nullable()->constrained()->restrictOnDelete();
$table->string('name', 100);
$table->boolean('is_active')->default(true);
$table->unsignedInteger('sort_order');
$table->timestamps();
$table->index(['service_unit_id', 'service_id', 'sort_order']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('work_types');
Schema::dropIfExists('services');
Schema::dropIfExists('service_units');
}
};
@@ -0,0 +1,95 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* The starting catalog from the specification (chapter 11.1), so every
* installation has it without a separate seed command. Units with
* services list them as 'service' => [work types]; others list work
* types directly. The last unit is the shared one.
*
* @var array<string, array<int|string, string|list<string>>>
*/
private const array CATALOG = [
'Mediatuotanto' => [
'Videotuotanto' => ['videokuvaus', 'kuvausassistentti', 'editointi', 'animointi', '3D-mallinnus'],
'Valokuvaus' => ['kuvaus', 'editointi'],
'Äänituotanto' => ['äänitys', 'editointi'],
],
'Markkinointi' => ['graafinen työ', 'julkaisutyö', 'kampanjatyö'],
'Painotuotanto' => ['painotyö', 'asennus'],
'Ylläpitopalvelut' => ['asennustyö', 'päivitystyö'],
'Verkkosivut' => ['ohjelmointityö'],
'Ohjelmistot' => ['ohjelmointityö', 'ohjelmointityö vaativa', 'pelimoottoritoteutukset'],
'Kuluttajapalvelut' => ['valokuvaus', 'tulosteet', 'passikuvat', 'digitointi'],
'Kaikille yhteiset' => ['suunnittelu', 'tuotanto', 'projektin johtaminen', 'konsultointi', 'koulutus'],
];
private const string SHARED_UNIT = 'Kaikille yhteiset';
public function up(): void
{
if (DB::table('service_units')->exists()) {
return;
}
$now = now();
$unitOrder = 0;
foreach (self::CATALOG as $unitName => $children) {
$unitId = DB::table('service_units')->insertGetId([
'name' => $unitName,
'is_shared' => $unitName === self::SHARED_UNIT,
'is_active' => true,
'sort_order' => ++$unitOrder,
'created_at' => $now,
'updated_at' => $now,
]);
$serviceOrder = 0;
$workTypeOrder = 0;
foreach ($children as $key => $child) {
if (is_array($child)) {
$serviceId = DB::table('services')->insertGetId([
'service_unit_id' => $unitId,
'name' => $key,
'is_active' => true,
'sort_order' => ++$serviceOrder,
'created_at' => $now,
'updated_at' => $now,
]);
foreach (array_values($child) as $index => $workType) {
$this->insertWorkType($unitId, $serviceId, $workType, $index + 1, $now);
}
continue;
}
$this->insertWorkType($unitId, null, $child, ++$workTypeOrder, $now);
}
}
}
/**
* The starting data is not removed: it may already be referenced.
*/
public function down(): void {}
private function insertWorkType(int $unitId, ?int $serviceId, string $name, int $sortOrder, mixed $now): void
{
DB::table('work_types')->insert([
'service_unit_id' => $unitId,
'service_id' => $serviceId,
'name' => $name,
'is_active' => true,
'sort_order' => $sortOrder,
'created_at' => $now,
'updated_at' => $now,
]);
}
};
+7 -5
View File
@@ -316,9 +316,10 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
- `billing_units`: `customer_id`, `name`, `billing_address`, `e_invoice_address`, `e_invoice_operator`, `reference` *(olemassa)*
**Catalog** (palveluyksiköt ja hinnasto)
- `service_units`: `name`, `sort_order`, `is_shared` (kaikille yhteiset)
- `services`: `service_unit_id`, `name`, `sort_order`
- `work_types`: `service_unit_id`, `service_id` (nullable), `name`, `hourly_rate_cents` *(V2)*, `sort_order`, `is_active`
- `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)*
- 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ä)
@@ -393,8 +394,9 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
- Sisäinen asiakas on merkitty, eikä sitä voi poistaa.
### 16.3 Pohjatiedot
- Pääkäyttäjä ja johto voivat lisätä, nimetä uudelleen, järjestää ja poistaa käytöstä palveluyksiköitä, palveluita ja työtehtäviä. Käytössä olleita ei poisteta, vaan ne poistetaan käytöstä.
- Luvun 11.1 lista luodaan siemendatana.
- Pääkäyttäjä ja johto voivat lisätä, nimetä uudelleen, järjestää ja poistaa käytöstä palveluyksiköitä, palveluita ja työtehtäviä Pohjatiedot-sivulla *(valmis)*. Käytössä olleita ei poisteta, vaan ne poistetaan käytöstä. Järjestys muutetaan Siirrä ylös / Siirrä alas -painikkeilla (toimii näppäimistöllä).
- Työtehtävän voi siirtää toiseen saman yksikön palveluun tai suoraan yksikön alle.
- Luvun 11.1 lista lisätään migraatiossa, jos taulut ovat tyhjiä *(valmis)*.
### 16.4 Asiakastyöt
- Työntekijä voi luoda ja muokata asiakastöitä; alihankkija ei.
+69
View File
@@ -0,0 +1,69 @@
<?php
return [
'title' => 'Pohjatiedot',
'intro' => 'Palveluyksiköt, palvelut ja työtehtävät. Asiakastyölle valitaan palveluyksiköt, ja tehtävät ja tunnit kirjataan työtehtäville. Rivejä ei poisteta, vaan ne poistetaan käytöstä, jotta vanhat kirjaukset säilyvät.',
'show_inactive' => 'Näytä käytöstä poistetut',
'inactive' => 'Ei käytössä',
'shared' => 'Työtehtävät ovat valittavissa kaikissa palveluyksiköissä.',
'no_work_types' => 'Ei työtehtäviä.',
'save' => 'Tallenna',
'cancel' => 'Peruuta',
'actions' => [
'edit' => 'Muokkaa',
'edit_named' => 'Muokkaa: :name',
'move_up_named' => 'Siirrä ylös: :name',
'move_down_named' => 'Siirrä alas: :name',
'active' => 'Käytössä',
'active_named' => 'Käytössä: :name',
'add_service_unit' => 'Lisää palveluyksikkö',
'add_service' => 'Lisää palvelu',
'add_service_to' => 'Lisää palvelu yksikköön :name',
'add_work_type' => 'Lisää työtehtävä',
'add_work_type_to' => 'Lisää työtehtävä yksikköön :name',
],
'status' => [
'moved_up' => ':name siirretty ylöspäin.',
'moved_down' => ':name siirretty alaspäin.',
'already_first' => ':name on jo ensimmäisenä.',
'already_last' => ':name on jo viimeisenä.',
'activated' => ':name otettu käyttöön.',
'deactivated' => ':name poistettu käytöstä. Se ei näy uusissa valinnoissa.',
'not_found' => 'Riviä ei löytynyt. Päivitä sivu.',
'created' => ':name lisätty.',
'updated' => ':name tallennettu.',
],
'service_units' => [
'create_title' => 'Uusi palveluyksikkö',
'edit_title' => 'Muokkaa palveluyksikköä',
],
'services' => [
'create_title' => 'Uusi palvelu',
'edit_title' => 'Muokkaa palvelua',
],
'work_types' => [
'create_title' => 'Uusi työtehtävä',
'edit_title' => 'Muokkaa työtehtävää',
'service' => 'Palvelu',
'service_description' => 'Työtehtävä voi kuulua palveluun tai suoraan palveluyksikköön.',
'no_service' => 'Ei palvelua (suoraan palveluyksikön alla)',
],
'fields' => [
'name' => 'Nimi',
'service_unit' => 'Palveluyksikkö',
],
'errors' => [
'name_required' => 'Anna nimi.',
'invalid_name' => 'Nimen pituus voi olla enintään 100 merkkiä.',
'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.',
],
];
+1
View File
@@ -6,6 +6,7 @@ return [
'home' => 'Etusivu',
'customers' => 'Asiakkaat',
'users' => 'Käyttäjät',
'catalog' => 'Pohjatiedot',
'signed_in_as' => 'Kirjautuneena: :name',
'logout' => 'Kirjaudu ulos',
'theme_toggle' => 'Tumma teema',
@@ -0,0 +1,57 @@
{{--
Row actions of a catalog item on the catalog page: edit, move up/down
(buttons, so no dragging is needed) and an "in use" checkbox whose name
stays the same while its state changes.
--}}
@props([
'level',
'id',
'name',
'active',
'editUrl',
])
<div class="flex flex-wrap items-center gap-2">
<x-button
:href="$editUrl"
wire:navigate
subtle
color="black"
sm
icon="pencil"
:text="__('catalog.actions.edit')"
:aria-label="__('catalog.actions.edit_named', ['name' => $name])"
/>
<x-button.circle
id="move-up-{{ $level }}-{{ $id }}"
wire:click="move('{{ $level }}', {{ $id }}, 'up')"
subtle
color="black"
sm
icon="arrow-up"
:aria-label="__('catalog.actions.move_up_named', ['name' => $name])"
/>
<x-button.circle
id="move-down-{{ $level }}-{{ $id }}"
wire:click="move('{{ $level }}', {{ $id }}, 'down')"
subtle
color="black"
sm
icon="arrow-down"
:aria-label="__('catalog.actions.move_down_named', ['name' => $name])"
/>
<label class="inline-flex min-h-6 cursor-pointer items-center gap-2 text-sm">
<input
type="checkbox"
id="active-{{ $level }}-{{ $id }}"
wire:click="toggleActive('{{ $level }}', {{ $id }})"
@checked($active)
aria-label="{{ __('catalog.actions.active_named', ['name' => $name]) }}"
class="size-4 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-800"
/>
<span aria-hidden="true">{{ __('catalog.actions.active') }}</span>
</label>
</div>
@@ -0,0 +1,29 @@
{{-- Work types of a service or of a service unit, with their row actions. --}}
@props([
'workTypes',
])
@if ($workTypes === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.no_work_types') }}</p>
@else
<ul class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($workTypes as $workType)
<li wire:key="work-type-{{ $workType->id }}" class="flex flex-wrap items-center justify-between gap-3 py-2">
<span class="break-words">
{{ $workType->name }}
@unless ($workType->isActive)
<span class="ml-2 text-sm">({{ __('catalog.inactive') }})</span>
@endunless
</span>
<x-catalog.item-actions
level="work_type"
:id="$workType->id"
:name="$workType->name"
:active="$workType->isActive"
:edit-url="route('catalog.work-types.edit', $workType->id)"
/>
</li>
@endforeach
</ul>
@endif
+4
View File
@@ -57,6 +57,10 @@
<nav aria-label="{{ __('layout.main_menu') }}" class="flex flex-1 flex-wrap items-center gap-1">
@include('partials.nav-item', ['route' => 'customers.index', 'pattern' => 'customers.*', 'label' => __('layout.customers')])
@can('catalog.manage')
@include('partials.nav-item', ['route' => 'catalog.index', 'pattern' => 'catalog.*', 'label' => __('layout.catalog')])
@endcan
@can('users.manage')
@include('partials.nav-item', ['route' => 'users.index', 'pattern' => 'users.*', 'label' => __('layout.users')])
@endcan
@@ -0,0 +1,58 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->management()->create());
});
it('has no accessibility issues on the catalog pages', function (string $page, string $device, string $colorScheme) {
$media = ServiceUnitModel::query()->where('name', 'Mediatuotanto')->sole();
WorkTypeModel::query()->where('name', 'animointi')->update(['is_active' => false]);
$workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole();
$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),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['catalog', 'new service unit', 'new service', 'edit work type'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('moves a row with the keyboard, keeping focus and announcing it', function () {
$marketing = ServiceUnitModel::query()->where('name', 'Markkinointi')->sole();
$button = '#move-up-service_unit-'.$marketing->id;
visit(route('catalog.index'))
->keys($button, 'Enter')
->assertSee('Markkinointi siirretty ylöspäin.')
->assertScript('document.activeElement.id', 'move-up-service_unit-'.$marketing->id)
->assertScript('document.querySelector("section h2").textContent.trim()', 'Markkinointi');
});
it('takes a row out of use with the keyboard', function () {
$workType = WorkTypeModel::query()->where('name', 'painotyö')->sole();
visit(route('catalog.index'))
->keys('#active-work_type-'.$workType->id, 'Space')
->assertSee('painotyö poistettu käytöstä.')
->assertSee('(Ei käytössä)')
->assertNoAccessibilityIssues(level: 2);
});
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace Tests\Fakes;
use App\Modules\Catalog\Domain\Contracts\ServiceRepository;
use App\Modules\Catalog\Domain\Entities\CatalogItem;
use App\Modules\Catalog\Domain\Entities\Service;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
class InMemoryServiceRepository implements ServiceRepository
{
/** @var array<int, Service> */
public array $items = [];
private int $nextId = 1;
public function findById(int $id): ?Service
{
return isset($this->items[$id]) ? clone $this->items[$id] : null;
}
public function save(Service $service): Service
{
$id = $service->id() ?? $this->nextId++;
$this->items[$id] = Service::reconstitute($id, $service->serviceUnitId(), $service->name(), $service->isActive(), $service->sortOrder());
return clone $this->items[$id];
}
public function isNameTaken(int $serviceUnitId, string $name, ?int $exceptId = null): bool
{
return self::nameTakenIn($this->siblings($serviceUnitId), $name, $exceptId);
}
public function nextSortOrder(int $serviceUnitId): int
{
return self::nextIn($this->siblings($serviceUnitId));
}
public function neighbour(Service $service, MoveDirection $direction): ?Service
{
return self::neighbourIn($this->siblings($service->serviceUnitId()), $service, $direction);
}
/**
* @return array<int, Service>
*/
private function siblings(int $serviceUnitId): array
{
return array_filter($this->items, fn (Service $service): bool => $service->serviceUnitId() === $serviceUnitId);
}
/**
* @template T of CatalogItem
*
* @param array<int, T> $siblings
* @return T|null
*/
private static function neighbourIn(array $siblings, CatalogItem $item, MoveDirection $direction): ?CatalogItem
{
$candidates = array_filter($siblings, fn (CatalogItem $sibling): bool => $direction === MoveDirection::Up
? $sibling->sortOrder() < $item->sortOrder()
: $sibling->sortOrder() > $item->sortOrder());
usort($candidates, fn (CatalogItem $a, CatalogItem $b): int => $direction === MoveDirection::Up
? $b->sortOrder() <=> $a->sortOrder()
: $a->sortOrder() <=> $b->sortOrder());
return isset($candidates[0]) ? clone $candidates[0] : null;
}
/**
* @param array<int, CatalogItem> $siblings
*/
private static function nameTakenIn(array $siblings, string $name, ?int $exceptId): bool
{
foreach ($siblings as $id => $sibling) {
if ($id !== $exceptId && mb_strtolower($sibling->name()->value) === mb_strtolower($name)) {
return true;
}
}
return false;
}
/**
* @param array<int, CatalogItem> $siblings
*/
private static function nextIn(array $siblings): int
{
return array_reduce($siblings, fn (int $max, CatalogItem $item): int => max($max, $item->sortOrder()), 0) + 1;
}
}
@@ -0,0 +1,85 @@
<?php
namespace Tests\Fakes;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Entities\CatalogItem;
use App\Modules\Catalog\Domain\Entities\ServiceUnit;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
class InMemoryServiceUnitRepository implements ServiceUnitRepository
{
/** @var array<int, ServiceUnit> */
public array $items = [];
private int $nextId = 1;
public function findById(int $id): ?ServiceUnit
{
return isset($this->items[$id]) ? clone $this->items[$id] : null;
}
public function save(ServiceUnit $serviceUnit): ServiceUnit
{
$id = $serviceUnit->id() ?? $this->nextId++;
$this->items[$id] = ServiceUnit::reconstitute($id, $serviceUnit->name(), $serviceUnit->isShared(), $serviceUnit->isActive(), $serviceUnit->sortOrder());
return clone $this->items[$id];
}
public function isNameTaken(string $name, ?int $exceptId = null): bool
{
return self::nameTakenIn($this->items, $name, $exceptId);
}
public function nextSortOrder(): int
{
return self::nextIn($this->items);
}
public function neighbour(ServiceUnit $serviceUnit, MoveDirection $direction): ?ServiceUnit
{
return self::neighbourIn($this->items, $serviceUnit, $direction);
}
/**
* @template T of CatalogItem
*
* @param array<int, T> $siblings
* @return T|null
*/
private static function neighbourIn(array $siblings, CatalogItem $item, MoveDirection $direction): ?CatalogItem
{
$candidates = array_filter($siblings, fn (CatalogItem $sibling): bool => $direction === MoveDirection::Up
? $sibling->sortOrder() < $item->sortOrder()
: $sibling->sortOrder() > $item->sortOrder());
usort($candidates, fn (CatalogItem $a, CatalogItem $b): int => $direction === MoveDirection::Up
? $b->sortOrder() <=> $a->sortOrder()
: $a->sortOrder() <=> $b->sortOrder());
return isset($candidates[0]) ? clone $candidates[0] : null;
}
/**
* @param array<int, CatalogItem> $siblings
*/
private static function nameTakenIn(array $siblings, string $name, ?int $exceptId): bool
{
foreach ($siblings as $id => $sibling) {
if ($id !== $exceptId && mb_strtolower($sibling->name()->value) === mb_strtolower($name)) {
return true;
}
}
return false;
}
/**
* @param array<int, CatalogItem> $siblings
*/
private static function nextIn(array $siblings): int
{
return array_reduce($siblings, fn (int $max, CatalogItem $item): int => max($max, $item->sortOrder()), 0) + 1;
}
}
@@ -0,0 +1,93 @@
<?php
namespace Tests\Fakes;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Entities\CatalogItem;
use App\Modules\Catalog\Domain\Entities\WorkType;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
class InMemoryWorkTypeRepository implements WorkTypeRepository
{
/** @var array<int, WorkType> */
public array $items = [];
private int $nextId = 1;
public function findById(int $id): ?WorkType
{
return isset($this->items[$id]) ? clone $this->items[$id] : null;
}
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());
return clone $this->items[$id];
}
public function isNameTaken(int $serviceUnitId, ?int $serviceId, string $name, ?int $exceptId = null): bool
{
return self::nameTakenIn($this->siblings($serviceUnitId, $serviceId), $name, $exceptId);
}
public function nextSortOrder(int $serviceUnitId, ?int $serviceId): int
{
return self::nextIn($this->siblings($serviceUnitId, $serviceId));
}
public function neighbour(WorkType $workType, MoveDirection $direction): ?WorkType
{
return self::neighbourIn($this->siblings($workType->serviceUnitId(), $workType->serviceId()), $workType, $direction);
}
/**
* @return array<int, WorkType>
*/
private function siblings(int $serviceUnitId, ?int $serviceId): array
{
return array_filter($this->items, fn (WorkType $workType): bool => $workType->serviceUnitId() === $serviceUnitId && $workType->serviceId() === $serviceId);
}
/**
* @template T of CatalogItem
*
* @param array<int, T> $siblings
* @return T|null
*/
private static function neighbourIn(array $siblings, CatalogItem $item, MoveDirection $direction): ?CatalogItem
{
$candidates = array_filter($siblings, fn (CatalogItem $sibling): bool => $direction === MoveDirection::Up
? $sibling->sortOrder() < $item->sortOrder()
: $sibling->sortOrder() > $item->sortOrder());
usort($candidates, fn (CatalogItem $a, CatalogItem $b): int => $direction === MoveDirection::Up
? $b->sortOrder() <=> $a->sortOrder()
: $a->sortOrder() <=> $b->sortOrder());
return isset($candidates[0]) ? clone $candidates[0] : null;
}
/**
* @param array<int, CatalogItem> $siblings
*/
private static function nameTakenIn(array $siblings, string $name, ?int $exceptId): bool
{
foreach ($siblings as $id => $sibling) {
if ($id !== $exceptId && mb_strtolower($sibling->name()->value) === mb_strtolower($name)) {
return true;
}
}
return false;
}
/**
* @param array<int, CatalogItem> $siblings
*/
private static function nextIn(array $siblings): int
{
return array_reduce($siblings, fn (int $max, CatalogItem $item): int => max($max, $item->sortOrder()), 0) + 1;
}
}
@@ -0,0 +1,119 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->management()->create());
$this->unit = fn (string $name) => ServiceUnitModel::query()->where('name', $name)->sole();
});
it('has the starting catalog from the specification', function () {
$tree = app(CatalogQueries::class)->tree();
$media = $tree[0];
expect(array_map(fn ($node) => $node->serviceUnit->name, $tree))->toBe([
'Mediatuotanto', 'Markkinointi', 'Painotuotanto', 'Ylläpitopalvelut', 'Verkkosivut', 'Ohjelmistot', 'Kuluttajapalvelut', 'Kaikille yhteiset',
])
->and(array_map(fn ($node) => $node->service->name, $media->services))->toBe(['Videotuotanto', 'Valokuvaus', 'Äänituotanto'])
->and(array_map(fn ($workType) => $workType->name, $media->services[0]->workTypes))->toBe(['videokuvaus', 'kuvausassistentti', 'editointi', 'animointi', '3D-mallinnus'])
->and(end($tree)->serviceUnit->isShared)->toBeTrue()
->and(WorkTypeModel::query()->count())->toBe(29);
});
it('offers the work types of the chosen units and the shared ones, but not inactive ones', function () {
$marketing = ($this->unit)('Markkinointi');
WorkTypeModel::query()->where('name', 'kampanjatyö')->update(['is_active' => false]);
$nodes = app(CatalogQueries::class)->activeWorkTypesFor([$marketing->id]);
expect(array_map(fn ($node) => $node->serviceUnit->name, $nodes))->toBe(['Markkinointi', 'Kaikille yhteiset'])
->and(array_map(fn ($workType) => $workType->name, $nodes[0]->workTypes))->toBe(['graafinen työ', 'julkaisutyö'])
->and(array_map(fn ($unit) => $unit->name, app(CatalogQueries::class)->activeServiceUnits()))->not->toContain('Kaikille yhteiset');
});
it('shows the catalog page to admins and management only', function (string $role, int $status) {
$this->actingAs(User::factory()->{$role}()->create())->get(route('catalog.index'))->assertStatus($status);
})->with([
'admin' => ['admin', 200],
'management' => ['management', 200],
'employee' => ['employee', 403],
'intern' => ['intern', 403],
'subcontractor' => ['subcontractor', 403],
]);
it('shows the menu link only to those who may manage the catalog', function () {
$this->get(route('customers.index'))->assertSee('Pohjatiedot');
$this->actingAs(User::factory()->create())->get(route('customers.index'))->assertDontSee('Pohjatiedot');
});
it('adds a service unit, a service and a work type', function () {
Livewire::test('catalog::service-unit-form')
->set('form.name', 'Tapahtumat')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('catalog.index'));
$unit = ($this->unit)('Tapahtumat');
Livewire::test('catalog::service-form', ['serviceUnit' => $unit->id])
->set('form.name', 'Messut')
->call('save')
->assertHasNoErrors();
$service = ServiceModel::query()->where('name', 'Messut')->sole();
Livewire::test('catalog::work-type-form', ['serviceUnit' => $unit->id])
->set('form.name', 'osastosuunnittelu')
->set('form.service_id', (string) $service->id)
->call('save')
->assertHasNoErrors();
expect(WorkTypeModel::query()->where('name', 'osastosuunnittelu')->sole()->service_id)->toBe($service->id);
});
it('shows a taken name as a Finnish field error', function () {
Livewire::test('catalog::service-unit-form')
->set('form.name', 'markkinointi')
->call('save')
->assertHasErrors(['form.name'])
->assertSee('Samalla tasolla on jo tämänniminen rivi.');
});
it('moves and deactivates rows on the catalog page', function () {
$marketing = ($this->unit)('Markkinointi');
Livewire::test('catalog::index')
->call('move', 'service_unit', $marketing->id, 'up')
->assertSee('Markkinointi siirretty ylöspäin.')
->call('move', 'service_unit', $marketing->id, 'up')
->assertSee('Markkinointi on jo ensimmäisenä.')
->call('toggleActive', 'service_unit', $marketing->id)
->assertSee('Markkinointi poistettu käytöstä.')
->set('showInactive', false)
->assertDontSee('graafinen työ');
expect($marketing->fresh()->sort_order)->toBe(1)
->and($marketing->fresh()->is_active)->toBeFalse();
});
it('returns 404 for unknown items and does not add services to the shared unit', function () {
$shared = ($this->unit)('Kaikille yhteiset');
$this->get(route('catalog.service-units.edit', 999))->assertNotFound();
$this->get(route('catalog.work-types.edit', 999))->assertNotFound();
$this->get(route('catalog.services.create', $shared->id))->assertNotFound();
});
it('does not let the edited item be changed in the browser', function () {
Livewire::test('catalog::work-type-form', ['serviceUnit' => ($this->unit)('Markkinointi')->id])
->set('workTypeId', 1);
})->throws(CannotUpdateLockedPropertyException::class);
@@ -0,0 +1,99 @@
<?php
use App\Modules\Catalog\Application\UseCases\AddService;
use App\Modules\Catalog\Application\UseCases\AddServiceUnit;
use App\Modules\Catalog\Application\UseCases\AddWorkType;
use App\Modules\Catalog\Application\UseCases\MoveCatalogItem;
use App\Modules\Catalog\Application\UseCases\RenameCatalogItem;
use App\Modules\Catalog\Application\UseCases\SetCatalogItemActive;
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\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\CatalogNameTaken;
use App\Modules\Catalog\Domain\Exceptions\ServiceNotInUnit;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryServiceRepository;
use Tests\Fakes\InMemoryServiceUnitRepository;
use Tests\Fakes\InMemoryWorkTypeRepository;
beforeEach(function () {
$this->units = new InMemoryServiceUnitRepository;
$this->services = new InMemoryServiceRepository;
$this->workTypes = new InMemoryWorkTypeRepository;
$transactions = new FakeTransactionManager;
$this->addUnit = new AddServiceUnit($this->units, $transactions);
$this->addService = new AddService($this->units, $this->services, $transactions);
$this->addWorkType = new AddWorkType($this->units, $this->services, $this->workTypes, $transactions);
$this->rename = new RenameCatalogItem($this->units, $this->services, $transactions);
$this->updateWorkType = new UpdateWorkType($this->units, $this->services, $this->workTypes, $transactions);
$this->setActive = new SetCatalogItemActive($this->units, $this->services, $this->workTypes, $transactions);
$this->move = new MoveCatalogItem($this->units, $this->services, $this->workTypes, $transactions);
$this->media = $this->addUnit->execute('Mediatuotanto');
$this->marketing = $this->addUnit->execute('Markkinointi');
$this->video = $this->addService->execute($this->media, 'Videotuotanto');
$this->photo = $this->addService->execute($this->media, 'Valokuvaus');
});
it('adds items last among their siblings', function () {
expect($this->units->findById($this->marketing)?->sortOrder())->toBe(2)
->and($this->services->findById($this->photo)?->sortOrder())->toBe(2);
});
it('rejects a name already used on the same level, ignoring case', function () {
$this->addWorkType->execute($this->media, $this->video, 'editointi');
$this->addWorkType->execute($this->media, $this->video, 'Editointi');
})->throws(CatalogNameTaken::class);
it('allows the same work type name under another service or unit', function () {
$this->addWorkType->execute($this->media, $this->video, 'editointi');
$this->addWorkType->execute($this->media, $this->photo, 'editointi');
$this->addWorkType->execute($this->marketing, null, 'editointi');
expect($this->workTypes->items)->toHaveCount(3);
});
it('rejects a service of another unit', function () {
$this->addWorkType->execute($this->marketing, $this->video, 'editointi');
})->throws(ServiceNotInUnit::class);
it('renames and rejects a taken name', function () {
$this->rename->execute(CatalogLevel::Service, $this->video, 'Video');
expect($this->services->findById($this->video)?->name()->value)->toBe('Video')
->and(fn () => $this->rename->execute(CatalogLevel::ServiceUnit, $this->media, 'markkinointi'))->toThrow(CatalogNameTaken::class);
});
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');
$workType = $this->workTypes->findById($editing);
expect($workType?->serviceId())->toBe($this->photo)
->and($workType?->sortOrder())->toBe(2);
});
it('moves items up and down, and does nothing at either end', function () {
expect($this->move->execute(CatalogLevel::ServiceUnit, $this->marketing, MoveDirection::Up))->toBeTrue()
->and($this->units->findById($this->marketing)?->sortOrder())->toBe(1)
->and($this->units->findById($this->media)?->sortOrder())->toBe(2)
->and($this->move->execute(CatalogLevel::ServiceUnit, $this->marketing, MoveDirection::Up))->toBeFalse()
->and($this->move->execute(CatalogLevel::Service, $this->photo, MoveDirection::Down))->toBeFalse();
});
it('takes items out of use and back', function () {
$this->setActive->execute(CatalogLevel::Service, $this->video, false);
expect($this->services->findById($this->video)?->isActive())->toBeFalse();
$this->setActive->execute(CatalogLevel::Service, $this->video, true);
expect($this->services->findById($this->video)?->isActive())->toBeTrue();
});
it('fails for an unknown item', function () {
$this->setActive->execute(CatalogLevel::WorkType, 999, false);
})->throws(CatalogItemNotFound::class);
@@ -0,0 +1,45 @@
<?php
use App\Modules\Catalog\Domain\Entities\Service;
use App\Modules\Catalog\Domain\Entities\ServiceUnit;
use App\Modules\Catalog\Domain\Entities\WorkType;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\ServiceNotInUnit;
use App\Modules\Catalog\Domain\Exceptions\SharedUnitHasNoServices;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
it('normalises a catalog name and rejects an empty or too long one', function () {
expect((new CatalogName(' 3D mallinnus '))->value)->toBe('3D mallinnus')
->and(fn () => new CatalogName(' '))->toThrow(InvalidCatalogName::class)
->and(fn () => new CatalogName(str_repeat('a', 101)))->toThrow(InvalidCatalogName::class);
});
it('gives the shared unit no services', function () {
$shared = ServiceUnit::reconstitute(1, new CatalogName('Kaikille yhteiset'), true, true, 1);
Service::create($shared, new CatalogName('Palvelu'), 1);
})->throws(SharedUnitHasNoServices::class);
it('puts a work type only under a service of its own unit', function () {
$media = ServiceUnit::reconstitute(1, new CatalogName('Mediatuotanto'), false, true, 1);
$marketing = ServiceUnit::reconstitute(2, new CatalogName('Markkinointi'), false, true, 2);
$video = Service::reconstitute(10, 1, new CatalogName('Videotuotanto'), true, 1);
expect(WorkType::create($media, $video, new CatalogName('editointi'), 1)->serviceId())->toBe(10)
->and(fn () => WorkType::create($marketing, $video, new CatalogName('editointi'), 1))->toThrow(ServiceNotInUnit::class);
});
it('deactivates, activates and swaps order', function () {
$first = ServiceUnit::reconstitute(1, new CatalogName('A'), false, true, 1);
$second = ServiceUnit::reconstitute(2, new CatalogName('B'), false, true, 2);
$first->deactivate();
$first->swapOrderWith($second);
expect($first->isActive())->toBeFalse()
->and($first->sortOrder())->toBe(2)
->and($second->sortOrder())->toBe(1);
$first->activate();
expect($first->isActive())->toBeTrue();
});