diff --git a/CLAUDE.md b/CLAUDE.md index bdaf1db..66637b2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project -An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users` 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: ``, ``), 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` (`::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////` for classes, `make:test --pest [--unit] Modules//Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files. diff --git a/app/Modules/Catalog/Application/Contracts/CatalogQueries.php b/app/Modules/Catalog/Application/Contracts/CatalogQueries.php new file mode 100644 index 0000000..5e97e3b --- /dev/null +++ b/app/Modules/Catalog/Application/Contracts/CatalogQueries.php @@ -0,0 +1,53 @@ + + */ + public function tree(bool $includeInactive = true): array; + + /** + * Active service units a customer job can be assigned to (not the shared unit). + * + * @return list + */ + public function activeServiceUnits(): array; + + /** + * Active work types of the given service units plus the shared work + * types, grouped by unit and service. + * + * @param list $serviceUnitIds + * @return list + */ + 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 + */ + public function servicesOf(int $serviceUnitId): array; +} diff --git a/app/Modules/Catalog/Application/DTOs/ServiceNode.php b/app/Modules/Catalog/Application/DTOs/ServiceNode.php new file mode 100644 index 0000000..b455a16 --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/ServiceNode.php @@ -0,0 +1,19 @@ + $workTypes + */ + public function __construct( + public ServiceSummary $service, + public array $workTypes, + ) {} +} diff --git a/app/Modules/Catalog/Application/DTOs/ServiceSummary.php b/app/Modules/Catalog/Application/DTOs/ServiceSummary.php new file mode 100644 index 0000000..9aa0ef3 --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/ServiceSummary.php @@ -0,0 +1,15 @@ + $services + * @param list $workTypes Work types under no service. + */ + public function __construct( + public ServiceUnitSummary $serviceUnit, + public array $services, + public array $workTypes, + ) {} +} diff --git a/app/Modules/Catalog/Application/DTOs/ServiceUnitSummary.php b/app/Modules/Catalog/Application/DTOs/ServiceUnitSummary.php new file mode 100644 index 0000000..7211730 --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/ServiceUnitSummary.php @@ -0,0 +1,15 @@ +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(); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/AddServiceUnit.php b/app/Modules/Catalog/Application/UseCases/AddServiceUnit.php new file mode 100644 index 0000000..950f8f8 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/AddServiceUnit.php @@ -0,0 +1,39 @@ +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(); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/AddWorkType.php b/app/Modules/Catalog/Application/UseCases/AddWorkType.php new file mode 100644 index 0000000..3bfa553 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/AddWorkType.php @@ -0,0 +1,53 @@ +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(); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/MoveCatalogItem.php b/app/Modules/Catalog/Application/UseCases/MoveCatalogItem.php new file mode 100644 index 0000000..9733d9f --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/MoveCatalogItem.php @@ -0,0 +1,83 @@ +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; + } +} diff --git a/app/Modules/Catalog/Application/UseCases/RenameCatalogItem.php b/app/Modules/Catalog/Application/UseCases/RenameCatalogItem.php new file mode 100644 index 0000000..c4274a4 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/RenameCatalogItem.php @@ -0,0 +1,68 @@ +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); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/SetCatalogItemActive.php b/app/Modules/Catalog/Application/UseCases/SetCatalogItemActive.php new file mode 100644 index 0000000..81e5acd --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/SetCatalogItemActive.php @@ -0,0 +1,58 @@ +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; + } +} diff --git a/app/Modules/Catalog/Application/UseCases/UpdateWorkType.php b/app/Modules/Catalog/Application/UseCases/UpdateWorkType.php new file mode 100644 index 0000000..c32b43c --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/UpdateWorkType.php @@ -0,0 +1,60 @@ +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); + }); + } +} diff --git a/app/Modules/Catalog/Domain/Contracts/ServiceRepository.php b/app/Modules/Catalog/Domain/Contracts/ServiceRepository.php new file mode 100644 index 0000000..8abd7b6 --- /dev/null +++ b/app/Modules/Catalog/Domain/Contracts/ServiceRepository.php @@ -0,0 +1,36 @@ +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]; + } +} diff --git a/app/Modules/Catalog/Domain/Entities/Service.php b/app/Modules/Catalog/Domain/Entities/Service.php new file mode 100644 index 0000000..3108f5b --- /dev/null +++ b/app/Modules/Catalog/Domain/Entities/Service.php @@ -0,0 +1,42 @@ +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; + } +} diff --git a/app/Modules/Catalog/Domain/Entities/ServiceUnit.php b/app/Modules/Catalog/Domain/Entities/ServiceUnit.php new file mode 100644 index 0000000..8d40943 --- /dev/null +++ b/app/Modules/Catalog/Domain/Entities/ServiceUnit.php @@ -0,0 +1,35 @@ +shared; + } +} diff --git a/app/Modules/Catalog/Domain/Entities/WorkType.php b/app/Modules/Catalog/Domain/Entities/WorkType.php new file mode 100644 index 0000000..d595bf5 --- /dev/null +++ b/app/Modules/Catalog/Domain/Entities/WorkType.php @@ -0,0 +1,76 @@ +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; + } + } +} diff --git a/app/Modules/Catalog/Domain/Enums/CatalogLevel.php b/app/Modules/Catalog/Domain/Enums/CatalogLevel.php new file mode 100644 index 0000000..b1d4685 --- /dev/null +++ b/app/Modules/Catalog/Domain/Enums/CatalogLevel.php @@ -0,0 +1,15 @@ + (service) > work type. + */ +enum CatalogLevel: string +{ + case ServiceUnit = 'service_unit'; + case Service = 'service'; + case WorkType = 'work_type'; +} diff --git a/app/Modules/Catalog/Domain/Enums/MoveDirection.php b/app/Modules/Catalog/Domain/Enums/MoveDirection.php new file mode 100644 index 0000000..c3f921a --- /dev/null +++ b/app/Modules/Catalog/Domain/Enums/MoveDirection.php @@ -0,0 +1,11 @@ +value} {$id} was not found."); + } +} diff --git a/app/Modules/Catalog/Domain/Exceptions/CatalogNameTaken.php b/app/Modules/Catalog/Domain/Exceptions/CatalogNameTaken.php new file mode 100644 index 0000000..b52bee7 --- /dev/null +++ b/app/Modules/Catalog/Domain/Exceptions/CatalogNameTaken.php @@ -0,0 +1,15 @@ + self::MAX_LENGTH) { + throw new InvalidCatalogName; + } + + $this->value = $value; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ServiceModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ServiceModel.php new file mode 100644 index 0000000..51e7345 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ServiceModel.php @@ -0,0 +1,40 @@ + */ + use HasFactory; + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'service_unit_id' => 'integer', + 'is_active' => 'boolean', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ServiceUnitModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ServiceUnitModel.php new file mode 100644 index 0000000..936bbe3 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/ServiceUnitModel.php @@ -0,0 +1,40 @@ + */ + use HasFactory; + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'is_shared' => 'boolean', + 'is_active' => 'boolean', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkTypeModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkTypeModel.php new file mode 100644 index 0000000..480570d --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkTypeModel.php @@ -0,0 +1,42 @@ + */ + use HasFactory; + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'service_unit_id' => 'integer', + 'service_id' => 'integer', + 'is_active' => 'boolean', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentCatalogQueries.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentCatalogQueries.php new file mode 100644 index 0000000..e1f66cf --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentCatalogQueries.php @@ -0,0 +1,149 @@ +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 $units + * @return list + */ + 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> $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> $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|null $models + * @return list + */ + 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); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentServiceRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentServiceRepository.php new file mode 100644 index 0000000..7653d89 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentServiceRepository.php @@ -0,0 +1,63 @@ +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); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentServiceUnitRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentServiceUnitRepository.php new file mode 100644 index 0000000..e946181 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentServiceUnitRepository.php @@ -0,0 +1,61 @@ +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); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkTypeRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkTypeRepository.php new file mode 100644 index 0000000..8008603 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkTypeRepository.php @@ -0,0 +1,84 @@ +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 + */ + 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, + ); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php b/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php new file mode 100644 index 0000000..818e731 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php @@ -0,0 +1,49 @@ + + */ + 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)); + } +} diff --git a/app/Modules/Catalog/Presentation/Livewire/Forms/CatalogItemForm.php b/app/Modules/Catalog/Presentation/Livewire/Forms/CatalogItemForm.php new file mode 100644 index 0000000..962b8e7 --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/Forms/CatalogItemForm.php @@ -0,0 +1,74 @@ +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> + */ + protected function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:100'], + 'service_id' => ['nullable', 'integer'], + ]; + } + + /** + * @return array + */ + 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'), + ]; + } +} diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php new file mode 100644 index 0000000..128b56d --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php @@ -0,0 +1,216 @@ +catalogQueries = $catalogQueries; + } + + public function mount(): void + { + $this->authorize('catalog.manage'); + } + + /** + * @return list + */ + #[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; + } +}; +?> + +
+
+

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

+ + +
+ +

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

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

{{ $statusMessage }}

+ + @foreach ($this->tree as $node) + @php($unit = $node->serviceUnit) + +
+
+

+ {{ $unit->name }} + @unless ($unit->isActive) + ({{ __('catalog.inactive') }}) + @endunless +

+ + +
+ + @if ($unit->isShared) +

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

+ @endif + + @foreach ($node->services as $serviceNode) + @php($service = $serviceNode->service) + +
+
+

+ {{ $service->name }} + @unless ($service->isActive) + ({{ __('catalog.inactive') }}) + @endunless +

+ + +
+ + +
+ @endforeach + + @if ($node->workTypes !== [] || $node->services === []) + + @endif + +
+ @unless ($unit->isShared) + + @endunless + +
+
+ @endforeach +
diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡service-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡service-form.blade.php new file mode 100644 index 0000000..19ae175 --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡service-form.blade.php @@ -0,0 +1,104 @@ +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); + } +}; +?> + +
+
+

{{ $this->heading() }}

+ @if ($unitName !== '') +

{{ __('catalog.fields.service_unit') }}: {{ $unitName }}

+ @endif +
+ +
+ + +
+ + +
+ +
diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡service-unit-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡service-unit-form.blade.php new file mode 100644 index 0000000..3586269 --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡service-unit-form.blade.php @@ -0,0 +1,93 @@ +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()); + } +}; +?> + +
+
+

{{ $this->heading() }}

+ +
+ +
+ + +
+ + +
+ +
diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡work-type-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡work-type-form.blade.php new file mode 100644 index 0000000..d9bcb95 --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡work-type-form.blade.php @@ -0,0 +1,135 @@ +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 + */ + #[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); + } +}; +?> + +
+
+

{{ $this->heading() }}

+ @if ($unitName !== '') +

{{ __('catalog.fields.service_unit') }}: {{ $unitName }}

+ @endif +
+ +
+ + + @if ($this->services !== []) + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->services as $service) + + @endforeach + + @endif + +
+ + +
+ +
diff --git a/app/Modules/Catalog/Presentation/Routes/web.php b/app/Modules/Catalog/Presentation/Routes/web.php new file mode 100644 index 0000000..8d2b31b --- /dev/null +++ b/app/Modules/Catalog/Presentation/Routes/web.php @@ -0,0 +1,29 @@ +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'); + }); diff --git a/bootstrap/providers.php b/bootstrap/providers.php index e8402d3..5b7bb22 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -1,5 +1,6 @@ + */ +class ServiceFactory extends Factory +{ + protected $model = ServiceModel::class; + + /** + * @return array + */ + 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), + ]; + } +} diff --git a/database/factories/ServiceUnitFactory.php b/database/factories/ServiceUnitFactory.php new file mode 100644 index 0000000..d4e687b --- /dev/null +++ b/database/factories/ServiceUnitFactory.php @@ -0,0 +1,32 @@ + + */ +class ServiceUnitFactory extends Factory +{ + protected $model = ServiceUnitModel::class; + + /** + * @return array + */ + 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]); + } +} diff --git a/database/factories/WorkTypeFactory.php b/database/factories/WorkTypeFactory.php new file mode 100644 index 0000000..d7ed425 --- /dev/null +++ b/database/factories/WorkTypeFactory.php @@ -0,0 +1,34 @@ + + */ +class WorkTypeFactory extends Factory +{ + protected $model = WorkTypeModel::class; + + /** + * @return array + */ + 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]); + } +} diff --git a/database/migrations/2026_11_23_161730_create_catalog_tables.php b/database/migrations/2026_11_23_161730_create_catalog_tables.php new file mode 100644 index 0000000..8a760e9 --- /dev/null +++ b/database/migrations/2026_11_23_161730_create_catalog_tables.php @@ -0,0 +1,59 @@ + 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'); + } +}; diff --git a/database/migrations/2026_11_23_161731_insert_initial_catalog.php b/database/migrations/2026_11_23_161731_insert_initial_catalog.php new file mode 100644 index 0000000..88d632e --- /dev/null +++ b/database/migrations/2026_11_23_161731_insert_initial_catalog.php @@ -0,0 +1,95 @@ + [work types]; others list work + * types directly. The last unit is the shared one. + * + * @var array>> + */ + 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, + ]); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 9a0a9dc..92a9daa 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -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. diff --git a/lang/fi/catalog.php b/lang/fi/catalog.php new file mode 100644 index 0000000..689dfa4 --- /dev/null +++ b/lang/fi/catalog.php @@ -0,0 +1,69 @@ + '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.', + ], +]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index cf7a13e..450dfd7 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -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', diff --git a/resources/views/components/catalog/item-actions.blade.php b/resources/views/components/catalog/item-actions.blade.php new file mode 100644 index 0000000..c1ad093 --- /dev/null +++ b/resources/views/components/catalog/item-actions.blade.php @@ -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', +]) + +
+ + + + + + + +
diff --git a/resources/views/components/catalog/work-type-list.blade.php b/resources/views/components/catalog/work-type-list.blade.php new file mode 100644 index 0000000..4e148c6 --- /dev/null +++ b/resources/views/components/catalog/work-type-list.blade.php @@ -0,0 +1,29 @@ +{{-- Work types of a service or of a service unit, with their row actions. --}} +@props([ + 'workTypes', +]) + +@if ($workTypes === []) +

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

+@else +
    + @foreach ($workTypes as $workType) +
  • + + {{ $workType->name }} + @unless ($workType->isActive) + ({{ __('catalog.inactive') }}) + @endunless + + + +
  • + @endforeach +
+@endif diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 0a84cc2..c3d4391 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -57,6 +57,10 @@