diff --git a/CLAUDE.md b/CLAUDE.md index 9ad644e..a0ee723 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project -An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks, task checklists) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). +An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks, task checklists, and the task calendar `jobs::calendar`: a Gantt of tasks per person where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings`, split over working days with the rest moved to the next working day past the daily maximum `jobs.daily_capacity_hours`) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` 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. @@ -24,6 +24,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - 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`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, `billing.manage`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP. +- **Holidays** are Shared: `Shared\Application\UseCases\HolidayCalendar` gives the Finnish public holidays (`FinnishHolidays`, calculated) minus those the admin took out of use plus company days off (`holiday_overrides`), edited on `shared::holidays` (`/settings/holidays`, gate `settings.manage`). - **Company details** (name, business ID, address, phone, email) are kept by `Shared\Application\UseCases\CompanyDetailsStore` in the settings (`shared.company_*`) and edited by the admin on `shared::company` (`/settings/company`, gate `settings.manage`). `BusinessId` (Y-tunnus with check digit) is a Shared value object. - **PDFs** use `barryvdh/laravel-dompdf` with a plain Blade view (no Tailwind; DejaVu Sans), streamed inline: see the quick sale receipt `Sales\Presentation\Http\Controllers\ShowReceipt` and `Sales/Presentation/Views/receipt.blade.php` (view namespace `sales-views`). - **Security headers** (`X-Frame-Options`, `frame-ancestors`, `nosniff`, `Referrer-Policy`, HSTS over HTTPS) come from the global `Shared\Presentation\Http\Middleware\SetSecurityHeaders`, pushed in `SharedServiceProvider`. No full CSP: Alpine/Livewire need `unsafe-eval`. diff --git a/app/Modules/Billing/Infrastructure/CustomerReferencesFromBilling.php b/app/Modules/Billing/Infrastructure/CustomerReferencesFromBilling.php new file mode 100644 index 0000000..367ca25 --- /dev/null +++ b/app/Modules/Billing/Infrastructure/CustomerReferencesFromBilling.php @@ -0,0 +1,18 @@ +where('customer_id', $customerId)->exists() + || DB::table('billing_invoice_jobs')->where('customer_id', $customerId)->exists(); + } +} diff --git a/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php b/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php index 78b0c10..8ca48df 100644 --- a/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php +++ b/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php @@ -10,6 +10,7 @@ use App\Modules\Billing\Application\Contracts\BillingJobs; use App\Modules\Billing\Application\Contracts\BillingPrices; use App\Modules\Billing\Application\Contracts\BillingQueries; use App\Modules\Billing\Domain\Contracts\BillingExportRepository; +use App\Modules\Billing\Infrastructure\CustomerReferencesFromBilling; use App\Modules\Billing\Infrastructure\CustomersForBilling; use App\Modules\Billing\Infrastructure\ExpensesForBilling; use App\Modules\Billing\Infrastructure\HoursForBilling; @@ -17,6 +18,7 @@ use App\Modules\Billing\Infrastructure\JobsForBilling; use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBillingExportRepository; use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBillingQueries; use App\Modules\Billing\Infrastructure\PricesForBilling; +use App\Modules\Customers\Application\Contracts\CustomerReferences; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; use Livewire\Livewire; @@ -41,6 +43,12 @@ class BillingServiceProvider extends ServiceProvider BillingCustomers::class => CustomersForBilling::class, ]; + public function register(): void + { + // A customer with invoices cannot be removed. + $this->app->tag([CustomerReferencesFromBilling::class], CustomerReferences::TAG); + } + public function boot(): void { $presentationPath = dirname(__DIR__, 2).'/Presentation'; diff --git a/app/Modules/Catalog/Application/Contracts/WorkflowTemplateQueries.php b/app/Modules/Catalog/Application/Contracts/WorkflowTemplateQueries.php new file mode 100644 index 0000000..81f2760 --- /dev/null +++ b/app/Modules/Catalog/Application/Contracts/WorkflowTemplateQueries.php @@ -0,0 +1,34 @@ + + */ + public function all(): array; + + public function find(int $id): ?WorkflowTemplateDetails; + + /** + * Active templates whose work type is in use in the given service units + * or in the shared unit, in catalog order and by name. + * + * @param list $serviceUnitIds + * @return list + */ + public function activeFor(array $serviceUnitIds): array; +} diff --git a/app/Modules/Catalog/Application/DTOs/WorkflowStepData.php b/app/Modules/Catalog/Application/DTOs/WorkflowStepData.php new file mode 100644 index 0000000..ce3593a --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/WorkflowStepData.php @@ -0,0 +1,31 @@ + $steps + */ + public function __construct( + public string $name, + public int $workTypeId, + public array $steps, + ) {} +} diff --git a/app/Modules/Catalog/Application/DTOs/WorkflowTemplateDetails.php b/app/Modules/Catalog/Application/DTOs/WorkflowTemplateDetails.php new file mode 100644 index 0000000..66c374e --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/WorkflowTemplateDetails.php @@ -0,0 +1,24 @@ + $steps + */ + public function __construct( + public int $id, + public string $name, + public int $workTypeId, + public string $workTypeName, + public int $serviceUnitId, + public bool $isActive, + public array $steps, + ) {} +} diff --git a/app/Modules/Catalog/Application/DTOs/WorkflowTemplateSummary.php b/app/Modules/Catalog/Application/DTOs/WorkflowTemplateSummary.php new file mode 100644 index 0000000..f8b3993 --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/WorkflowTemplateSummary.php @@ -0,0 +1,22 @@ + $input + * @return list + * + * @throws InvalidWorkflowStepTitle with the index of the step + */ + public function build(array $input): array + { + $steps = []; + + foreach ($input as $index => $step) { + try { + $title = new WorkflowStepTitle($step->title); + } catch (InvalidWorkflowStepTitle) { + throw new InvalidWorkflowStepTitle($index); + } + + $steps[] = new WorkflowStep($title, $step->description, $step->workTypeId); + } + + return $steps; + } + + /** + * A step's own work type must be in use and belong to the template work + * type's unit or to the shared unit. A work type the template already + * uses stays allowed after it is taken out of use. + * + * @param list $steps + * @param list $currentSteps + * + * @throws WorkflowStepWorkTypeNotAllowed + */ + public function checkWorkTypes(WorkType $templateWorkType, array $steps, array $currentSteps = []): void + { + $currentIds = array_map(fn (WorkflowStep $step): ?int => $step->workTypeId, $currentSteps); + + foreach ($steps as $index => $step) { + if ($step->workTypeId === null || $step->workTypeId === $templateWorkType->id()) { + continue; + } + + $workType = $this->workTypes->findById($step->workTypeId); + + if ($workType === null + || (! $workType->isActive() && ! in_array($workType->id(), $currentIds, true)) + || ! $this->sameOrSharedUnit($templateWorkType, $workType)) { + throw new WorkflowStepWorkTypeNotAllowed($index); + } + } + } + + private function sameOrSharedUnit(WorkType $templateWorkType, WorkType $workType): bool + { + return $workType->serviceUnitId() === $templateWorkType->serviceUnitId() + || ($this->serviceUnits->findById($workType->serviceUnitId())?->isShared() ?? false); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/AddWorkflowTemplate.php b/app/Modules/Catalog/Application/UseCases/AddWorkflowTemplate.php new file mode 100644 index 0000000..e0fbd78 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/AddWorkflowTemplate.php @@ -0,0 +1,64 @@ +name); + $steps = $this->stepBuilder->build($data->steps); + $template = WorkflowTemplate::create($data->workTypeId, $name, $steps); + + return $this->transactions->run(function () use ($data, $name, $steps, $template): int { + $workType = $this->workTypes->findById($data->workTypeId); + + if ($workType === null || ! $workType->isActive()) { + throw new CatalogItemNotFound(CatalogLevel::WorkType, $data->workTypeId); + } + + if ($this->templates->isNameTaken($data->workTypeId, $name->value)) { + throw new WorkflowTemplateNameTaken; + } + + $this->stepBuilder->checkWorkTypes($workType, $steps); + + return (int) $this->templates->save($template)->id(); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/SetWorkflowTemplateActive.php b/app/Modules/Catalog/Application/UseCases/SetWorkflowTemplateActive.php new file mode 100644 index 0000000..1132910 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/SetWorkflowTemplateActive.php @@ -0,0 +1,34 @@ +transactions->run(function () use ($templateId, $active): void { + $template = $this->templates->findById($templateId) ?? throw new WorkflowTemplateNotFound($templateId); + + $active ? $template->activate() : $template->deactivate(); + $this->templates->save($template); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/UpdateWorkflowTemplate.php b/app/Modules/Catalog/Application/UseCases/UpdateWorkflowTemplate.php new file mode 100644 index 0000000..f569439 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/UpdateWorkflowTemplate.php @@ -0,0 +1,68 @@ +name); + $steps = $this->stepBuilder->build($data->steps); + + $this->transactions->run(function () use ($templateId, $data, $name, $steps): void { + $template = $this->templates->findById($templateId) ?? throw new WorkflowTemplateNotFound($templateId); + $workType = $this->workTypes->findById($data->workTypeId); + $workTypeChanged = $data->workTypeId !== $template->workTypeId(); + + if ($workType === null || ($workTypeChanged && ! $workType->isActive())) { + throw new CatalogItemNotFound(CatalogLevel::WorkType, $data->workTypeId); + } + + if ($this->templates->isNameTaken($data->workTypeId, $name->value, $templateId)) { + throw new WorkflowTemplateNameTaken; + } + + $this->stepBuilder->checkWorkTypes($workType, $steps, $template->steps()); + + $template->change($data->workTypeId, $name, $steps); + $this->templates->save($template); + }); + } +} diff --git a/app/Modules/Catalog/Domain/Contracts/WorkflowTemplateRepository.php b/app/Modules/Catalog/Domain/Contracts/WorkflowTemplateRepository.php new file mode 100644 index 0000000..755cb46 --- /dev/null +++ b/app/Modules/Catalog/Domain/Contracts/WorkflowTemplateRepository.php @@ -0,0 +1,23 @@ + $steps + */ + private function __construct( + private ?int $id, + private int $workTypeId, + private CatalogName $name, + private bool $active, + private array $steps, + ) {} + + /** + * @param list $steps + * + * @throws WorkflowTemplateNeedsSteps + */ + public static function create(int $workTypeId, CatalogName $name, array $steps): self + { + self::ensureSteps($steps); + + return new self(null, $workTypeId, $name, true, $steps); + } + + /** + * @param list $steps + */ + public static function reconstitute(int $id, int $workTypeId, CatalogName $name, bool $active, array $steps): self + { + return new self($id, $workTypeId, $name, $active, $steps); + } + + public function id(): ?int + { + return $this->id; + } + + public function workTypeId(): int + { + return $this->workTypeId; + } + + public function name(): CatalogName + { + return $this->name; + } + + public function isActive(): bool + { + return $this->active; + } + + /** + * @return list + */ + public function steps(): array + { + return $this->steps; + } + + /** + * Changes the name, the work type and the steps at once, as the template form saves them. + * + * @param list $steps + * + * @throws WorkflowTemplateNeedsSteps + */ + public function change(int $workTypeId, CatalogName $name, array $steps): void + { + self::ensureSteps($steps); + + $this->workTypeId = $workTypeId; + $this->name = $name; + $this->steps = $steps; + } + + public function activate(): void + { + $this->active = true; + } + + public function deactivate(): void + { + $this->active = false; + } + + /** + * @param list $steps + */ + private static function ensureSteps(array $steps): void + { + if ($steps === []) { + throw new WorkflowTemplateNeedsSteps; + } + } +} diff --git a/app/Modules/Catalog/Domain/Exceptions/InvalidWorkflowStepTitle.php b/app/Modules/Catalog/Domain/Exceptions/InvalidWorkflowStepTitle.php new file mode 100644 index 0000000..b03a9eb --- /dev/null +++ b/app/Modules/Catalog/Domain/Exceptions/InvalidWorkflowStepTitle.php @@ -0,0 +1,19 @@ +description = $description === '' ? null : $description; + } +} diff --git a/app/Modules/Catalog/Domain/ValueObjects/WorkflowStepTitle.php b/app/Modules/Catalog/Domain/ValueObjects/WorkflowStepTitle.php new file mode 100644 index 0000000..75979dd --- /dev/null +++ b/app/Modules/Catalog/Domain/ValueObjects/WorkflowStepTitle.php @@ -0,0 +1,29 @@ + self::MAX_LENGTH) { + throw new InvalidWorkflowStepTitle; + } + + $this->value = $value; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateModel.php new file mode 100644 index 0000000..0f045a4 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateModel.php @@ -0,0 +1,40 @@ + + */ + public function steps(): HasMany + { + return $this->hasMany(WorkflowTemplateStepModel::class, 'workflow_template_id')->orderBy('sort_order'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'work_type_id' => 'integer', + 'is_active' => 'boolean', + ]; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepModel.php new file mode 100644 index 0000000..3b4c04a --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepModel.php @@ -0,0 +1,34 @@ + + */ + protected function casts(): array + { + return [ + 'workflow_template_id' => 'integer', + 'work_type_id' => 'integer', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateQueries.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateQueries.php new file mode 100644 index 0000000..c5fc3f9 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateQueries.php @@ -0,0 +1,128 @@ +ordered() + ->withCount('steps') + ->get() + ->map(fn (WorkflowTemplateModel $model): WorkflowTemplateSummary => new WorkflowTemplateSummary( + $model->id, + $model->name, + $model->work_type_id, + (string) $model->getAttribute('work_type_name'), + (int) $model->getAttribute('service_unit_id'), + (string) $model->getAttribute('service_unit_name'), + $model->is_active, + (int) $model->getAttribute('steps_count'), + )) + ->values() + ->all(); + } + + public function find(int $id): ?WorkflowTemplateDetails + { + $models = $this->ordered()->whereKey($id)->get(); + + return $this->toDetails($models)[0] ?? null; + } + + public function activeFor(array $serviceUnitIds): array + { + $models = $this->ordered() + ->where('workflow_templates.is_active', true) + ->where('work_types.is_active', true) + ->where('service_units.is_active', true) + ->where(fn (Builder $query) => $query->whereNull('services.id')->orWhere('services.is_active', true)) + ->where(fn (Builder $query) => $query + ->whereIn('service_units.id', $serviceUnitIds) + ->orWhere('service_units.is_shared', true)) + ->get(); + + return $this->toDetails($models); + } + + /** + * Templates with their work type and unit, in catalog order: units (the + * shared one last), services, work types under no service last, then by name. + * + * @return Builder + */ + private function ordered(): Builder + { + return WorkflowTemplateModel::query() + ->join('work_types', 'work_types.id', '=', 'workflow_templates.work_type_id') + ->join('service_units', 'service_units.id', '=', 'work_types.service_unit_id') + ->leftJoin('services', 'services.id', '=', 'work_types.service_id') + ->select('workflow_templates.*') + ->addSelect([ + 'work_types.name as work_type_name', + 'service_units.id as service_unit_id', + 'service_units.name as service_unit_name', + ]) + ->orderBy('service_units.is_shared') + ->orderBy('service_units.sort_order') + ->orderByRaw('services.sort_order IS NULL') + ->orderBy('services.sort_order') + ->orderBy('work_types.sort_order') + ->orderBy('workflow_templates.name') + ->orderBy('workflow_templates.id'); + } + + /** + * @param Collection $models + * @return list + */ + private function toDetails(Collection $models): array + { + if ($models->isEmpty()) { + return []; + } + + $steps = WorkflowTemplateStepModel::query() + ->whereIn('workflow_template_id', $models->pluck('id')) + ->orderBy('sort_order') + ->get() + ->groupBy('workflow_template_id'); + + $workTypeNames = WorkTypeModel::query() + ->whereIn('id', $steps->flatten(1)->pluck('work_type_id')->filter()->unique()) + ->pluck('name', 'id'); + + return $models->map(function (WorkflowTemplateModel $model) use ($steps, $workTypeNames): WorkflowTemplateDetails { + $workTypeName = (string) $model->getAttribute('work_type_name'); + + return new WorkflowTemplateDetails( + $model->id, + $model->name, + $model->work_type_id, + $workTypeName, + (int) $model->getAttribute('service_unit_id'), + $model->is_active, + ($steps->get($model->id) ?? collect()) + ->map(fn (WorkflowTemplateStepModel $step): WorkflowStepSummary => new WorkflowStepSummary( + $step->title, + $step->description, + $step->work_type_id, + $step->work_type_id ?? $model->work_type_id, + $step->work_type_id === null ? $workTypeName : (string) $workTypeNames->get($step->work_type_id), + )) + ->values() + ->all(), + ); + })->values()->all(); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateRepository.php new file mode 100644 index 0000000..217beba --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateRepository.php @@ -0,0 +1,74 @@ +with('steps')->find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function save(WorkflowTemplate $template): WorkflowTemplate + { + $model = $template->id() === null ? new WorkflowTemplateModel : WorkflowTemplateModel::query()->findOrFail($template->id()); + + $model->fill([ + 'work_type_id' => $template->workTypeId(), + 'name' => $template->name()->value, + 'is_active' => $template->isActive(), + ])->save(); + + // Steps have no identity of their own: the saved list replaces the old one. + WorkflowTemplateStepModel::query()->where('workflow_template_id', $model->id)->delete(); + + foreach ($template->steps() as $index => $step) { + WorkflowTemplateStepModel::query()->create([ + 'workflow_template_id' => $model->id, + 'work_type_id' => $step->workTypeId, + 'title' => $step->title->value, + 'description' => $step->description, + 'sort_order' => $index + 1, + ]); + } + + return $this->toEntity($model->load('steps')); + } + + public function isNameTaken(int $workTypeId, string $name, ?int $exceptId = null): bool + { + return WorkflowTemplateModel::query() + ->where('work_type_id', $workTypeId) + ->whereRaw('LOWER(name) = ?', [mb_strtolower($name)]) + ->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId)) + ->exists(); + } + + private function toEntity(WorkflowTemplateModel $model): WorkflowTemplate + { + return WorkflowTemplate::reconstitute( + $model->id, + $model->work_type_id, + new CatalogName($model->name), + $model->is_active, + $model->steps + ->map(fn (WorkflowTemplateStepModel $step): WorkflowStep => new WorkflowStep( + new WorkflowStepTitle($step->title), + $step->description, + $step->work_type_id, + )) + ->values() + ->all(), + ); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php b/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php index 697a659..e5609a3 100644 --- a/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php +++ b/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php @@ -5,10 +5,12 @@ namespace App\Modules\Catalog\Infrastructure\Providers; use App\Models\User; use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Catalog\Application\Contracts\PriceListQueries; +use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries; use App\Modules\Catalog\Domain\Contracts\ProductRepository; use App\Modules\Catalog\Domain\Contracts\ServiceRepository; use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository; use App\Modules\Catalog\Domain\Contracts\VatRateRepository; +use App\Modules\Catalog\Domain\Contracts\WorkflowTemplateRepository; use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentCatalogQueries; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentPriceListQueries; @@ -16,6 +18,8 @@ use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentProductR use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceUnitRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentVatRateRepository; +use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkflowTemplateQueries; +use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkflowTemplateRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkTypeRepository; use App\Modules\Users\Domain\Enums\Role; use Illuminate\Support\Facades\Gate; @@ -40,6 +44,8 @@ class CatalogServiceProvider extends ServiceProvider ProductRepository::class => EloquentProductRepository::class, PriceListQueries::class => EloquentPriceListQueries::class, VatRateRepository::class => EloquentVatRateRepository::class, + WorkflowTemplateRepository::class => EloquentWorkflowTemplateRepository::class, + WorkflowTemplateQueries::class => EloquentWorkflowTemplateQueries::class, ]; public function boot(): void diff --git a/app/Modules/Catalog/Presentation/Livewire/Forms/WorkflowTemplateForm.php b/app/Modules/Catalog/Presentation/Livewire/Forms/WorkflowTemplateForm.php new file mode 100644 index 0000000..d86c75e --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/Forms/WorkflowTemplateForm.php @@ -0,0 +1,103 @@ + + */ + public array $steps = []; + + public int $nextKey = 1; + + public function addStep(string $title = '', string $workTypeId = '', string $description = ''): int + { + $key = $this->nextKey++; + $this->steps[] = ['key' => $key, 'title' => $title, 'work_type_id' => $workTypeId, 'description' => $description]; + + return $key; + } + + public function toData(): WorkflowTemplateData + { + $this->validate(); + + return new WorkflowTemplateData( + $this->name, + (int) $this->work_type_id, + array_map(fn (array $step): WorkflowStepData => WorkflowStepData::fromArray($step), $this->steps), + ); + } + + /** + * Shows a broken business rule as an error on the field it concerns. + */ + public function showDomainError(DomainException $exception): void + { + [$field, $key] = match (true) { + $exception instanceof InvalidCatalogName => ['name', 'catalog.errors.invalid_name'], + $exception instanceof WorkflowTemplateNameTaken => ['name', 'catalog.workflows.errors.name_taken'], + $exception instanceof CatalogItemNotFound => ['work_type_id', 'catalog.errors.work_type_unavailable'], + $exception instanceof WorkflowTemplateNeedsSteps => ['steps', 'catalog.workflows.errors.steps_required'], + $exception instanceof InvalidWorkflowStepTitle => ['steps.'.($exception->stepIndex ?? 0).'.title', 'catalog.workflows.errors.invalid_step_title'], + $exception instanceof WorkflowStepWorkTypeNotAllowed => ['steps.'.$exception->stepIndex.'.work_type_id', 'catalog.workflows.errors.step_work_type_not_allowed'], + default => throw $exception, + }; + + $this->addError($field, __($key)); + } + + /** + * @return array> + */ + protected function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:100'], + 'work_type_id' => ['required', 'integer'], + 'steps' => ['required', 'array', 'min:1'], + 'steps.*.title' => ['required', 'string', 'max:255'], + 'steps.*.work_type_id' => ['nullable', 'integer'], + 'steps.*.description' => ['nullable', 'string', 'max:5000'], + ]; + } + + /** + * @return array + */ + protected function messages(): array + { + return [ + 'name.required' => __('catalog.errors.name_required'), + 'name.max' => __('catalog.errors.invalid_name'), + 'work_type_id.required' => __('catalog.workflows.errors.work_type_required'), + 'work_type_id.integer' => __('catalog.errors.work_type_unavailable'), + 'steps.required' => __('catalog.workflows.errors.steps_required'), + 'steps.min' => __('catalog.workflows.errors.steps_required'), + 'steps.*.title.required' => __('catalog.workflows.errors.step_title_required'), + 'steps.*.title.max' => __('catalog.workflows.errors.invalid_step_title'), + 'steps.*.work_type_id.integer' => __('catalog.workflows.errors.step_work_type_not_allowed'), + 'steps.*.description.max' => __('catalog.workflows.errors.description_too_long'), + ]; + } +} diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php index 7b62f6d..f9c2e2c 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡index.blade.php @@ -122,6 +122,7 @@ new class extends Component

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

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

+

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

@if (session('status')) diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡workflow-template-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡workflow-template-form.blade.php new file mode 100644 index 0000000..373dce0 --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡workflow-template-form.blade.php @@ -0,0 +1,353 @@ + + */ + #[Locked] + public array $storedWorkTypeIds = []; + + public WorkflowTemplateForm $form; + + public string $statusMessage = ''; + + public function mount(WorkflowTemplateQueries $templates, ?int $template = null): void + { + $this->authorize('catalog.manage'); + + if ($template === null) { + $this->form->addStep(); + + return; + } + + $details = $templates->find($template); + + abort_if($details === null, 404); + + $this->templateId = $details->id; + $this->form->name = $details->name; + $this->form->work_type_id = (string) $details->workTypeId; + $this->storedWorkTypeIds = [$details->workTypeId]; + + foreach ($details->steps as $step) { + $this->form->addStep($step->title, $step->workTypeId === null ? '' : (string) $step->workTypeId, $step->description ?? ''); + + if ($step->workTypeId !== null) { + $this->storedWorkTypeIds[] = $step->workTypeId; + } + } + } + + /** + * Work types for the template, as optgroups "Unit" or "Unit – Service". + * + * @return array> + */ + #[Computed] + public function workTypeGroups(): array + { + return $this->groups(app(CatalogQueries::class)->tree(includeInactive: false)); + } + + /** + * Work types a step can have: those of the template work type's unit and the shared ones. + * + * @return array> + */ + #[Computed] + public function stepWorkTypeGroups(): array + { + $catalog = app(CatalogQueries::class); + $workType = $this->form->work_type_id === '' ? null : $catalog->findWorkType((int) $this->form->work_type_id); + + return $workType === null ? [] : $this->groups($catalog->activeWorkTypesFor([$workType->serviceUnitId])); + } + + public function addStep(): void + { + $this->authorize('catalog.manage'); + + $key = $this->form->addStep(); + + $this->statusMessage = __('catalog.workflows.status.step_added', ['number' => count($this->form->steps)]); + $this->js("document.getElementById('step-{$key}-title')?.focus()"); + } + + public function moveStep(int $index, string $direction): void + { + $this->authorize('catalog.manage'); + + $steps = array_values($this->form->steps); + $target = $direction === 'up' ? $index - 1 : $index + 1; + + if (! isset($steps[$index])) { + return; + } + + $key = $steps[$index]['key']; + + if (! isset($steps[$target])) { + $this->statusMessage = __($direction === 'up' ? 'catalog.workflows.status.already_first' : 'catalog.workflows.status.already_last', ['number' => $index + 1]); + + return; + } + + [$steps[$index], $steps[$target]] = [$steps[$target], $steps[$index]]; + $this->form->steps = $steps; + $this->resetErrorBag(); + + $this->statusMessage = __('catalog.workflows.status.step_moved', ['from' => $index + 1, 'to' => $target + 1]); + $this->js("document.getElementById('step-{$key}-{$direction}')?.focus()"); + } + + public function removeStep(int $index): void + { + $this->authorize('catalog.manage'); + + $steps = array_values($this->form->steps); + + if (! isset($steps[$index]) || count($steps) === 1) { + return; + } + + array_splice($steps, $index, 1); + $this->form->steps = $steps; + $this->resetErrorBag(); + + $this->statusMessage = __('catalog.workflows.status.step_removed', ['number' => $index + 1]); + + // Focus the step that took its place, the new last one, or the add button. + $next = $steps[$index] ?? $steps[count($steps) - 1]; + $this->js(count($steps) > 1 + ? "document.getElementById('step-{$next['key']}-remove')?.focus()" + : "document.getElementById('add-step')?.focus()"); + } + + public function save(AddWorkflowTemplate $add, UpdateWorkflowTemplate $update): void + { + $this->authorize('catalog.manage'); + + $data = $this->form->toData(); + + try { + if ($this->templateId === null) { + $add->execute($data); + session()->flash('status', __('catalog.status.created', ['name' => trim($data->name)])); + } else { + $update->execute($this->templateId, $data); + session()->flash('status', __('catalog.status.updated', ['name' => trim($data->name)])); + } + } catch (WorkflowTemplateNotFound) { + abort(404); + } catch (DomainException $exception) { + $this->form->showDomainError($exception); + + return; + } + + $this->redirectRoute('catalog.workflow-templates', navigate: true); + } + + public function heading(): string + { + return __($this->templateId === null ? 'catalog.workflows.create_title' : 'catalog.workflows.edit_title'); + } + + public function render(): mixed + { + return $this->view()->title($this->heading()); + } + + /** + * @param list<\App\Modules\Catalog\Application\DTOs\ServiceUnitNode> $tree + * @return array> + */ + private function groups(array $tree): array + { + $groups = []; + $offered = []; + + foreach ($tree as $node) { + foreach ($node->services as $serviceNode) { + if ($serviceNode->workTypes !== []) { + $groups[$node->serviceUnit->name.' – '.$serviceNode->service->name] = $serviceNode->workTypes; + } + } + + if ($node->workTypes !== []) { + $groups[$node->serviceUnit->name] = $node->workTypes; + } + } + + foreach ($groups as $workTypes) { + foreach ($workTypes as $workType) { + $offered[] = $workType->id; + } + } + + // Keep the stored choices, even when they are out of use now. + $catalog = app(CatalogQueries::class); + $inactive = []; + + foreach (array_unique($this->storedWorkTypeIds) as $id) { + if (! in_array($id, $offered, true) && ($workType = $catalog->findWorkType($id)) !== null) { + $inactive[] = $workType; + } + } + + if ($inactive !== []) { + $groups[__('catalog.inactive')] = $inactive; + } + + return $groups; + } +}; +?> + +
+

{{ $this->heading() }}

+ +
+ + + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->workTypeGroups as $group => $workTypes) + + @foreach ($workTypes as $workType) + + @endforeach + + @endforeach + + +
+
+

{{ __('catalog.workflows.steps') }}

+

{{ __('catalog.workflows.steps_help') }}

+
+ +

{{ $statusMessage }}

+ + @error('form.steps') + + @enderror + +
    + @foreach ($form->steps as $index => $step) + {{-- The index is part of the key: a moved step is rendered anew, so its fields bind to their new position. --}} +
  1. +
    + {{ __('catalog.workflows.step_legend', ['number' => $index + 1]) }} + + + + + + @foreach ($this->stepWorkTypeGroups as $group => $workTypes) + + @foreach ($workTypes as $workType) + + @endforeach + + @endforeach + + + + +
    + + + @if (count($form->steps) > 1) + + @endif +
    +
    +
  2. + @endforeach +
+ + +
+ +
+ + +
+ +
diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡workflow-templates.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡workflow-templates.blade.php new file mode 100644 index 0000000..9218825 --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡workflow-templates.blade.php @@ -0,0 +1,152 @@ +authorize('catalog.manage'); + } + + /** + * @return array> + */ + #[Computed] + public function groups(): array + { + $groups = []; + + foreach (app(WorkflowTemplateQueries::class)->all() as $template) { + $groups[$template->serviceUnitName][] = $template; + } + + return $groups; + } + + public function toggleActive(int $templateId, SetWorkflowTemplateActive $setActive): void + { + $this->authorize('catalog.manage'); + + $template = app(WorkflowTemplateQueries::class)->find($templateId); + + if ($template === null) { + $this->statusMessage = __('catalog.status.not_found'); + + return; + } + + try { + $setActive->execute($templateId, ! $template->isActive); + } catch (WorkflowTemplateNotFound) { + $this->statusMessage = __('catalog.status.not_found'); + + return; + } + + unset($this->groups); + + $this->statusMessage = __($template->isActive ? 'catalog.workflows.status.deactivated' : 'catalog.status.activated', ['name' => $template->name]); + } + + /** + * @return list + */ + public function headers(): array + { + return [ + ['index' => 'name', 'label' => __('catalog.fields.name'), 'sortable' => false], + ['index' => 'work_type', 'label' => __('catalog.workflows.work_type'), 'sortable' => false], + ['index' => 'steps', 'label' => __('catalog.workflows.step_count'), 'sortable' => false], + ['index' => 'actions', 'label' => __('catalog.products.actions'), 'sortable' => false], + ]; + } + + public function render(): mixed + { + return $this->view()->title(__('catalog.workflows.title')); + } +}; +?> + +
+
+

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

+ + +
+ +
+

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

+

{{ __('catalog.workflows.back_to_catalog') }}

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

{{ $statusMessage }}

+ + @forelse ($this->groups as $unitName => $templates) +
+

{{ $unitName }}

+ + + @interact('column_name', $template) + {{ $template->name }} + @unless ($template->isActive) + ({{ __('catalog.inactive') }}) + @endunless + @endinteract + + @interact('column_work_type', $template) + {{ $template->workTypeName }} + @endinteract + + @interact('column_steps', $template) + {{ $template->stepCount }} + @endinteract + + @interact('column_actions', $template) +
+ + + +
+ @endinteract +
+
+ @empty +

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

+ @endforelse +
diff --git a/app/Modules/Catalog/Presentation/Routes/web.php b/app/Modules/Catalog/Presentation/Routes/web.php index 3c81239..9c79be6 100644 --- a/app/Modules/Catalog/Presentation/Routes/web.php +++ b/app/Modules/Catalog/Presentation/Routes/web.php @@ -27,6 +27,12 @@ Route::middleware(['web', 'auth', 'can:catalog.manage']) ->whereNumber('workType') ->name('work-types.edit'); + Route::livewire('/workflow-templates', 'catalog::workflow-templates')->name('workflow-templates'); + Route::livewire('/workflow-templates/create', 'catalog::workflow-template-form')->name('workflow-templates.create'); + Route::livewire('/workflow-templates/{template}/edit', 'catalog::workflow-template-form') + ->whereNumber('template') + ->name('workflow-templates.edit'); + Route::livewire('/prices', 'catalog::prices')->name('prices'); Route::livewire('/products/create', 'catalog::product-form')->name('products.create'); Route::livewire('/products/{product}/edit', 'catalog::product-form') diff --git a/app/Modules/Customers/Application/Contracts/CustomerReferences.php b/app/Modules/Customers/Application/Contracts/CustomerReferences.php new file mode 100644 index 0000000..062876b --- /dev/null +++ b/app/Modules/Customers/Application/Contracts/CustomerReferences.php @@ -0,0 +1,17 @@ +ensureCanRemove($customerId); + + return true; + } catch (CustomerNotFound|InternalCustomerCannotBeRemoved|CustomerInUse) { + return false; + } + } + + /** + * @throws CustomerNotFound + * @throws InternalCustomerCannotBeRemoved + * @throws CustomerInUse + */ + public function ensureCanRemove(int $customerId): Customer + { + $customer = $this->customers->findById($customerId) + ?? throw new CustomerNotFound($customerId); + + if ($customer->isInternal()) { + throw new InternalCustomerCannotBeRemoved; + } + + if ($this->contacts->existsForCustomer($customerId) + || $this->billingUnits->existsForCustomer($customerId) + || $this->references->refersTo($customerId)) { + throw new CustomerInUse; + } + + return $customer; + } +} diff --git a/app/Modules/Customers/Application/UseCases/RemoveCustomer.php b/app/Modules/Customers/Application/UseCases/RemoveCustomer.php new file mode 100644 index 0000000..c51b1e2 --- /dev/null +++ b/app/Modules/Customers/Application/UseCases/RemoveCustomer.php @@ -0,0 +1,38 @@ +transactions->run(function () use ($customerId): void { + $this->customers->delete($this->removal->ensureCanRemove($customerId)); + }); + } +} diff --git a/app/Modules/Customers/Domain/Contracts/BillingUnitRepository.php b/app/Modules/Customers/Domain/Contracts/BillingUnitRepository.php index 88ade86..8e29334 100644 --- a/app/Modules/Customers/Domain/Contracts/BillingUnitRepository.php +++ b/app/Modules/Customers/Domain/Contracts/BillingUnitRepository.php @@ -20,4 +20,6 @@ interface BillingUnitRepository public function save(BillingUnit $billingUnit): BillingUnit; public function delete(BillingUnit $billingUnit): void; + + public function existsForCustomer(int $customerId): bool; } diff --git a/app/Modules/Customers/Domain/Contracts/CustomerContactRepository.php b/app/Modules/Customers/Domain/Contracts/CustomerContactRepository.php index 11733fd..e9afb82 100644 --- a/app/Modules/Customers/Domain/Contracts/CustomerContactRepository.php +++ b/app/Modules/Customers/Domain/Contracts/CustomerContactRepository.php @@ -20,4 +20,6 @@ interface CustomerContactRepository public function save(CustomerContact $contact): CustomerContact; public function delete(CustomerContact $contact): void; + + public function existsForCustomer(int $customerId): bool; } diff --git a/app/Modules/Customers/Domain/Contracts/CustomerRepository.php b/app/Modules/Customers/Domain/Contracts/CustomerRepository.php index fa1ed24..54bc7fa 100644 --- a/app/Modules/Customers/Domain/Contracts/CustomerRepository.php +++ b/app/Modules/Customers/Domain/Contracts/CustomerRepository.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Modules\Customers\Domain\Contracts; use App\Modules\Customers\Domain\Entities\Customer; +use App\Modules\Customers\Domain\Exceptions\CustomerInUse; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; use App\Modules\Shared\Domain\ValueObjects\BusinessId; @@ -18,6 +19,11 @@ interface CustomerRepository */ public function save(Customer $customer): Customer; + /** + * @throws CustomerInUse when other rows refer to the customer + */ + public function delete(Customer $customer): void; + public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool; public function isPersonalIdentityCodeTaken(PersonalIdentityCode $code, ?int $exceptCustomerId = null): bool; diff --git a/app/Modules/Customers/Domain/Exceptions/CustomerInUse.php b/app/Modules/Customers/Domain/Exceptions/CustomerInUse.php new file mode 100644 index 0000000..e201bda --- /dev/null +++ b/app/Modules/Customers/Domain/Exceptions/CustomerInUse.php @@ -0,0 +1,19 @@ + $references + */ + public function __construct(private iterable $references) {} + + public function refersTo(int $customerId): bool + { + foreach ($this->references as $references) { + if ($references->refersTo($customerId)) { + return true; + } + } + + return false; + } +} diff --git a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentBillingUnitRepository.php b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentBillingUnitRepository.php index db4ea72..073e22b 100644 --- a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentBillingUnitRepository.php +++ b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentBillingUnitRepository.php @@ -40,6 +40,11 @@ class EloquentBillingUnitRepository implements BillingUnitRepository BillingUnitModel::query()->whereKey($billingUnit->id())->delete(); } + public function existsForCustomer(int $customerId): bool + { + return BillingUnitModel::query()->where('customer_id', $customerId)->exists(); + } + private function toEntity(BillingUnitModel $model): BillingUnit { return BillingUnit::reconstitute( diff --git a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerContactRepository.php b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerContactRepository.php index 83ff077..b884c48 100644 --- a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerContactRepository.php +++ b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerContactRepository.php @@ -40,6 +40,11 @@ class EloquentCustomerContactRepository implements CustomerContactRepository CustomerContactModel::query()->whereKey($contact->id())->delete(); } + public function existsForCustomer(int $customerId): bool + { + return CustomerContactModel::query()->where('customer_id', $customerId)->exists(); + } + private function toEntity(CustomerContactModel $model): CustomerContact { return CustomerContact::reconstitute( diff --git a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php index 0522654..bc214de 100644 --- a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php +++ b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php @@ -4,11 +4,13 @@ namespace App\Modules\Customers\Infrastructure\Persistence\Repositories; use App\Modules\Customers\Domain\Contracts\CustomerRepository; use App\Modules\Customers\Domain\Entities\Customer; +use App\Modules\Customers\Domain\Exceptions\CustomerInUse; use App\Modules\Customers\Domain\ValueObjects\CustomerName; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel; use App\Modules\Customers\Infrastructure\Persistence\PersonalIdentityCodeHasher; use App\Modules\Shared\Domain\ValueObjects\BusinessId; +use Illuminate\Database\QueryException; class EloquentCustomerRepository implements CustomerRepository { @@ -38,6 +40,24 @@ class EloquentCustomerRepository implements CustomerRepository return $this->toEntity($model); } + /** + * Customer jobs, quick sales and invoices refer to customers with + * restricting foreign keys, so the database refuses the delete while + * any of them exists. That keeps this module unaware of their tables. + */ + public function delete(Customer $customer): void + { + try { + CustomerModel::query()->whereKey($customer->id())->delete(); + } catch (QueryException $exception) { + if (str_starts_with((string) $exception->getCode(), '23')) { + throw new CustomerInUse; + } + + throw $exception; + } + } + public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool { return CustomerModel::query() diff --git a/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php b/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php index ef3cc17..cd1c781 100644 --- a/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php +++ b/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php @@ -4,10 +4,12 @@ namespace App\Modules\Customers\Infrastructure\Providers; use App\Models\User; use App\Modules\Customers\Application\Contracts\CustomerQueries; +use App\Modules\Customers\Application\Contracts\CustomerReferences; use App\Modules\Customers\Application\Contracts\CustomerRowUsage; use App\Modules\Customers\Domain\Contracts\BillingUnitRepository; use App\Modules\Customers\Domain\Contracts\CustomerContactRepository; use App\Modules\Customers\Domain\Contracts\CustomerRepository; +use App\Modules\Customers\Infrastructure\AnyModuleRefersToCustomer; use App\Modules\Customers\Infrastructure\NothingUsesCustomerRows; use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentBillingUnitRepository; use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerContactRepository; @@ -36,6 +38,15 @@ class CustomersServiceProvider extends ServiceProvider CustomerRowUsage::class => NothingUsesCustomerRows::class, ]; + public function register(): void + { + // Jobs, Sales and Billing tag their own checks of rows that refer to a customer. + $this->app->bind( + CustomerReferences::class, + fn ($app): CustomerReferences => new AnyModuleRefersToCustomer($app->tagged(CustomerReferences::TAG)), + ); + } + public function boot(): void { $presentationPath = dirname(__DIR__, 2).'/Presentation'; diff --git a/app/Modules/Customers/Presentation/Livewire/⚡show.blade.php b/app/Modules/Customers/Presentation/Livewire/⚡show.blade.php index 0611b75..67d05e7 100644 --- a/app/Modules/Customers/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Customers/Presentation/Livewire/⚡show.blade.php @@ -4,12 +4,17 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries; use App\Modules\Customers\Application\DTOs\BillingUnitSummary; use App\Modules\Customers\Application\DTOs\ContactSummary; use App\Modules\Customers\Application\DTOs\CustomerSummary; +use App\Modules\Customers\Application\Services\CustomerRemoval; use App\Modules\Customers\Application\UseCases\RemoveBillingUnit; use App\Modules\Customers\Application\UseCases\RemoveContact; +use App\Modules\Customers\Application\UseCases\RemoveCustomer; use App\Modules\Customers\Domain\Exceptions\BillingUnitInUse; use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound; use App\Modules\Customers\Domain\Exceptions\ContactInUse; use App\Modules\Customers\Domain\Exceptions\ContactNotFound; +use App\Modules\Customers\Domain\Exceptions\CustomerInUse; +use App\Modules\Customers\Domain\Exceptions\CustomerNotFound; +use App\Modules\Customers\Domain\Exceptions\InternalCustomerCannotBeRemoved; use App\Modules\Customers\Domain\Enums\CustomerType; use Illuminate\Support\Facades\Gate; use Livewire\Attributes\Computed; @@ -17,7 +22,8 @@ use Livewire\Attributes\Locked; use Livewire\Component; /** - * A customer's page: details, contacts and billing units. + * A customer's page: details, contacts and billing units. A customer with + * nothing linked to it can be removed here. */ new class extends Component { @@ -27,7 +33,7 @@ new class extends Component public int $customerId; /** - * The row the remove dialog asks about: 'contact' or 'billing_unit'. + * What the remove dialog asks about: 'customer', 'contact' or 'billing_unit'. */ #[Locked] public ?string $removalType = null; @@ -42,9 +48,12 @@ new class extends Component protected CustomerQueries $customerQueries; - public function boot(CustomerQueries $customerQueries): void + protected CustomerRemoval $customerRemoval; + + public function boot(CustomerQueries $customerQueries, CustomerRemoval $customerRemoval): void { $this->customerQueries = $customerQueries; + $this->customerRemoval = $customerRemoval; } public function mount(int $customer): void @@ -77,6 +86,15 @@ new class extends Component return $this->customer->personalIdentityCodeMasked; } + /** + * Whether nothing is linked to this customer, so the remove button is shown. + */ + #[Computed] + public function canBeRemoved(): bool + { + return $this->customerRemoval->canRemove($this->customerId); + } + /** * @return list */ @@ -96,13 +114,15 @@ new class extends Component } /** - * Opens the remove dialog for a contact or a billing unit of this customer. + * Opens the remove dialog for this customer, or for one of its contacts + * or billing units. */ public function confirmRemoval(string $type, int $id): void { $this->authorize('customers.use'); $name = match ($type) { + 'customer' => $id === $this->customerId ? $this->customerQueries->findSummary($id)?->name : null, 'contact' => $this->customerQueries->findContact($this->customerId, $id)?->name, 'billing_unit' => $this->customerQueries->findBillingUnit($this->customerId, $id)?->name, default => null, @@ -122,7 +142,7 @@ new class extends Component $this->js("document.getElementById('".self::REMOVE_DIALOG."').showModal()"); } - public function remove(RemoveContact $removeContact, RemoveBillingUnit $removeBillingUnit): void + public function remove(RemoveContact $removeContact, RemoveBillingUnit $removeBillingUnit, RemoveCustomer $removeCustomer): void { $this->authorize('customers.use'); @@ -130,6 +150,12 @@ new class extends Component return; } + if ($this->removalType === 'customer') { + $this->removeCustomer($removeCustomer); + + return; + } + try { match ($this->removalType) { 'contact' => $removeContact->execute($this->customerId, $this->removalId), @@ -150,6 +176,32 @@ new class extends Component $this->reset('removalType', 'removalId', 'removalName'); } + /** + * Removes this customer and returns to the customer list, or tells why + * it was kept and moves focus back to the page heading. + */ + private function removeCustomer(RemoveCustomer $removeCustomer): void + { + try { + $removeCustomer->execute($this->customerId); + + session()->flash('status', __('customers.removal.removed_customer', ['name' => $this->removalName])); + $this->redirectRoute('customers.index', navigate: true); + + return; + } catch (CustomerNotFound) { + $this->statusMessage = __('customers.removal.already_removed'); + } catch (InternalCustomerCannotBeRemoved) { + $this->statusMessage = __('customers.removal.internal_customer'); + } catch (CustomerInUse) { + $this->statusMessage = __('customers.removal.in_use_customer', ['name' => $this->removalName]); + } + + $this->js("document.getElementById('".self::REMOVE_DIALOG."').close(); document.getElementById('customer-heading').focus()"); + + $this->reset('removalType', 'removalId', 'removalName'); + } + public function render(): mixed { return $this->view()->title($this->customer->name); @@ -160,16 +212,28 @@ new class extends Component
-

{{ $this->customer->name }}

+

{{ $this->customer->name }}

- +
+ + + @if ($this->canBeRemoved) + + @endif +
@if (session('status')) diff --git a/app/Modules/Jobs/Application/Contracts/TaskCalendarQueries.php b/app/Modules/Jobs/Application/Contracts/TaskCalendarQueries.php new file mode 100644 index 0000000..a9b46ae --- /dev/null +++ b/app/Modules/Jobs/Application/Contracts/TaskCalendarQueries.php @@ -0,0 +1,38 @@ + + */ + public function scheduledTasks(string $from, string $to, ?int $serviceUnitId = null, ?int $onlyAssigneeUserId = null): array; + + /** + * Tasks that are not done and have no planned period, on jobs that are + * not archived, by due date. + * + * @return list + */ + public function unscheduledOpenTasks(?int $serviceUnitId = null, ?int $onlyAssigneeUserId = null, int $limit = 100): array; + + /** + * Minutes each person's tasks that are not done book per day. + * + * @param list $userIds + * @return array> user id => Y-m-d => minutes. + */ + public function openMinutesByUser(array $userIds, string $from, string $to): array; +} diff --git a/app/Modules/Jobs/Application/DTOs/CalendarAssignment.php b/app/Modules/Jobs/Application/DTOs/CalendarAssignment.php new file mode 100644 index 0000000..99355b8 --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/CalendarAssignment.php @@ -0,0 +1,20 @@ +task->taskId.'-'.($this->userId ?? 'none'); + } +} diff --git a/app/Modules/Jobs/Application/DTOs/CalendarRow.php b/app/Modules/Jobs/Application/DTOs/CalendarRow.php new file mode 100644 index 0000000..0fb93ac --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/CalendarRow.php @@ -0,0 +1,32 @@ + $minutesByDay Y-m-d => minutes, for every shown day. + * @param list $bars Ordered by start. + */ + public function __construct( + public ?int $userId, + public string $name, + public array $minutesByDay, + public array $bars, + public int $lanes, + ) {} + + /** + * @return list The bars that are on the day. + */ + public function barsOn(int $dayIndex): array + { + return array_values(array_filter($this->bars, fn (CalendarBar $bar): bool => $bar->start <= $dayIndex && $dayIndex < $bar->start + $bar->span)); + } +} diff --git a/app/Modules/Jobs/Application/DTOs/CalendarTask.php b/app/Modules/Jobs/Application/DTOs/CalendarTask.php new file mode 100644 index 0000000..db42222 --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/CalendarTask.php @@ -0,0 +1,41 @@ + $assignments One per assignee. + */ + public function __construct( + public int $taskId, + public int $jobId, + public string $jobNumber, + public string $jobName, + public string $title, + public TaskStatus $status, + public ?string $dueOn, + public ?string $estimatedHours, + public ?string $plannedFrom, + public ?string $plannedTo, + public array $assignments, + ) {} + + public function assignmentOf(int $userId): ?CalendarAssignment + { + foreach ($this->assignments as $assignment) { + if ($assignment->userId === $userId) { + return $assignment; + } + } + + return null; + } +} diff --git a/app/Modules/Jobs/Application/DTOs/ScheduleResult.php b/app/Modules/Jobs/Application/DTOs/ScheduleResult.php new file mode 100644 index 0000000..aadf5e2 --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/ScheduleResult.php @@ -0,0 +1,19 @@ + $days The shown days, Y-m-d, consecutive. + * @param list $people Rows in order; id null is the "no assignee" row. + * @param list $tasks + * @param array> $minutesByUser user id => Y-m-d => booked minutes. + * @return list + */ + public static function build(array $days, array $people, array $tasks, array $minutesByUser): array + { + $rows = []; + + foreach ($people as $person) { + $bars = []; + + foreach ($tasks as $task) { + $bar = self::bar($task, $person['id'], $days); + + if ($bar !== null) { + $bars[] = $bar; + } + } + + [$bars, $lanes] = self::stack($bars); + $minutes = []; + + foreach ($days as $day) { + $minutes[$day] = $person['id'] === null ? 0 : ($minutesByUser[$person['id']][$day] ?? 0); + } + + $rows[] = new CalendarRow($person['id'], $person['name'], $minutes, $bars, $lanes); + } + + return $rows; + } + + /** + * @param list $days + */ + private static function bar(CalendarTask $task, ?int $userId, array $days): ?CalendarBar + { + if ($task->plannedFrom === null || $task->plannedTo === null || $days === []) { + return null; + } + + if ($userId === null) { + if ($task->assignments !== []) { + return null; + } + + $from = $task->plannedFrom; + $to = $task->plannedTo; + $minutes = 0; + } else { + $assignment = $task->assignmentOf($userId); + + if ($assignment === null) { + return null; + } + + $from = $task->plannedFrom; + $to = max($from, $assignment->to ?? $task->plannedTo); + $minutes = $assignment->minutes; + } + + $first = $days[0]; + $last = $days[count($days) - 1]; + + if ($to < $first || $from > $last) { + return null; + } + + $start = $from < $first ? 0 : (int) array_search($from, $days, true); + $end = $to > $last ? count($days) - 1 : (int) array_search($to, $days, true); + $late = $task->status !== TaskStatus::Done && $task->dueOn !== null && $to > $task->dueOn; + + return new CalendarBar($task, $userId, $from, $to, $minutes, $start, $end - $start + 1, 0, $late); + } + + /** + * Puts each bar on the first lane where it does not overlap another. + * + * @param list $bars + * @return array{0: list, 1: int} + */ + private static function stack(array $bars): array + { + usort($bars, fn (CalendarBar $a, CalendarBar $b): int => [$a->start, -$a->span, $a->task->taskId] <=> [$b->start, -$b->span, $b->task->taskId]); + + $laneEnds = []; + $stacked = []; + + foreach ($bars as $bar) { + $lane = 0; + + while (isset($laneEnds[$lane]) && $laneEnds[$lane] >= $bar->start) { + $lane++; + } + + $laneEnds[$lane] = $bar->start + $bar->span - 1; + $stacked[] = new CalendarBar($bar->task, $bar->userId, $bar->from, $bar->to, $bar->minutes, $bar->start, $bar->span, $lane, $bar->late); + } + + return [$stacked, max(1, count($laneEnds))]; + } +} diff --git a/app/Modules/Jobs/Application/Services/TaskPlanner.php b/app/Modules/Jobs/Application/Services/TaskPlanner.php new file mode 100644 index 0000000..b5d928d --- /dev/null +++ b/app/Modules/Jobs/Application/Services/TaskPlanner.php @@ -0,0 +1,106 @@ +settings->get(self::CAPACITY_KEY) ?? ''); + + return (int) round(($hours > 0 && $hours <= 24 ? $hours : self::DEFAULT_CAPACITY_HOURS) * 60); + } + + /** + * Rebooks the task's assignees and, if their days were full, moves the + * task's planned end later. The task must be saved (have an id); + * save it again afterwards. + * + * @return bool Whether the planned end moved later. + */ + public function plan(Task $task): bool + { + $taskId = (int) $task->id(); + $from = $task->plannedFrom(); + $to = $task->plannedTo(); + + if ($from === null || $to === null) { + $this->bookings->deleteForTask($taskId); + + return false; + } + + $this->bookings->deleteForTask($taskId, $task->assigneeUserIds()); + + $minutes = (int) round(($task->estimatedHours()->value ?? 0) * 60); + $lookahead = $to->add(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d'); + $holidays = $this->holidays->activeDatesBetween($from->format('Y-m-d'), $lookahead); + $capacity = $this->capacityMinutes(); + $end = $to; + + foreach ($task->assigneeUserIds() as $userId) { + $schedule = TaskScheduler::schedule( + $from, + $to, + $minutes, + $this->bookings->otherOpenMinutes($userId, $from->format('Y-m-d'), $lookahead, $taskId), + $capacity, + $holidays, + ); + + $this->bookings->replaceFor($taskId, $userId, $schedule->minutesByDay); + + if ($schedule->end > $end) { + $end = $schedule->end; + } + } + + if ($end > $to) { + $task->schedule($from, $end); + + return true; + } + + return false; + } + + /** + * The end of a task placed on a day without an end (TaskScheduler::defaultEnd). + */ + public function defaultEnd(DateTimeImmutable $from, Task $task): DateTimeImmutable + { + $minutes = (int) round(($task->estimatedHours()->value ?? 0) * 60); + $lookahead = $from->add(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d'); + + return TaskScheduler::defaultEnd($from, $minutes, $this->capacityMinutes(), $this->holidays->activeDatesBetween($from->format('Y-m-d'), $lookahead)); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/AddTask.php b/app/Modules/Jobs/Application/UseCases/AddTask.php index ae5a87f..aaeeec8 100644 --- a/app/Modules/Jobs/Application/UseCases/AddTask.php +++ b/app/Modules/Jobs/Application/UseCases/AddTask.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Modules\Jobs\Application\UseCases; use App\Modules\Jobs\Application\DTOs\TaskData; +use App\Modules\Jobs\Application\Services\TaskPlanner; use App\Modules\Jobs\Application\Services\TaskReferenceChecker; use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository; use App\Modules\Jobs\Domain\Contracts\TaskRepository; @@ -12,6 +13,7 @@ use App\Modules\Jobs\Domain\Entities\Task; use App\Modules\Jobs\Domain\Enums\TaskStatus; use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference; +use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart; use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet; use App\Modules\Jobs\Domain\ValueObjects\TaskTitle; use App\Modules\Shared\Application\Contracts\TransactionManager; @@ -22,6 +24,7 @@ final class AddTask private CustomerJobRepository $jobs, private TaskRepository $tasks, private TaskReferenceChecker $references, + private TaskPlanner $planner, private TransactionManager $transactions, ) {} @@ -31,6 +34,7 @@ final class AddTask * @throws CustomerJobNotFound * @throws TasksNotAllowedYet * @throws InvalidTaskReference + * @throws PlanEndsBeforeStart */ public function execute(int $jobId, TaskData $data, int $actorUserId): int { @@ -51,9 +55,17 @@ final class AddTask TaskInput::hours($data->estimatedHours), $data->assigneeUserIds, $actorUserId, + TaskInput::date($data->plannedFrom), + TaskInput::date($data->plannedTo), ); - return (int) $this->tasks->save($task)->id(); + $task = $this->tasks->save($task); + + if ($task->isScheduled() && $this->planner->plan($task)) { + $task = $this->tasks->save($task); + } + + return (int) $task->id(); }); } } diff --git a/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php b/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php new file mode 100644 index 0000000..214b0a8 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php @@ -0,0 +1,92 @@ + $schedules In step order; a missing one leaves the task without a due date and estimate. + * @return int How many tasks were added. + * + * @throws CustomerJobNotFound + * @throws InvalidEstimatedHours + * @throws TasksNotAllowedYet + * @throws WorkflowTemplateNotAvailable + * @throws InvalidTaskReference when a step's work type is not available for the job + */ + public function execute(int $jobId, int $templateId, int $actorUserId, array $schedules = []): int + { + $dueDates = array_map(fn (TemplateTaskSchedule $schedule) => TaskInput::date($schedule->dueOn), $schedules); + $estimates = array_map(fn (TemplateTaskSchedule $schedule) => TaskInput::hours($schedule->estimatedHours), $schedules); + + return $this->transactions->run(function () use ($jobId, $templateId, $actorUserId, $dueDates, $estimates): int { + $job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId); + $template = $this->availableTemplate($templateId, $job->details()->serviceUnitIds); + + foreach ($template->steps as $index => $step) { + $this->references->check($job, $step->effectiveWorkTypeId, [$actorUserId]); + + $this->tasks->save(Task::create( + $jobId, + $job->details()->status, + $step->effectiveWorkTypeId, + new TaskTitle($step->title), + $step->description, + TaskStatus::Waiting, + $dueDates[$index] ?? null, + $estimates[$index] ?? null, + [$actorUserId], + $actorUserId, + )); + } + + return count($template->steps); + }); + } + + /** + * @param list $serviceUnitIds + */ + private function availableTemplate(int $templateId, array $serviceUnitIds): WorkflowTemplateDetails + { + foreach ($this->templates->activeFor($serviceUnitIds) as $template) { + if ($template->id === $templateId) { + return $template; + } + } + + throw new WorkflowTemplateNotAvailable($templateId); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/ClearTaskSchedule.php b/app/Modules/Jobs/Application/UseCases/ClearTaskSchedule.php new file mode 100644 index 0000000..8372ffc --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/ClearTaskSchedule.php @@ -0,0 +1,35 @@ +transactions->run(function () use ($jobId, $taskId): void { + $task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId); + $task->schedule(null, null); + $this->planner->plan($task); + $this->tasks->save($task); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/ScheduleTask.php b/app/Modules/Jobs/Application/UseCases/ScheduleTask.php new file mode 100644 index 0000000..482d502 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/ScheduleTask.php @@ -0,0 +1,75 @@ +transactions->run(function () use ($jobId, $taskId, $fromUserId, $toUserId, $from, $to): ScheduleResult { + $job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId); + $task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId); + + $assignees = $task->assigneeUserIds(); + + if ($fromUserId !== $toUserId) { + $assignees = array_values(array_filter($assignees, fn (int $userId): bool => $userId !== $fromUserId)); + + if ($toUserId !== null) { + $assignees[] = $toUserId; + } + } + + $this->references->check($job, $task->workTypeId(), $assignees, $task); + + $task->changeAssignees($assignees); + $task->schedule($from, $to ?? $this->planner->defaultEnd($from, $task)); + + $task = $this->tasks->save($task); + $extended = $this->planner->plan($task); + $task = $this->tasks->save($task); + + return new ScheduleResult( + (string) $task->plannedFrom()?->format('Y-m-d'), + (string) $task->plannedTo()?->format('Y-m-d'), + $extended, + ); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/UpdateTask.php b/app/Modules/Jobs/Application/UseCases/UpdateTask.php index 070a373..026acf0 100644 --- a/app/Modules/Jobs/Application/UseCases/UpdateTask.php +++ b/app/Modules/Jobs/Application/UseCases/UpdateTask.php @@ -5,12 +5,15 @@ declare(strict_types=1); namespace App\Modules\Jobs\Application\UseCases; use App\Modules\Jobs\Application\DTOs\TaskData; +use App\Modules\Jobs\Application\Services\TaskPlanner; use App\Modules\Jobs\Application\Services\TaskReferenceChecker; use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository; use App\Modules\Jobs\Domain\Contracts\TaskRepository; +use App\Modules\Jobs\Domain\Entities\Task; use App\Modules\Jobs\Domain\Enums\TaskStatus; use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference; +use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart; use App\Modules\Jobs\Domain\Exceptions\TaskNotFound; use App\Modules\Jobs\Domain\ValueObjects\TaskTitle; use App\Modules\Shared\Application\Contracts\TransactionManager; @@ -21,6 +24,7 @@ final class UpdateTask private CustomerJobRepository $jobs, private TaskRepository $tasks, private TaskReferenceChecker $references, + private TaskPlanner $planner, private TransactionManager $transactions, ) {} @@ -28,6 +32,7 @@ final class UpdateTask * @throws CustomerJobNotFound * @throws TaskNotFound * @throws InvalidTaskReference + * @throws PlanEndsBeforeStart */ public function execute(int $jobId, int $taskId, TaskData $data): void { @@ -39,6 +44,8 @@ final class UpdateTask $this->references->check($job, $data->workTypeId, $data->assigneeUserIds, $task); + $before = self::planningInput($task); + $task->changeDetails( $data->workTypeId, $title, @@ -48,8 +55,28 @@ final class UpdateTask TaskInput::hours($data->estimatedHours), $data->assigneeUserIds, ); + $task->schedule(TaskInput::date($data->plannedFrom), TaskInput::date($data->plannedTo)); - $this->tasks->save($task); + $task = $this->tasks->save($task); + + // Rebook only when what the bookings depend on changed. + if (self::planningInput($task) !== $before) { + $this->planner->plan($task); + $this->tasks->save($task); + } }); } + + /** + * @return array{0: ?string, 1: ?string, 2: ?float, 3: list} + */ + private static function planningInput(Task $task): array + { + return [ + $task->plannedFrom()?->format('Y-m-d'), + $task->plannedTo()?->format('Y-m-d'), + $task->estimatedHours()?->value, + $task->assigneeUserIds(), + ]; + } } diff --git a/app/Modules/Jobs/Domain/Contracts/TaskBookingRepository.php b/app/Modules/Jobs/Domain/Contracts/TaskBookingRepository.php new file mode 100644 index 0000000..df85e30 --- /dev/null +++ b/app/Modules/Jobs/Domain/Contracts/TaskBookingRepository.php @@ -0,0 +1,32 @@ + $minutesByDay Y-m-d => minutes. + */ + public function replaceFor(int $taskId, int $userId, array $minutesByDay): void; + + /** + * Removes the task's bookings, except those of the given assignees. + * + * @param list $keepUserIds + */ + public function deleteForTask(int $taskId, array $keepUserIds = []): void; + + /** + * Minutes the user's other tasks that are not done book per day. + * + * @return array Y-m-d => minutes. + */ + public function otherOpenMinutes(int $userId, string $from, string $to, int $exceptTaskId): array; +} diff --git a/app/Modules/Jobs/Domain/Entities/Task.php b/app/Modules/Jobs/Domain/Entities/Task.php index dd30d9d..87efd01 100644 --- a/app/Modules/Jobs/Domain/Entities/Task.php +++ b/app/Modules/Jobs/Domain/Entities/Task.php @@ -6,6 +6,7 @@ namespace App\Modules\Jobs\Domain\Entities; use App\Modules\Jobs\Domain\Enums\JobStatus; use App\Modules\Jobs\Domain\Enums\TaskStatus; +use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart; use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet; use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours; use App\Modules\Jobs\Domain\ValueObjects\TaskTitle; @@ -14,6 +15,7 @@ use DateTimeImmutable; /** * A task (tehtävä) of a customer job: one step of the work, done by its * assignees under one work type. Time entries are recorded on tasks. + * Its planned schedule (planned from–to) places it in the task calendar. */ final class Task { @@ -31,14 +33,18 @@ final class Task private ?EstimatedHours $estimatedHours, private array $assigneeUserIds, private int $createdBy, + private ?DateTimeImmutable $plannedFrom = null, + private ?DateTimeImmutable $plannedTo = null, ) { $this->assigneeUserIds = self::normaliseIds($assigneeUserIds); + self::checkPlan($plannedFrom, $plannedTo); } /** * @param list $assigneeUserIds * * @throws TasksNotAllowedYet + * @throws PlanEndsBeforeStart */ public static function create( int $jobId, @@ -51,12 +57,14 @@ final class Task ?EstimatedHours $estimatedHours, array $assigneeUserIds, int $createdBy, + ?DateTimeImmutable $plannedFrom = null, + ?DateTimeImmutable $plannedTo = null, ): self { if (! $jobStatus->allowsTasks()) { throw new TasksNotAllowedYet; } - return new self(null, $jobId, $workTypeId, $title, self::text($description), $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy); + return new self(null, $jobId, $workTypeId, $title, self::text($description), $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy, ...self::plan($plannedFrom, $plannedTo)); } /** @@ -73,8 +81,10 @@ final class Task ?EstimatedHours $estimatedHours, array $assigneeUserIds, int $createdBy, + ?DateTimeImmutable $plannedFrom = null, + ?DateTimeImmutable $plannedTo = null, ): self { - return new self($id, $jobId, $workTypeId, $title, $description, $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy); + return new self($id, $jobId, $workTypeId, $title, $description, $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy, $plannedFrom, $plannedTo); } /** @@ -103,6 +113,25 @@ final class Task $this->status = $status; } + /** + * Sets the planned schedule. A start without an end lasts one day; + * null as the start removes the schedule. + * + * @throws PlanEndsBeforeStart + */ + public function schedule(?DateTimeImmutable $from, ?DateTimeImmutable $to): void + { + [$this->plannedFrom, $this->plannedTo] = self::plan($from, $to); + } + + /** + * @param list $assigneeUserIds + */ + public function changeAssignees(array $assigneeUserIds): void + { + $this->assigneeUserIds = self::normaliseIds($assigneeUserIds); + } + public function id(): ?int { return $this->id; @@ -143,6 +172,21 @@ final class Task return $this->estimatedHours; } + public function plannedFrom(): ?DateTimeImmutable + { + return $this->plannedFrom; + } + + public function plannedTo(): ?DateTimeImmutable + { + return $this->plannedTo; + } + + public function isScheduled(): bool + { + return $this->plannedFrom !== null; + } + /** * @return list */ @@ -168,6 +212,33 @@ final class Task return $ids; } + /** + * @return array{0: ?DateTimeImmutable, 1: ?DateTimeImmutable} + * + * @throws PlanEndsBeforeStart + */ + private static function plan(?DateTimeImmutable $from, ?DateTimeImmutable $to): array + { + if ($from === null) { + return [null, null]; + } + + $to ??= $from; + self::checkPlan($from, $to); + + return [$from, $to]; + } + + /** + * @throws PlanEndsBeforeStart + */ + private static function checkPlan(?DateTimeImmutable $from, ?DateTimeImmutable $to): void + { + if ($from !== null && $to !== null && $to < $from) { + throw new PlanEndsBeforeStart; + } + } + private static function text(?string $value): ?string { $value = $value === null ? '' : trim($value); diff --git a/app/Modules/Jobs/Domain/Enums/TaskStatus.php b/app/Modules/Jobs/Domain/Enums/TaskStatus.php index 404fc92..8d9ae9e 100644 --- a/app/Modules/Jobs/Domain/Enums/TaskStatus.php +++ b/app/Modules/Jobs/Domain/Enums/TaskStatus.php @@ -5,7 +5,8 @@ declare(strict_types=1); namespace App\Modules\Jobs\Domain\Enums; /** - * Status of a task (spec 8.2). Per-service-unit columns come in phase 3. + * Status of a task (spec 8.2). The statuses are fixed: tasks are arranged + * per person in the task calendar instead of per-unit Kanban columns. */ enum TaskStatus: string { diff --git a/app/Modules/Jobs/Domain/Exceptions/WorkflowTemplateNotAvailable.php b/app/Modules/Jobs/Domain/Exceptions/WorkflowTemplateNotAvailable.php new file mode 100644 index 0000000..2e5e770 --- /dev/null +++ b/app/Modules/Jobs/Domain/Exceptions/WorkflowTemplateNotAvailable.php @@ -0,0 +1,18 @@ + $otherMinutes Y-m-d => minutes booked by the assignee's other open tasks. + * @param list $holidays Y-m-d dates of the holidays in use. + */ + public static function schedule( + DateTimeImmutable $from, + DateTimeImmutable $to, + int $minutes, + array $otherMinutes, + int $capacityMinutes, + array $holidays, + ): TaskSchedule { + if ($minutes <= 0) { + return new TaskSchedule([], $to, false); + } + + $holidaySet = array_flip($holidays); + $days = self::days($from, $to); + $targets = array_values(array_filter($days, fn (string $day): bool => self::isWorkingDay($day, $holidaySet))); + + if ($targets === []) { + $targets = $days; + } + + $shares = self::split($minutes, count($targets)); + $booked = []; + $carry = 0; + + foreach ($targets as $index => $day) { + $wanted = $shares[$index] + $carry; + $booking = min($wanted, self::free($day, $otherMinutes, $capacityMinutes)); + $carry = $wanted - $booking; + + if ($booking > 0) { + $booked[$day] = $booking; + } + } + + $day = $to; + + for ($extra = 0; $carry > 0 && $extra < self::MAX_EXTRA_DAYS; $extra++) { + $day = $day->add(new DateInterval('P1D')); + $date = $day->format('Y-m-d'); + + if (! self::isWorkingDay($date, $holidaySet)) { + continue; + } + + $booking = min($carry, self::free($date, $otherMinutes, $capacityMinutes)); + $carry -= $booking; + + if ($booking > 0) { + $booked[$date] = $booking; + } + } + + if ($carry > 0) { + $date = $day->format('Y-m-d'); + $booked[$date] = ($booked[$date] ?? 0) + $carry; + } + + ksort($booked); + $lastDay = array_key_last($booked); + $end = $lastDay !== null && $lastDay > $to->format('Y-m-d') ? new DateTimeImmutable($lastDay) : $to; + + return new TaskSchedule($booked, $end, $end > $to); + } + + /** + * The end of a task placed on a day without an end: as many working + * days as the estimate needs at the daily maximum; without an estimate, the day itself. + * + * @param list $holidays + */ + public static function defaultEnd(DateTimeImmutable $from, int $minutes, int $capacityMinutes, array $holidays): DateTimeImmutable + { + if ($minutes <= 0 || $capacityMinutes <= 0) { + return $from; + } + + $needed = (int) ceil($minutes / $capacityMinutes); + $holidaySet = array_flip($holidays); + $day = $from; + $counted = self::isWorkingDay($from->format('Y-m-d'), $holidaySet) ? 1 : 0; + + for ($extra = 0; $counted < $needed && $extra < self::MAX_EXTRA_DAYS; $extra++) { + $day = $day->add(new DateInterval('P1D')); + + if (self::isWorkingDay($day->format('Y-m-d'), $holidaySet)) { + $counted++; + } + } + + return $day; + } + + /** + * @param array $holidaySet + */ + public static function isWorkingDay(string $date, array $holidaySet): bool + { + $day = new DateTimeImmutable($date); + + return (int) $day->format('N') <= 5 && ! isset($holidaySet[$date]); + } + + /** + * @return list + */ + private static function days(DateTimeImmutable $from, DateTimeImmutable $to): array + { + $days = []; + + for ($day = $from; $day <= $to; $day = $day->add(new DateInterval('P1D'))) { + $days[] = $day->format('Y-m-d'); + } + + return $days; + } + + /** + * Splits the minutes into equal quarter-hour shares; the first days get + * the remainder. Odd minutes go to the first day. + * + * @return list + */ + private static function split(int $minutes, int $parts): array + { + $steps = intdiv($minutes, self::STEP_MINUTES); + $odd = $minutes % self::STEP_MINUTES; + $shares = []; + + for ($index = 0; $index < $parts; $index++) { + $shares[] = (intdiv($steps, $parts) + ($index < $steps % $parts ? 1 : 0)) * self::STEP_MINUTES; + } + + $shares[0] += $odd; + + return $shares; + } + + /** + * @param array $otherMinutes + */ + private static function free(string $day, array $otherMinutes, int $capacityMinutes): int + { + return max(0, $capacityMinutes - ($otherMinutes[$day] ?? 0)); + } +} diff --git a/app/Modules/Jobs/Domain/ValueObjects/TaskSchedule.php b/app/Modules/Jobs/Domain/ValueObjects/TaskSchedule.php new file mode 100644 index 0000000..49383f8 --- /dev/null +++ b/app/Modules/Jobs/Domain/ValueObjects/TaskSchedule.php @@ -0,0 +1,24 @@ + $minutesByDay Y-m-d => minutes, in date order. + */ + public function __construct( + public array $minutesByDay, + public DateTimeImmutable $end, + public bool $extended, + ) {} +} diff --git a/app/Modules/Jobs/Infrastructure/CustomerReferencesFromJobs.php b/app/Modules/Jobs/Infrastructure/CustomerReferencesFromJobs.php new file mode 100644 index 0000000..d0ba51e --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/CustomerReferencesFromJobs.php @@ -0,0 +1,17 @@ +where('customer_id', $customerId)->exists(); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php index 4c238fe..5460d6a 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php @@ -13,7 +13,7 @@ use Illuminate\Database\Eloquent\Model; /** * Persistence model of a task, used only inside the Jobs Infrastructure - * layer. Assignees are in task_assignees. + * layer. Assignees are in task_assignees, day bookings in task_bookings. * * @property int $id * @property int $customer_job_id @@ -22,11 +22,13 @@ use Illuminate\Database\Eloquent\Model; * @property string|null $description * @property TaskStatus $status * @property CarbonImmutable|null $due_on + * @property CarbonImmutable|null $planned_from + * @property CarbonImmutable|null $planned_to * @property string|null $estimated_hours * @property int $created_by */ #[Table('tasks')] -#[Fillable(['customer_job_id', 'work_type_id', 'title', 'description', 'status', 'due_on', 'estimated_hours', 'created_by'])] +#[Fillable(['customer_job_id', 'work_type_id', 'title', 'description', 'status', 'due_on', 'planned_from', 'planned_to', 'estimated_hours', 'created_by'])] #[UseFactory(TaskFactory::class)] class TaskModel extends Model { @@ -43,6 +45,8 @@ class TaskModel extends Model 'work_type_id' => 'integer', 'status' => TaskStatus::class, 'due_on' => 'immutable_date', + 'planned_from' => 'immutable_date', + 'planned_to' => 'immutable_date', 'created_by' => 'integer', ]; } diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskBookingRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskBookingRepository.php new file mode 100644 index 0000000..5f1a3d2 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskBookingRepository.php @@ -0,0 +1,50 @@ +where('task_id', $taskId)->where('user_id', $userId)->delete(); + + $rows = []; + + foreach ($minutesByDay as $day => $minutes) { + if ($minutes > 0) { + $rows[] = ['task_id' => $taskId, 'user_id' => $userId, 'day' => $day, 'minutes' => $minutes]; + } + } + + if ($rows !== []) { + DB::table('task_bookings')->insert($rows); + } + } + + public function deleteForTask(int $taskId, array $keepUserIds = []): void + { + DB::table('task_bookings') + ->where('task_id', $taskId) + ->when($keepUserIds !== [], fn ($query) => $query->whereNotIn('user_id', $keepUserIds)) + ->delete(); + } + + public function otherOpenMinutes(int $userId, string $from, string $to, int $exceptTaskId): array + { + return DB::table('task_bookings') + ->join('tasks', 'tasks.id', '=', 'task_bookings.task_id') + ->where('task_bookings.user_id', $userId) + ->where('task_bookings.task_id', '!=', $exceptTaskId) + ->where('tasks.status', '!=', TaskStatus::Done->value) + ->whereBetween('task_bookings.day', [$from, $to]) + ->groupBy('task_bookings.day') + ->selectRaw('task_bookings.day as day, SUM(task_bookings.minutes) as minutes') + ->pluck('minutes', 'day') + ->mapWithKeys(fn ($minutes, $day): array => [substr((string) $day, 0, 10) => (int) $minutes]) + ->all(); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCalendarQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCalendarQueries.php new file mode 100644 index 0000000..996644c --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCalendarQueries.php @@ -0,0 +1,132 @@ +tasks($serviceUnitId, $onlyAssigneeUserId) + ->whereNotNull('tasks.planned_from') + ->where('tasks.planned_from', '<=', $to) + ->where('tasks.planned_to', '>=', $from) + ->orderBy('tasks.planned_from') + ->orderBy('tasks.id'); + + return $this->calendarTasks($query); + } + + public function unscheduledOpenTasks(?int $serviceUnitId = null, ?int $onlyAssigneeUserId = null, int $limit = 100): array + { + $query = $this->tasks($serviceUnitId, $onlyAssigneeUserId) + ->whereNull('tasks.planned_from') + ->where('tasks.status', '!=', TaskStatus::Done->value) + ->where('customer_jobs.status', '!=', JobStatus::Archived->value) + ->orderByRaw('tasks.due_on IS NULL') + ->orderBy('tasks.due_on') + ->orderBy('tasks.id') + ->limit($limit); + + return $this->calendarTasks($query); + } + + public function openMinutesByUser(array $userIds, string $from, string $to): array + { + if ($userIds === []) { + return []; + } + + $minutes = []; + + DB::table('task_bookings') + ->join('tasks', 'tasks.id', '=', 'task_bookings.task_id') + ->whereIn('task_bookings.user_id', $userIds) + ->where('tasks.status', '!=', TaskStatus::Done->value) + ->whereBetween('task_bookings.day', [$from, $to]) + ->groupBy('task_bookings.user_id', 'task_bookings.day') + ->selectRaw('task_bookings.user_id as user_id, task_bookings.day as day, SUM(task_bookings.minutes) as minutes') + ->get() + ->each(function ($row) use (&$minutes): void { + $minutes[(int) $row->user_id][substr((string) $row->day, 0, 10)] = (int) $row->minutes; + }); + + return $minutes; + } + + private function tasks(?int $serviceUnitId, ?int $onlyAssigneeUserId): Builder + { + $query = DB::table('tasks')->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id'); + + if ($serviceUnitId !== null) { + $query->whereIn('customer_jobs.id', DB::table('customer_job_service_unit')->select('customer_job_id')->where('service_unit_id', $serviceUnitId)); + } + + if ($onlyAssigneeUserId !== null) { + JobInvolvement::restrict($query, $onlyAssigneeUserId); + $query->whereIn('tasks.id', DB::table('task_assignees')->select('task_id')->where('user_id', $onlyAssigneeUserId)); + } + + return $query; + } + + /** + * @return list + */ + private function calendarTasks(Builder $query): array + { + $rows = $query->get([ + 'tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.status', 'tasks.due_on', 'tasks.estimated_hours', + 'tasks.planned_from', 'tasks.planned_to', 'customer_jobs.number', 'customer_jobs.name', + ]); + $taskIds = $rows->pluck('id')->map(fn ($id): int => (int) $id)->all(); + + if ($taskIds === []) { + return []; + } + + $assignees = DB::table('task_assignees')->whereIn('task_id', $taskIds)->orderBy('user_id')->get()->groupBy('task_id'); + $bookings = DB::table('task_bookings') + ->whereIn('task_id', $taskIds) + ->groupBy('task_id', 'user_id') + ->selectRaw('task_id, user_id, MIN(day) as first_day, MAX(day) as last_day, SUM(minutes) as minutes') + ->get() + ->keyBy(fn ($row): string => $row->task_id.'-'.$row->user_id); + + return $rows->map(fn ($row): CalendarTask => new CalendarTask( + (int) $row->id, + (int) $row->customer_job_id, + (string) $row->number, + (string) $row->name, + (string) $row->title, + TaskStatus::from((string) $row->status), + self::date($row->due_on), + $row->estimated_hours === null ? null : (string) (float) $row->estimated_hours, + self::date($row->planned_from), + self::date($row->planned_to), + ($assignees->get($row->id) ?? collect())->map(function ($assignee) use ($bookings, $row): CalendarAssignment { + $booking = $bookings->get($row->id.'-'.$assignee->user_id); + + return new CalendarAssignment( + (int) $assignee->user_id, + self::date($booking?->first_day), + self::date($booking?->last_day), + (int) ($booking->minutes ?? 0), + ); + })->values()->all(), + ))->values()->all(); + } + + private static function date(mixed $value): ?string + { + return $value === null ? null : substr((string) $value, 0, 10); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php index 3ab1f8a..28f1b4c 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php @@ -164,6 +164,8 @@ class EloquentTaskQueries implements TaskQueries ->sortBy('name') ->values() ->all(), + plannedFrom: $model->planned_from?->format('Y-m-d'), + plannedTo: $model->planned_to?->format('Y-m-d'), ))->values()->all(); } } diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php index 0e3106d..98d4b1c 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php @@ -7,6 +7,7 @@ use App\Modules\Jobs\Domain\Entities\Task; use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours; use App\Modules\Jobs\Domain\ValueObjects\TaskTitle; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel; +use Carbon\CarbonImmutable; use DateTimeImmutable; use Illuminate\Support\Facades\DB; @@ -37,6 +38,8 @@ class EloquentTaskRepository implements TaskRepository 'description' => $task->description(), 'status' => $task->status(), 'due_on' => $task->dueOn()?->format('Y-m-d'), + 'planned_from' => $task->plannedFrom()?->format('Y-m-d'), + 'planned_to' => $task->plannedTo()?->format('Y-m-d'), 'estimated_hours' => $task->estimatedHours()?->value, 'created_by' => $task->createdBy(), ])->save(); @@ -64,10 +67,17 @@ class EloquentTaskRepository implements TaskRepository new TaskTitle($model->title), $model->description, $model->status, - $model->due_on === null ? null : (DateTimeImmutable::createFromFormat('!Y-m-d', $model->due_on->format('Y-m-d')) ?: null), + self::date($model->due_on), $model->estimated_hours === null ? null : new EstimatedHours((float) $model->estimated_hours), DB::table('task_assignees')->where('task_id', $model->id)->pluck('user_id')->map(fn ($id): int => (int) $id)->all(), $model->created_by, + self::date($model->planned_from), + self::date($model->planned_to), ); } + + private static function date(?CarbonImmutable $value): ?DateTimeImmutable + { + return $value === null ? null : (DateTimeImmutable::createFromFormat('!Y-m-d', $value->format('Y-m-d')) ?: null); + } } diff --git a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php index 7b1b837..fb690be 100644 --- a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php +++ b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php @@ -3,15 +3,19 @@ namespace App\Modules\Jobs\Infrastructure\Providers; use App\Models\User; +use App\Modules\Customers\Application\Contracts\CustomerReferences; use App\Modules\Customers\Application\Contracts\CustomerRowUsage; use App\Modules\Jobs\Application\Contracts\ChecklistQueries; use App\Modules\Jobs\Application\Contracts\CustomerJobQueries; +use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries; use App\Modules\Jobs\Application\Contracts\TaskQueries; use App\Modules\Jobs\Application\Contracts\TaskUsage; use App\Modules\Jobs\Domain\Contracts\ChecklistItemRepository; use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository; use App\Modules\Jobs\Domain\Contracts\JobNumberSequence; +use App\Modules\Jobs\Domain\Contracts\TaskBookingRepository; use App\Modules\Jobs\Domain\Contracts\TaskRepository; +use App\Modules\Jobs\Infrastructure\CustomerReferencesFromJobs; use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs; use App\Modules\Jobs\Infrastructure\NothingUsesTasks; use App\Modules\Jobs\Infrastructure\Persistence\DatabaseJobNumberSequence; @@ -19,6 +23,8 @@ use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistIt use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobRepository; +use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskBookingRepository; +use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCalendarQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskRepository; use App\Modules\Users\Domain\Enums\Role; @@ -42,12 +48,20 @@ class JobsServiceProvider extends ServiceProvider CustomerRowUsage::class => CustomerRowUsageFromJobs::class, TaskRepository::class => EloquentTaskRepository::class, TaskQueries::class => EloquentTaskQueries::class, + TaskBookingRepository::class => EloquentTaskBookingRepository::class, + TaskCalendarQueries::class => EloquentTaskCalendarQueries::class, ChecklistItemRepository::class => EloquentChecklistItemRepository::class, ChecklistQueries::class => EloquentChecklistQueries::class, // Replaced by the TimeTracking module, which knows which tasks have time entries. TaskUsage::class => NothingUsesTasks::class, ]; + public function register(): void + { + // A customer with customer jobs cannot be removed. + $this->app->tag([CustomerReferencesFromJobs::class], CustomerReferences::TAG); + } + public function boot(): void { $presentationPath = dirname(__DIR__, 2).'/Presentation'; diff --git a/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php b/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php index 0e0e8ef..9cbe19d 100644 --- a/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php +++ b/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php @@ -9,6 +9,7 @@ use App\Modules\Jobs\Domain\Enums\TaskStatus; use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskTitle; +use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart; use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet; use App\Modules\Shared\Domain\Exceptions\DomainException; use Illuminate\Validation\Rule; @@ -29,6 +30,10 @@ class TaskForm extends Form public string $estimated_hours = ''; + public string $planned_from = ''; + + public string $planned_to = ''; + public string $description = ''; /** @var list */ @@ -41,6 +46,8 @@ class TaskForm extends Form $this->status = $task->status->value; $this->due_on = $task->dueOn ?? ''; $this->estimated_hours = $task->estimatedHours ?? ''; + $this->planned_from = $task->plannedFrom ?? ''; + $this->planned_to = $task->plannedTo ?? ''; $this->description = $task->description ?? ''; $this->assignee_user_ids = array_map(fn (NamedId $user): string => (string) $user->id, $task->assignees); } @@ -57,6 +64,8 @@ class TaskForm extends Form dueOn: $this->due_on === '' ? null : $this->due_on, estimatedHours: trim($this->estimated_hours) === '' ? null : $this->estimated_hours, assigneeUserIds: array_map('intval', $this->assignee_user_ids), + plannedFrom: $this->planned_from === '' ? null : $this->planned_from, + plannedTo: $this->planned_from === '' || $this->planned_to === '' ? null : $this->planned_to, ); } @@ -66,6 +75,7 @@ class TaskForm extends Form $exception instanceof InvalidTaskTitle => ['title', 'jobs.tasks.errors.invalid_title'], $exception instanceof InvalidEstimatedHours => ['estimated_hours', 'jobs.errors.invalid_hours'], $exception instanceof TasksNotAllowedYet => ['title', 'jobs.tasks.not_allowed_yet'], + $exception instanceof PlanEndsBeforeStart => ['planned_to', 'jobs.calendar.errors.to'], $exception instanceof InvalidTaskReference => [$exception->field === 'work_type' ? 'work_type_id' : 'assignee_user_ids', 'jobs.errors.invalid_reference'], default => throw $exception, }; @@ -83,6 +93,8 @@ class TaskForm extends Form 'work_type_id' => ['required', 'integer'], 'status' => ['required', Rule::enum(TaskStatus::class)], 'due_on' => ['nullable', 'date_format:Y-m-d'], + 'planned_from' => ['nullable', 'date_format:Y-m-d'], + 'planned_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:planned_from'], 'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'], 'description' => ['nullable', 'string', 'max:10000'], 'assignee_user_ids' => ['array'], @@ -100,6 +112,9 @@ class TaskForm extends Form 'title.max' => __('jobs.tasks.errors.invalid_title'), 'work_type_id.required' => __('jobs.tasks.errors.work_type_required'), 'due_on.date_format' => __('jobs.errors.invalid_date'), + 'planned_from.date_format' => __('jobs.errors.invalid_date'), + 'planned_to.date_format' => __('jobs.errors.invalid_date'), + 'planned_to.after_or_equal' => __('jobs.calendar.errors.to'), 'estimated_hours.numeric' => __('jobs.errors.invalid_hours'), 'estimated_hours.min' => __('jobs.errors.invalid_hours'), 'estimated_hours.max' => __('jobs.errors.invalid_hours'), diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php new file mode 100644 index 0000000..9633e7e --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php @@ -0,0 +1,787 @@ +authorize('jobs.view'); + } + + public function isSubcontractor(): bool + { + return auth()->user()?->role === Role::Subcontractor; + } + + public function startDate(): CarbonImmutable + { + $start = $this->from === '' ? null : CarbonImmutable::createFromFormat('!Y-m-d', $this->from); + + return $start instanceof CarbonImmutable && $start->format('Y-m-d') === $this->from ? $start : CarbonImmutable::today(); + } + + /** + * @return list + */ + #[Computed] + public function days(): array + { + $start = $this->startDate(); + + return array_map(fn (int $offset): string => $start->addDays($offset)->format('Y-m-d'), range(0, self::DAYS - 1)); + } + + /** + * Holidays in use on the shown days, date => name. + * + * @return array + */ + #[Computed] + public function holidays(): array + { + $names = []; + + foreach (app(HolidayCalendar::class)->between($this->days[0], $this->days[self::DAYS - 1]) as $holiday) { + if ($holiday->active) { + $names[$holiday->date] = $holiday->key === null ? (string) $holiday->name : __('holidays.names.'.$holiday->key); + } + } + + return $names; + } + + /** + * Rows: the signed-in user first, then the others by name, then tasks + * without an assignee. A subcontractor sees only their own row. + * + * @return list + */ + #[Computed] + public function people(): array + { + $userId = (int) auth()->id(); + $own = ['id' => $userId, 'name' => (string) auth()->user()?->name]; + + if ($this->isSubcontractor() || $this->mine) { + return [$own]; + } + + $others = []; + + foreach (app(UserAccountQueries::class)->activeUserOptions() as $user) { + if ($user->id !== $userId) { + $others[] = ['id' => $user->id, 'name' => $user->name]; + } + } + + return [$own, ...$others, ['id' => null, 'name' => __('jobs.calendar.no_assignee')]]; + } + + /** + * @return list + */ + #[Computed] + public function rows(): array + { + $queries = app(TaskCalendarQueries::class); + $first = $this->days[0]; + $last = $this->days[self::DAYS - 1]; + $userIds = array_values(array_filter(array_column($this->people, 'id'))); + + return TaskCalendarLayout::build( + $this->days, + $this->people, + $queries->scheduledTasks($first, $last, $this->serviceUnitId(), $this->onlyAssigneeUserId()), + $queries->openMinutesByUser($userIds, $first, $last), + ); + } + + /** + * @return list + */ + #[Computed] + public function unscheduled(): array + { + $tasks = app(TaskCalendarQueries::class)->unscheduledOpenTasks($this->serviceUnitId(), $this->onlyAssigneeUserId()); + + if ($this->mine) { + $userId = (int) auth()->id(); + $tasks = array_values(array_filter($tasks, fn (CalendarTask $task): bool => $task->assignmentOf($userId) !== null)); + } + + return $tasks; + } + + /** + * Names of the people on the rows, user id => name, for assignee lists. + * + * @return array + */ + #[Computed] + public function userNames(): array + { + $names = []; + + foreach (app(UserAccountQueries::class)->activeUserOptions() as $user) { + $names[$user->id] = $user->name; + } + + return $names; + } + + #[Computed] + public function capacityMinutes(): int + { + return app(TaskPlanner::class)->capacityMinutes(); + } + + public function canManage(): bool + { + return Gate::allows('jobs.manage-tasks', 0); + } + + public function showPrevious(): void + { + $this->moveRange(-self::DAYS); + } + + public function showNext(): void + { + $this->moveRange(self::DAYS); + } + + public function showToday(): void + { + $this->from = ''; + $this->refresh(); + $this->statusMessage = $this->showingMessage(); + } + + /** + * A bar was dropped (drag and drop). Without an end, the task gets as + * many working days as its estimate needs. + */ + public function reschedule(int $taskId, int $jobId, ?int $fromUserId, ?int $toUserId, string $plannedFrom, ?string $plannedTo, ScheduleTask $scheduleTask): void + { + $this->authorize('jobs.manage-tasks', $jobId); + + $this->schedule($scheduleTask, $taskId, $jobId, $fromUserId, $toUserId, $plannedFrom, $plannedTo); + } + + /** + * Opens the dialog of a bar or an unscheduled task (keyboard alternative to dragging). + */ + public function openDialog(int $taskId, ?int $userId): void + { + $task = $this->findTask($taskId); + + if ($task === null) { + $this->statusMessage = __('jobs.calendar.not_changed'); + + return; + } + + $this->authorize('jobs.update-task-status', $task->jobId); + + $this->resetErrorBag(); + $this->dialogTaskId = $task->taskId; + $this->dialogJobId = $task->jobId; + $this->dialogUserId = $userId; + $this->dialogTitle = __('jobs.calendar.dialog_task', ['title' => $task->title, 'job' => $task->jobNumber]); + $this->dialogStatus = $task->status->value; + $this->plannedFrom = $task->plannedFrom ?? CarbonImmutable::today()->format('Y-m-d'); + $this->plannedTo = $task->plannedTo ?? ''; + $this->assignee = $userId === null ? '' : (string) $userId; + $this->status = $task->status->value; + + $this->js("document.getElementById('task-schedule-dialog').showModal()"); + } + + public function saveDialog(ScheduleTask $scheduleTask, ChangeTaskStatus $changeTaskStatus): void + { + if ($this->dialogTaskId === null || $this->dialogJobId === null) { + return; + } + + $this->authorize('jobs.update-task-status', $this->dialogJobId); + + $taskId = $this->dialogTaskId; + $jobId = $this->dialogJobId; + $task = $this->findTask($taskId); + $toUserId = $this->dialogUserId; + $messages = []; + + if (Gate::allows('jobs.manage-tasks', $jobId)) { + $this->validate([ + 'plannedFrom' => ['required', 'date_format:Y-m-d'], + 'plannedTo' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:plannedFrom'], + 'assignee' => ['nullable', 'integer'], + ], [ + 'plannedFrom.*' => __('jobs.calendar.errors.from'), + 'plannedTo.*' => __('jobs.calendar.errors.to'), + ]); + + $toUserId = $this->assignee === '' ? null : (int) $this->assignee; + + if (! $this->schedule($scheduleTask, $taskId, $jobId, $this->dialogUserId, $toUserId, $this->plannedFrom, $this->plannedTo === '' ? null : $this->plannedTo)) { + return; + } + + $messages[] = $this->statusMessage; + } + + $status = TaskStatus::tryFrom($this->status); + + if ($status !== null && $status->value !== $this->dialogStatus) { + try { + $changeTaskStatus->execute($jobId, $taskId, $status); + } catch (TaskNotFound) { + $this->statusMessage = __('jobs.calendar.not_changed'); + + return; + } + + $this->refresh(); + $messages[] = __('jobs.calendar.status_changed', ['title' => $task->title ?? '', 'status' => __('jobs.tasks.statuses.'.$status->value)]); + } + + $this->statusMessage = implode(' ', $messages); + $this->closeDialogAndFocus($taskId, $toUserId); + } + + public function clearSchedule(ClearTaskSchedule $clearTaskSchedule): void + { + if ($this->dialogTaskId === null || $this->dialogJobId === null) { + return; + } + + $this->authorize('jobs.manage-tasks', $this->dialogJobId); + + $task = $this->findTask($this->dialogTaskId); + + try { + $clearTaskSchedule->execute($this->dialogJobId, $this->dialogTaskId); + } catch (TaskNotFound) { + $this->statusMessage = __('jobs.calendar.not_changed'); + + return; + } + + $this->refresh(); + $this->statusMessage = __('jobs.calendar.cleared', ['title' => $task->title ?? '']); + $taskId = $this->dialogTaskId; + $this->js("document.getElementById('task-schedule-dialog').close(); document.getElementById('unscheduled-{$taskId}')?.focus()"); + } + + public function updatedServiceUnit(): void + { + $this->refresh(); + } + + public function updatedMine(): void + { + $this->refresh(); + } + + public function dayLabel(string $date): string + { + $day = CarbonImmutable::createFromFormat('!Y-m-d', $date); + + return $day instanceof CarbonImmutable ? __('holidays.weekdays.'.$day->dayOfWeekIso).' '.$day->format('j.n.') : $date; + } + + public function isDayOff(string $date): bool + { + $day = CarbonImmutable::createFromFormat('!Y-m-d', $date); + + return isset($this->holidays[$date]) || ($day instanceof CarbonImmutable && $day->dayOfWeekIso >= 6); + } + + public function hours(int $minutes): string + { + return rtrim(rtrim(number_format($minutes / 60, 2, ',', ''), '0'), ','); + } + + public function shortDate(string $date): string + { + $day = CarbonImmutable::createFromFormat('!Y-m-d', $date); + + return $day instanceof CarbonImmutable ? $day->format('j.n.Y') : $date; + } + + public function barLabel(CalendarBar $bar): string + { + return __('jobs.calendar.bar_label', [ + 'title' => $bar->task->title, + 'job' => $bar->task->jobNumber.' '.$bar->task->jobName, + 'status' => __('jobs.tasks.statuses.'.$bar->task->status->value), + 'from' => $this->shortDate($bar->from), + 'to' => $this->shortDate($bar->to), + 'hours' => $bar->minutes > 0 ? __('jobs.calendar.bar_hours', ['hours' => $this->hours($bar->minutes)]) : '', + ]).($bar->late ? ', '.__('jobs.late') : ''); + } + + /** + * The person an unscheduled task is moved from when it is dropped on a + * row: its only assignee, so that the task moves rather than gets a + * second assignee. + */ + public function onlyAssignee(CalendarTask $task): ?int + { + return count($task->assignments) === 1 ? $task->assignments[0]->userId : null; + } + + public function render(): mixed + { + return $this->view()->title(__('jobs.calendar.title')); + } + + private function schedule(ScheduleTask $scheduleTask, int $taskId, int $jobId, ?int $fromUserId, ?int $toUserId, string $plannedFrom, ?string $plannedTo): bool + { + $task = $this->findTask($taskId); + + try { + $result = $scheduleTask->execute($jobId, $taskId, $fromUserId, $toUserId, $plannedFrom, $plannedTo); + } catch (CustomerJobNotFound|TaskNotFound|InvalidArgumentException) { + $this->statusMessage = __('jobs.calendar.not_changed'); + + return false; + } catch (PlanEndsBeforeStart) { + $this->addError('plannedTo', __('jobs.calendar.errors.to')); + $this->statusMessage = __('jobs.calendar.errors.to'); + + return false; + } catch (InvalidTaskReference) { + $this->statusMessage = __('jobs.calendar.inactive_person'); + + return false; + } + + $this->refresh(); + $this->statusMessage = __($result->extended ? 'jobs.calendar.moved_extended' : 'jobs.calendar.moved', [ + 'title' => $task->title ?? '', + 'person' => $toUserId === null ? __('jobs.calendar.no_assignee') : ($this->userNames[$toUserId] ?? ''), + 'from' => $this->shortDate($result->plannedFrom), + 'to' => $this->shortDate($result->plannedTo), + ]); + + return true; + } + + private function closeDialogAndFocus(int $taskId, ?int $userId): void + { + $key = $taskId.'-'.($userId ?? 'none'); + + $this->js("document.getElementById('task-schedule-dialog').close();" + ."const bar = document.getElementById('bar-{$key}');" + ."(bar && bar.offsetParent !== null ? bar : document.getElementById('agenda-bar-{$key}'))?.focus();"); + } + + private function findTask(int $taskId): ?CalendarTask + { + foreach ($this->rows as $row) { + foreach ($row->bars as $bar) { + if ($bar->task->taskId === $taskId) { + return $bar->task; + } + } + } + + foreach ($this->unscheduled as $task) { + if ($task->taskId === $taskId) { + return $task; + } + } + + return null; + } + + private function moveRange(int $days): void + { + $this->from = $this->startDate()->addDays($days)->format('Y-m-d'); + $this->refresh(); + $this->statusMessage = $this->showingMessage(); + } + + private function showingMessage(): string + { + return __('jobs.calendar.showing', ['from' => $this->shortDate($this->days[0]), 'to' => $this->shortDate($this->days[self::DAYS - 1])]); + } + + private function refresh(): void + { + unset($this->days, $this->holidays, $this->people, $this->rows, $this->unscheduled); + } + + private function serviceUnitId(): ?int + { + return $this->serviceUnit === '' ? null : (int) $this->serviceUnit; + } + + private function onlyAssigneeUserId(): ?int + { + return $this->isSubcontractor() ? (int) auth()->id() : null; + } +}; +?> + +@php + $canManage = $this->canManage(); + $days = $this->days; + $capacity = $this->hours($this->capacityMinutes); + $columns = 'grid-template-columns: 11rem repeat('.count($days).', minmax(0, 1fr));'; +@endphp + +
+
+

{{ __('jobs.calendar.title') }}

+

{{ __('jobs.calendar.intro') }}

+
+ +
+
+ + + +
+ +
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach (app(CatalogQueries::class)->activeServiceUnits() as $unit) + + @endforeach + +
+ + @if ($this->isSubcontractor()) +

{{ __('jobs.calendar.subcontractor_note') }}

+ @else +
+ +
+ @endif +
+ +

{{ $statusMessage }}

+ +
+

+ {{ __('jobs.calendar.range', ['from' => $this->shortDate($days[0]), 'to' => $this->shortDate($days[count($days) - 1])]) }} +

+ + {{-- Desktop: the Gantt grid. Dragging is a pointer shortcut; every bar is a button that opens the dialog. --}} + + + {{-- Phones and narrow windows: the same tasks as a list per person. --}} +
+ @foreach ($this->rows as $row) + @php($rowKey = $row->userId ?? 'none') +
+

{{ $row->name }}

+ + @if ($row->bars === []) +

{{ __('jobs.calendar.no_tasks') }}

+ @else +
    + @foreach ($row->bars as $bar) +
  • + +
  • + @endforeach +
+ @endif +
+ @endforeach +
+
+ +
+

{{ __('jobs.calendar.unscheduled') }}

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

{{ __('jobs.calendar.unscheduled_none') }}

+ @else +

{{ __('jobs.calendar.unscheduled_intro') }}

+ +
    + @foreach ($this->unscheduled as $task) +
  • $canManage, + ]) + > + {{ $task->title }} + {{ $task->jobNumber }} {{ $task->jobName }} + + {{ $task->assignments === [] ? __('jobs.calendar.no_assignee') : implode(', ', array_map(fn ($assignment) => $this->userNames[$assignment->userId] ?? '', $task->assignments)) }} + @if ($task->estimatedHours !== null) · {{ str_replace('.', ',', $task->estimatedHours) }} h @endif + + @if ($task->dueOn !== null) + {{ __('jobs.tasks.fields.due_on') }}: + @endif +
    + +
    +
  • + @endforeach +
+ @endif +
+ + +

{{ $dialogTitle }}

+ +
+ @if ($dialogJobId !== null && Gate::allows('jobs.manage-tasks', $dialogJobId)) + + + + + + @foreach ($this->userNames as $userId => $name) + + @endforeach + + @endif + + + @foreach (TaskStatus::cases() as $option) + + @endforeach + + + @if ($dialogJobId !== null) +

+ {{ __('jobs.calendar.open_job') }} + @if (Gate::allows('jobs.manage-tasks', $dialogJobId) && $dialogTaskId !== null) + {{ __('jobs.calendar.edit_task') }} + @endif +

+ @endif + + + + @if ($dialogJobId !== null && Gate::allows('jobs.manage-tasks', $dialogJobId)) + + @endif + + +
+
diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index 24f6a9e..4e302ff 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -313,7 +313,10 @@ new class extends Component @can('jobs.manage-tasks', $job->id) @if ($job->status->allowsTasks()) - +
+ + +
@endif @endcan
@@ -348,6 +351,14 @@ new class extends Component
{{ $task->assignees === [] ? __('jobs.not_set') : collect($task->assignees)->pluck('name')->join(', ') }}
{{ __('jobs.tasks.fields.due_on') }}
+
{{ __('jobs.tasks.schedule') }}
+
+ @if ($task->plannedFrom === null) + {{ __('jobs.not_set') }} + @else + {{ __('jobs.tasks.schedule_range', ['from' => $this->formatDate($task->plannedFrom), 'to' => $this->formatDate($task->plannedTo)]) }} + @endif +
{{ __('jobs.tasks.fields.estimated_hours') }}
{{ $task->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $task->estimatedHours).' h' }}
diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡task-checklist.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡task-checklist.blade.php index 0859ffe..aa6f3d6 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡task-checklist.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡task-checklist.blade.php @@ -260,7 +260,8 @@ new class extends Component }; ?> -
+{{-- Named by the task, so the checklists of a job's tasks are distinguishable landmarks. --}} +
@php($canCheck = Gate::allows('jobs.update-task-status', $jobId)) @php($canManage = Gate::allows('jobs.manage-tasks', $jobId)) @php($doneCount = count(array_filter($this->items, fn ($item) => $item->done))) diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php index 683d48e..4bc0c57 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php @@ -13,6 +13,7 @@ use App\Modules\Jobs\Presentation\Livewire\Forms\TaskForm; use App\Modules\Shared\Domain\Exceptions\DomainException; use App\Modules\Users\Application\Contracts\UserAccountQueries; use App\Modules\Users\Domain\Enums\Role; +use Carbon\CarbonImmutable; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; use Livewire\Component; @@ -130,11 +131,12 @@ new class extends Component try { if ($this->taskId === null) { - $addTask->execute($this->jobId, $data, (int) auth()->id()); - session()->flash('status', __('jobs.tasks.created', ['title' => trim($data->title)])); + $taskId = $addTask->execute($this->jobId, $data, (int) auth()->id()); + $message = __('jobs.tasks.created', ['title' => trim($data->title)]); } else { - $updateTask->execute($this->jobId, $this->taskId, $data); - session()->flash('status', __('jobs.tasks.updated', ['title' => trim($data->title)])); + $taskId = $this->taskId; + $updateTask->execute($this->jobId, $taskId, $data); + $message = __('jobs.tasks.updated', ['title' => trim($data->title)]); } } catch (CustomerJobNotFound|TaskNotFound) { abort(404); @@ -144,6 +146,14 @@ new class extends Component return; } + $plannedTo = app(TaskQueries::class)->findTask($this->jobId, $taskId)?->plannedTo; + + if ($data->plannedFrom !== null && $plannedTo !== null && $plannedTo !== ($data->plannedTo ?? $data->plannedFrom)) { + $message .= ' '.__('jobs.tasks.extended', ['to' => CarbonImmutable::parse($plannedTo)->format('j.n.Y')]); + } + + session()->flash('status', $message); + $this->redirect(route('jobs.show', $this->jobId).'#tasks', navigate: true); } @@ -208,6 +218,15 @@ new class extends Component />
+
+ {{ __('jobs.tasks.schedule') }} +

{{ __('jobs.tasks.fields.planned_hint') }}

+
+ + +
+
+
diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡tasks-from-template.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡tasks-from-template.blade.php new file mode 100644 index 0000000..943ce3a --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡tasks-from-template.blade.php @@ -0,0 +1,261 @@ + */ + #[Locked] + public array $serviceUnitIds = []; + + public string $templateId = ''; + + /** + * One row per step of the chosen template, in step order. + * + * @var list + */ + public array $rows = []; + + public function mount(CustomerJobQueries $jobQueries, int $job): void + { + $details = $jobQueries->findDetails($job); + + abort_if($details === null, 404); + + $this->authorize('jobs.manage-tasks', $details->id); + abort_unless($details->status->allowsTasks(), 404); + + $this->jobId = $details->id; + $this->jobTitle = $details->number.' '.$details->name; + $this->serviceUnitIds = array_map(fn (NamedId $unit): int => $unit->id, $details->serviceUnits); + } + + /** + * @return list + */ + #[Computed] + public function templates(): array + { + return app(WorkflowTemplateQueries::class)->activeFor($this->serviceUnitIds); + } + + /** + * The templates as radio options; the description lists the steps. + * + * @return list + */ + #[Computed] + public function options(): array + { + return array_map(fn (WorkflowTemplateDetails $template): array => [ + 'label' => $this->labelOf($template), + 'value' => (string) $template->id, + 'description' => __('jobs.tasks.from_template.steps', [ + 'steps' => implode(' → ', array_map( + fn (WorkflowStepSummary $step): string => $step->workTypeId === null ? $step->title : $step->title.' ('.$step->workTypeName.')', + $template->steps, + )), + ]), + ], $this->templates); + } + + #[Computed] + public function selectedTemplate(): ?WorkflowTemplateDetails + { + foreach ($this->templates as $template) { + if ((string) $template->id === $this->templateId) { + return $template; + } + } + + return null; + } + + /** + * A new template gets empty rows for its steps. + */ + public function updatedTemplateId(): void + { + $this->resetErrorBag(); + $this->rows = array_map(fn (): array => ['due_on' => '', 'estimated_hours' => ''], $this->selectedTemplate?->steps ?? []); + } + + public function add(AddTasksFromWorkflowTemplate $addTasks): void + { + $this->authorize('jobs.manage-tasks', $this->jobId); + + $this->validate( + [ + 'templateId' => ['required', 'integer'], + 'rows' => ['array'], + 'rows.*.due_on' => ['nullable', 'date_format:Y-m-d'], + 'rows.*.estimated_hours' => ['nullable', 'regex:/^\s*\d{1,5}([.,]\d{1,2})?\s*$/'], + ], + [ + 'templateId.required' => __('jobs.tasks.from_template.choose'), + 'templateId.integer' => __('jobs.tasks.from_template.not_available'), + 'rows.*.due_on.date_format' => __('jobs.errors.invalid_date'), + 'rows.*.estimated_hours.regex' => __('jobs.errors.invalid_hours'), + ], + ); + + $template = $this->selectedTemplate; + $schedules = array_map(fn (array $row): TemplateTaskSchedule => new TemplateTaskSchedule( + $row['due_on'] === '' ? null : $row['due_on'], + trim($row['estimated_hours']) === '' ? null : $row['estimated_hours'], + ), $this->rows); + + try { + $count = $addTasks->execute($this->jobId, (int) $this->templateId, (int) auth()->id(), $schedules); + } catch (CustomerJobNotFound) { + abort(404); + } catch (TasksNotAllowedYet) { + $this->addError('templateId', __('jobs.tasks.not_allowed_yet')); + + return; + } catch (InvalidEstimatedHours) { + $this->addError('templateId', __('jobs.errors.invalid_hours')); + + return; + } catch (WorkflowTemplateNotAvailable|InvalidTaskReference) { + unset($this->templates, $this->options, $this->selectedTemplate); + $this->addError('templateId', __('jobs.tasks.from_template.not_available')); + + return; + } + + session()->flash('status', trans_choice('jobs.tasks.from_template.added', $count, [ + 'count' => $count, + 'name' => $template === null ? '' : $this->labelOf($template), + ])); + + $this->redirect(route('jobs.show', $this->jobId).'#tasks', navigate: true); + } + + public function render(): mixed + { + return $this->view()->title(__('jobs.tasks.from_template.title').' – '.$this->jobTitle); + } + + private function labelOf(WorkflowTemplateDetails $template): string + { + return __('jobs.tasks.from_template.option', ['name' => $template->name, 'work_type' => $template->workTypeName]); + } +}; +?> + +
+
+

{{ __('jobs.tasks.from_template.title') }}

+

{{ __('jobs.tasks.job_label') }}: {{ $jobTitle }}

+
+ +

{{ __('jobs.tasks.from_template.intro') }}

+ + @if ($this->options === []) + @error('templateId') + + @enderror + +

{{ __('jobs.tasks.from_template.none') }}

+ + + @else +
+ + + @if (($template = $this->selectedTemplate) !== null) + {{-- An input grid is a form, so a native table rather than . --}} +
+

{{ __('jobs.tasks.from_template.schedule_help') }}

+ + + + + + + + + + + + @foreach ($template->steps as $index => $step) + + + + + + @endforeach + +
{{ __('jobs.tasks.from_template.table_caption', ['name' => $template->name]) }}
{{ __('jobs.tasks.from_template.task') }}{{ __('jobs.tasks.fields.due_on') }}{{ __('jobs.tasks.fields.estimated_hours') }}
+ {{ $step->title }} + {{ $step->workTypeName }} + + + @error('rows.'.$index.'.due_on') +

{{ $message }}

+ @enderror +
+ + @error('rows.'.$index.'.estimated_hours') +

{{ $message }}

+ @enderror +
+
+ @endif + +
+ + +
+ + @endif +
diff --git a/app/Modules/Jobs/Presentation/Routes/web.php b/app/Modules/Jobs/Presentation/Routes/web.php index 9f67ef5..ef34f47 100644 --- a/app/Modules/Jobs/Presentation/Routes/web.php +++ b/app/Modules/Jobs/Presentation/Routes/web.php @@ -10,8 +10,10 @@ Route::middleware(['web', 'auth', 'can:jobs.view']) Route::livewire('/create', 'jobs::form')->middleware('can:jobs.manage')->name('create'); Route::livewire('/quick', 'jobs::quick')->middleware('can:jobs.manage')->name('quick'); Route::livewire('/board', 'jobs::board')->name('board'); + Route::livewire('/calendar', 'jobs::calendar')->name('calendar'); Route::livewire('/{job}', 'jobs::show')->whereNumber('job')->name('show'); Route::livewire('/{job}/edit', 'jobs::form')->whereNumber('job')->middleware('can:jobs.manage')->name('edit'); Route::livewire('/{job}/tasks/create', 'jobs::task-form')->whereNumber('job')->name('tasks.create'); + Route::livewire('/{job}/tasks/from-template', 'jobs::tasks-from-template')->whereNumber('job')->name('tasks.from-template'); Route::livewire('/{job}/tasks/{task}/edit', 'jobs::task-form')->whereNumber(['job', 'task'])->name('tasks.edit'); }); diff --git a/app/Modules/Sales/Infrastructure/CustomerReferencesFromSales.php b/app/Modules/Sales/Infrastructure/CustomerReferencesFromSales.php new file mode 100644 index 0000000..baf5658 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/CustomerReferencesFromSales.php @@ -0,0 +1,17 @@ +where('customer_id', $customerId)->exists(); + } +} diff --git a/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php b/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php index 1302780..66699d2 100644 --- a/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php +++ b/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php @@ -3,11 +3,13 @@ namespace App\Modules\Sales\Infrastructure\Providers; use App\Models\User; +use App\Modules\Customers\Application\Contracts\CustomerReferences; use App\Modules\Sales\Application\Contracts\QuickSaleHours; use App\Modules\Sales\Application\Contracts\QuickSaleProducts; use App\Modules\Sales\Application\Contracts\QuickSaleQueries; use App\Modules\Sales\Domain\Contracts\CashDayRepository; use App\Modules\Sales\Domain\Contracts\QuickSaleRepository; +use App\Modules\Sales\Infrastructure\CustomerReferencesFromSales; use App\Modules\Sales\Infrastructure\HoursForQuickSales; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentCashDayRepository; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleQueries; @@ -36,6 +38,12 @@ class SalesServiceProvider extends ServiceProvider QuickSaleHours::class => HoursForQuickSales::class, ]; + public function register(): void + { + // A customer with quick sales cannot be removed. + $this->app->tag([CustomerReferencesFromSales::class], CustomerReferences::TAG); + } + public function boot(): void { $presentationPath = dirname(__DIR__, 2).'/Presentation'; diff --git a/app/Modules/Shared/Application/Contracts/HolidayOverrides.php b/app/Modules/Shared/Application/Contracts/HolidayOverrides.php new file mode 100644 index 0000000..06d7206 --- /dev/null +++ b/app/Modules/Shared/Application/Contracts/HolidayOverrides.php @@ -0,0 +1,24 @@ + In date order; dates are Y-m-d and inclusive. + */ + public function between(string $from, string $to): array; + + public function find(string $date): ?HolidayOverride; + + public function save(HolidayOverride $override): void; + + public function delete(string $date): void; +} diff --git a/app/Modules/Shared/Application/DTOs/Holiday.php b/app/Modules/Shared/Application/DTOs/Holiday.php new file mode 100644 index 0000000..f5b8e4d --- /dev/null +++ b/app/Modules/Shared/Application/DTOs/Holiday.php @@ -0,0 +1,25 @@ +key === null; + } +} diff --git a/app/Modules/Shared/Application/DTOs/HolidayOverride.php b/app/Modules/Shared/Application/DTOs/HolidayOverride.php new file mode 100644 index 0000000..530a874 --- /dev/null +++ b/app/Modules/Shared/Application/DTOs/HolidayOverride.php @@ -0,0 +1,18 @@ + In date order. + */ + public function between(string $from, string $to): array + { + $fromDate = self::date($from); + $toDate = self::date($to); + $holidays = []; + + for ($year = (int) $fromDate->format('Y'); $year <= (int) $toDate->format('Y'); $year++) { + foreach (FinnishHolidays::forYear($year) as $date => $key) { + if ($date >= $from && $date <= $to) { + $holidays[$date] = new Holiday($date, $key, null, true); + } + } + } + + foreach ($this->overrides->between($from, $to) as $override) { + $calculated = $holidays[$override->date] ?? null; + + if ($calculated !== null) { + $holidays[$override->date] = new Holiday($override->date, $calculated->key, null, $override->isHoliday); + } elseif ($override->isHoliday) { + $holidays[$override->date] = new Holiday($override->date, null, $override->name, true); + } + } + + ksort($holidays); + + return array_values($holidays); + } + + /** + * The holidays in use between the dates. + * + * @return list Y-m-d dates in order. + */ + public function activeDatesBetween(string $from, string $to): array + { + return array_values(array_map( + fn (Holiday $holiday): string => $holiday->date, + array_filter($this->between($from, $to), fn (Holiday $holiday): bool => $holiday->active), + )); + } + + /** + * @throws NotAHoliday + */ + public function disable(string $date): void + { + $this->calculatedKey($date); + $this->overrides->save(new HolidayOverride($date, false)); + } + + /** + * @throws NotAHoliday + */ + public function enable(string $date): void + { + $this->calculatedKey($date); + $this->overrides->delete($date); + } + + /** + * @throws InvalidHolidayName + * @throws HolidayAlreadyExists + */ + public function addCompanyDay(string $date, string $name): void + { + $name = trim((string) preg_replace('/\s+/u', ' ', $name)); + + if ($name === '' || mb_strlen($name) > 100) { + throw new InvalidHolidayName; + } + + self::date($date); + + if (isset(FinnishHolidays::forYear((int) substr($date, 0, 4))[$date]) || $this->overrides->find($date) !== null) { + throw new HolidayAlreadyExists; + } + + $this->overrides->save(new HolidayOverride($date, true, $name)); + } + + /** + * @throws NotAHoliday + */ + public function removeCompanyDay(string $date): void + { + $override = $this->overrides->find($date); + + if ($override === null || ! $override->isHoliday || isset(FinnishHolidays::forYear((int) substr($date, 0, 4))[$date])) { + throw new NotAHoliday; + } + + $this->overrides->delete($date); + } + + /** + * @throws NotAHoliday + */ + private function calculatedKey(string $date): string + { + self::date($date); + + return FinnishHolidays::forYear((int) substr($date, 0, 4))[$date] ?? throw new NotAHoliday; + } + + private static function date(string $value): DateTimeImmutable + { + $date = DateTimeImmutable::createFromFormat('!Y-m-d', $value); + + if ($date === false || $date->format('Y-m-d') !== $value) { + throw new InvalidArgumentException("Not a Y-m-d date: {$value}"); + } + + return $date; + } +} diff --git a/app/Modules/Shared/Domain/Exceptions/HolidayAlreadyExists.php b/app/Modules/Shared/Domain/Exceptions/HolidayAlreadyExists.php new file mode 100644 index 0000000..155bb5a --- /dev/null +++ b/app/Modules/Shared/Domain/Exceptions/HolidayAlreadyExists.php @@ -0,0 +1,13 @@ + Y-m-d date => holiday key, in date order. + */ + public static function forYear(int $year): array + { + $easter = self::easterSunday($year); + $midsummerEve = new DateTimeImmutable(sprintf('%04d-06-19', $year)); + + while ($midsummerEve->format('N') !== '5') { + $midsummerEve = $midsummerEve->add(new DateInterval('P1D')); + } + + $holidays = [ + sprintf('%04d-01-01', $year) => 'new_years_day', + sprintf('%04d-01-06', $year) => 'epiphany', + $easter->sub(new DateInterval('P2D'))->format('Y-m-d') => 'good_friday', + $easter->add(new DateInterval('P1D'))->format('Y-m-d') => 'easter_monday', + sprintf('%04d-05-01', $year) => 'may_day', + $easter->add(new DateInterval('P39D'))->format('Y-m-d') => 'ascension_day', + $midsummerEve->format('Y-m-d') => 'midsummer_eve', + sprintf('%04d-12-06', $year) => 'independence_day', + sprintf('%04d-12-24', $year) => 'christmas_eve', + sprintf('%04d-12-25', $year) => 'christmas_day', + sprintf('%04d-12-26', $year) => 'st_stephens_day', + ]; + + ksort($holidays); + + return $holidays; + } + + /** + * Easter Sunday by the anonymous Gregorian algorithm (Meeus/Jones/Butcher). + */ + public static function easterSunday(int $year): DateTimeImmutable + { + $a = $year % 19; + $b = intdiv($year, 100); + $c = $year % 100; + $d = intdiv($b, 4); + $e = $b % 4; + $f = intdiv($b + 8, 25); + $g = intdiv($b - $f + 1, 3); + $h = (19 * $a + $b - $d - $g + 15) % 30; + $i = intdiv($c, 4); + $k = $c % 4; + $l = (32 + 2 * $e + 2 * $i - $h - $k) % 7; + $m = intdiv($a + 11 * $h + 22 * $l, 451); + $month = intdiv($h + $l - 7 * $m + 114, 31); + $day = (($h + $l - 7 * $m + 114) % 31) + 1; + + return new DateTimeImmutable(sprintf('%04d-%02d-%02d', $year, $month, $day)); + } +} diff --git a/app/Modules/Shared/Infrastructure/Persistence/DatabaseHolidayOverrides.php b/app/Modules/Shared/Infrastructure/Persistence/DatabaseHolidayOverrides.php new file mode 100644 index 0000000..0106132 --- /dev/null +++ b/app/Modules/Shared/Infrastructure/Persistence/DatabaseHolidayOverrides.php @@ -0,0 +1,52 @@ +whereBetween('date', [$from, $to]) + ->orderBy('date') + ->get() + ->map(fn ($row): HolidayOverride => self::toOverride($row)) + ->values() + ->all(); + } + + public function find(string $date): ?HolidayOverride + { + $row = DB::table('holiday_overrides')->where('date', $date)->first(); + + return $row === null ? null : self::toOverride($row); + } + + public function save(HolidayOverride $override): void + { + $now = now(); + + DB::table('holiday_overrides')->upsert( + [['date' => $override->date, 'is_holiday' => $override->isHoliday, 'name' => $override->name, 'created_at' => $now, 'updated_at' => $now]], + ['date'], + ['is_holiday', 'name', 'updated_at'], + ); + } + + public function delete(string $date): void + { + DB::table('holiday_overrides')->where('date', $date)->delete(); + } + + private static function toOverride(object $row): HolidayOverride + { + return new HolidayOverride(substr((string) $row->date, 0, 10), (bool) $row->is_holiday, $row->name === null ? null : (string) $row->name); + } +} diff --git a/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php b/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php index 7f5feb8..d5b802c 100644 --- a/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php +++ b/app/Modules/Shared/Infrastructure/Providers/SharedServiceProvider.php @@ -4,9 +4,11 @@ namespace App\Modules\Shared\Infrastructure\Providers; use App\Models\User; use App\Modules\Shared\Application\Contracts\EventDispatcher; +use App\Modules\Shared\Application\Contracts\HolidayOverrides; use App\Modules\Shared\Application\Contracts\Settings; use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Shared\Infrastructure\Events\LaravelEventDispatcher; +use App\Modules\Shared\Infrastructure\Persistence\DatabaseHolidayOverrides; use App\Modules\Shared\Infrastructure\Persistence\DatabaseSettings; use App\Modules\Shared\Infrastructure\Persistence\LaravelTransactionManager; use App\Modules\Shared\Presentation\Http\Middleware\SetSecurityHeaders; @@ -25,6 +27,7 @@ class SharedServiceProvider extends ServiceProvider TransactionManager::class => LaravelTransactionManager::class, EventDispatcher::class => LaravelEventDispatcher::class, Settings::class => DatabaseSettings::class, + HolidayOverrides::class => DatabaseHolidayOverrides::class, ]; public function boot(): void diff --git a/app/Modules/Shared/Presentation/Livewire/⚡holidays.blade.php b/app/Modules/Shared/Presentation/Livewire/⚡holidays.blade.php new file mode 100644 index 0000000..b50a69b --- /dev/null +++ b/app/Modules/Shared/Presentation/Livewire/⚡holidays.blade.php @@ -0,0 +1,222 @@ +authorize('settings.manage'); + + if ($this->year < 2000 || $this->year > 2100) { + $this->year = (int) now()->format('Y'); + } + } + + /** + * @return list + */ + #[Computed] + public function holidays(): array + { + return array_map(fn (Holiday $holiday): array => [ + 'date' => $holiday->date, + 'day' => $this->formatDay($holiday->date), + 'name' => $this->holidayName($holiday), + 'kind' => __($holiday->isCompanyDay() ? 'holidays.kinds.company' : 'holidays.kinds.public'), + 'active' => $holiday->active, + 'company' => $holiday->isCompanyDay(), + ], app(HolidayCalendar::class)->between($this->year.'-01-01', $this->year.'-12-31')); + } + + /** + * @return list + */ + public function headers(): array + { + return [ + ['index' => 'day', 'label' => __('holidays.columns.date'), 'sortable' => false], + ['index' => 'name', 'label' => __('holidays.columns.name'), 'sortable' => false], + ['index' => 'kind', 'label' => __('holidays.columns.kind'), 'sortable' => false], + ['index' => 'state', 'label' => __('holidays.columns.state'), 'sortable' => false], + ['index' => 'actions', 'label' => __('holidays.columns.actions'), 'sortable' => false], + ]; + } + + public function changeYear(int $step): void + { + $this->authorize('settings.manage'); + + $this->year = max(2000, min(2100, $this->year + ($step < 0 ? -1 : 1))); + $this->statusMessage = __('holidays.showing_year', ['year' => $this->year]); + unset($this->holidays); + } + + public function disable(string $date, HolidayCalendar $calendar): void + { + $this->change($date, fn () => $calendar->disable($date), 'holidays.disabled'); + } + + public function enable(string $date, HolidayCalendar $calendar): void + { + $this->change($date, fn () => $calendar->enable($date), 'holidays.enabled'); + } + + public function remove(string $date, HolidayCalendar $calendar): void + { + $this->change($date, fn () => $calendar->removeCompanyDay($date), 'holidays.removed'); + } + + public function add(HolidayCalendar $calendar): void + { + $this->authorize('settings.manage'); + $this->statusMessage = ''; + + $this->validate([ + 'date' => ['required', 'date_format:Y-m-d', 'after_or_equal:2000-01-01', 'before_or_equal:2100-12-31'], + 'name' => ['required', 'string', 'max:100'], + ], [ + 'date.*' => __('holidays.errors.date'), + 'name.*' => __('holidays.errors.name'), + ]); + + try { + $calendar->addCompanyDay($this->date, $this->name); + } catch (InvalidHolidayName) { + $this->addError('name', __('holidays.errors.name')); + + return; + } catch (HolidayAlreadyExists) { + $this->addError('date', __('holidays.errors.exists')); + + return; + } + + $this->statusMessage = __('holidays.added', ['day' => $this->formatDay($this->date), 'name' => trim($this->name)]); + $this->year = (int) substr($this->date, 0, 4); + $this->reset('date', 'name'); + unset($this->holidays); + } + + public function render(): mixed + { + return $this->view()->title(__('holidays.title')); + } + + private function change(string $date, \Closure $action, string $messageKey): void + { + $this->authorize('settings.manage'); + + $holiday = collect($this->holidays)->firstWhere('date', $date); + + try { + $action(); + } catch (NotAHoliday|\InvalidArgumentException) { + $this->statusMessage = __('holidays.not_changed'); + + return; + } + + unset($this->holidays); + $this->statusMessage = __($messageKey, ['day' => $this->formatDay($date), 'name' => $holiday['name'] ?? '']); + } + + private function holidayName(Holiday $holiday): string + { + return $holiday->key === null ? (string) $holiday->name : __('holidays.names.'.$holiday->key); + } + + private function formatDay(string $date): string + { + $day = CarbonImmutable::createFromFormat('!Y-m-d', $date); + + return ! $day instanceof CarbonImmutable ? $date :__('holidays.weekdays.'.$day->dayOfWeekIso).' '.$day->format('j.n.Y'); + } +}; +?> + +
+
+

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

+

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

+

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

+
+ +

{{ $statusMessage }}

+ +
+
+ +

{{ __('holidays.year_heading', ['year' => $year]) }}

+ +
+ + + @interact('column_day', $holiday) + {{ $holiday['day'] }} + @endinteract + + @interact('column_name', $holiday) + {{ $holiday['name'] }} + @endinteract + + @interact('column_kind', $holiday) + {{ $holiday['kind'] }} + @endinteract + + @interact('column_state', $holiday) + @if ($holiday['active']) + + @else + + @endif + @endinteract + + @interact('column_actions', $holiday) + @if ($holiday['company']) + + @elseif ($holiday['active']) + + @else + + @endif + @endinteract + +
+ +
+

{{ __('holidays.add_heading') }}

+ +
+ + +
+ +
+ +
+
diff --git a/app/Modules/Shared/Presentation/Routes/web.php b/app/Modules/Shared/Presentation/Routes/web.php index 91142c1..587e1f6 100644 --- a/app/Modules/Shared/Presentation/Routes/web.php +++ b/app/Modules/Shared/Presentation/Routes/web.php @@ -7,4 +7,5 @@ Route::middleware(['web', 'auth', 'can:settings.manage']) ->name('settings.') ->group(function () { Route::livewire('/company', 'shared::company')->name('company'); + Route::livewire('/holidays', 'shared::holidays')->name('holidays'); }); diff --git a/database/migrations/2026_11_24_144942_create_workflow_templates_tables.php b/database/migrations/2026_11_24_144942_create_workflow_templates_tables.php new file mode 100644 index 0000000..9bf4381 --- /dev/null +++ b/database/migrations/2026_11_24_144942_create_workflow_templates_tables.php @@ -0,0 +1,45 @@ +id(); + $table->foreignId('work_type_id')->constrained()->restrictOnDelete(); + $table->string('name', 100); + $table->boolean('is_active')->default(true); + $table->timestamps(); + }); + + Schema::create('workflow_template_steps', function (Blueprint $table) { + $table->id(); + $table->foreignId('workflow_template_id')->constrained()->cascadeOnDelete(); + // Null: the step's task gets the template's work type. + $table->foreignId('work_type_id')->nullable()->constrained()->restrictOnDelete(); + $table->string('title'); + $table->text('description')->nullable(); + $table->unsignedInteger('sort_order'); + $table->timestamps(); + + $table->index(['workflow_template_id', 'sort_order']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('workflow_template_steps'); + Schema::dropIfExists('workflow_templates'); + } +}; diff --git a/database/migrations/2026_11_24_155202_create_holiday_overrides_table.php b/database/migrations/2026_11_24_155202_create_holiday_overrides_table.php new file mode 100644 index 0000000..f33c48b --- /dev/null +++ b/database/migrations/2026_11_24_155202_create_holiday_overrides_table.php @@ -0,0 +1,28 @@ +id(); + $table->date('date')->unique(); + $table->boolean('is_holiday'); + $table->string('name', 100)->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('holiday_overrides'); + } +}; diff --git a/database/migrations/2026_11_24_155203_add_schedule_to_tasks_table.php b/database/migrations/2026_11_24_155203_add_schedule_to_tasks_table.php new file mode 100644 index 0000000..84a879f --- /dev/null +++ b/database/migrations/2026_11_24_155203_add_schedule_to_tasks_table.php @@ -0,0 +1,40 @@ +date('planned_from')->nullable()->after('due_on'); + $table->date('planned_to')->nullable()->after('planned_from'); + $table->index(['planned_from', 'planned_to']); + }); + + Schema::create('task_bookings', function (Blueprint $table) { + $table->foreignId('task_id')->constrained('tasks')->cascadeOnDelete(); + $table->foreignId('user_id')->constrained('users')->cascadeOnDelete(); + $table->date('day'); + $table->unsignedInteger('minutes'); + $table->primary(['task_id', 'user_id', 'day']); + $table->index(['user_id', 'day']); + }); + } + + public function down(): void + { + Schema::dropIfExists('task_bookings'); + + Schema::table('tasks', function (Blueprint $table) { + $table->dropIndex(['planned_from', 'planned_to']); + $table->dropColumn(['planned_from', 'planned_to']); + }); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 88799b9..4bd6706 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -113,7 +113,7 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli | Palveluyksiköt | `service_units` | Yksi tai useampi *(K28)* | | Alkamispäivä | `starts_on` | | | Määräaika | `due_on` | | -| Aikataulu | `planned_from`, `planned_to` | Suunniteltu toteutusaikataulu; näkyy kalenterinäkymässä *(K20)* | +| Aikataulu | `planned_from`, `planned_to` | Suunniteltu toteutusaikataulu *(K20)*. Kalenterinäkymä näyttää työn tehtävät tekijöittäin, ei työtä itseään (18.3). | | Kesto / laji | `kind` | ks. 5.2 | | Tila | `status` | ks. 5.3 | | Prioriteetti | `priority` | ks. 5.4 | @@ -239,15 +239,16 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä ### 8.2 Tehtävät -- Tehtävät ovat asiakastyön alla. Kentät: nimi, kuvaus, tekijät (yksi tai useampi käyttäjä), määräpäivä, arvioitu aika, tila, tarkistuslista (todo) *(K26, K33, K35)*. +- Tehtävät ovat asiakastyön alla. Kentät: nimi, kuvaus, tekijät (yksi tai useampi käyttäjä), määräpäivä, arvioitu aika, aikataulu (suunniteltu alku ja loppu), tila, tarkistuslista (todo) *(K26, K33, K35)*. - Tehtävän tilat oletuksena: odottaa (`Waiting`), työn alla (`InProgress`), tarkastettavana (`InReview`), valmis (`Done`). Määräaika ja myöhässä-ilmaisin. -- Tehtävien sarakkeet voivat olla palveluyksikkökohtaisia, ja ne määritellään asetuksista *(K34)*. +- ~~Tehtävien sarakkeet voivat olla palveluyksikkökohtaisia, ja ne määritellään asetuksista *(K34)*.~~ Päätös: tehtävien Kanbania ei tehdä. Tehtävän tilat ovat kiinteät, ja tehtäviä järjestetään henkilöittäin tehtäväkalenterissa (18.3). - Kommentit tehtävälle *(K27)*. Kuvatiedostojen lähetys tehtävälle (esim. puhelimen kameralla) *(K26)*. ### 8.3 Työnkulkupohjat *(K32)* -- Palvelun työtehtävälle voi määritellä pohjan, joka luo valmiin tehtävälistan, esim. videokuvaus = suunnittelu → kuvaus → editointi → tarkastus → toimitus. -- Pohjia muokataan pohjatietojen hallinnasta (pääkäyttäjä ja johto). +- Palvelun työtehtävälle voi määritellä pohjan, joka luo valmiin tehtävälistan, esim. videokuvaus = suunnittelu → kuvaus → editointi → tarkastus → toimitus. Työtehtävällä voi olla useita nimettyjä pohjia. +- Vaiheella on nimi, kuvaus ja työtehtävä: oletuksena pohjan työtehtävä, tai oma työtehtävä pohjan palveluyksiköstä tai kaikille yhteisistä, jotta tunnit hinnoitellaan vaiheittain oikein. +- Pohjia muokataan pohjatietojen hallinnasta (pääkäyttäjä ja johto). Pohjia ei poisteta, vaan ne poistetaan käytöstä. Luodut tehtävät ovat kopioita: pohjan muutos ei muuta niitä *(valmis)*. ## 9. Tuntikirjaus *(K37–K41)* @@ -351,7 +352,9 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - Nimi on yksilöllinen saman tason sisällä (kirjainkoosta riippumatta). Rivejä ei poisteta, vaan ne poistetaan käytöstä; viiteavaimet estävät poiston. - `vat_rates` *(V2, olemassa)*: `name`, `basis_points` (sadasosaprosentteina, 2550 = 25,5 %), `is_default`, `is_active`, `sort_order` - `products` *(V2, olemassa)*: `name`, `unit` (`piece`/`page`/`square_metre`/`metre`/`hour`/`package`), `price_cents` (kuluttajatuotteella verollinen, muuten veroton), `vat_rate_id`, `is_consumer_product`, `auto_hours`, `work_type_id` (nullable, pakollinen jos `auto_hours` > 0), `is_active`, `sort_order` -- `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, työajanseuranta päällä) +- `workflow_templates` *(V3, olemassa)*: `work_type_id`, `name` (yksilöllinen työtehtävän sisällä), `is_active`; `workflow_template_steps`: `workflow_template_id`, `work_type_id` (nullable = pohjan työtehtävä), `title`, `description`, `sort_order` +- `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, työajanseuranta päällä, `jobs.daily_capacity_hours` = päiväkatto tunteina, oletus 8) +- `holiday_overrides` *(V3, olemassa)*: `date` (uniikki), `is_holiday` (false = laskettu arkipyhä poistettu käytöstä, true = yrityksen oma vapaapäivä), `name` (oman päivän nimi) **Jobs** (asiakastyöt) - `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by` *(olemassa)*; `quoted_amount_cents`, `monthly_fee_cents`, `completed_at` (asetetaan, kun työ saavuttaa lukitsevan tilan; tyhjennetään, kun lukitus avataan), `quick_sale_year` (uniikki; merkitsee vuoden pikamyyntityön) *(V2, olemassa)* @@ -363,13 +366,12 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `customer_job_changes`: `customer_job_id`, `user_id`, `field`, `old_value`, `new_value`, `created_at` **Tasks** -- `tasks`: `customer_job_id`, `work_type_id`, `title`, `description`, `status`, `due_on`, `estimated_hours`, `created_by` *(olemassa)* +- `tasks`: `customer_job_id`, `work_type_id`, `title`, `description`, `status`, `due_on`, `estimated_hours`, `created_by` *(olemassa)*; `planned_from`, `planned_to` *(V3, olemassa)* +- `task_bookings` *(V3, olemassa)*: `task_id`, `user_id`, `day`, `minutes` (tehtävän arvion varaus tekijän päivästä) - `task_assignees`: `task_id`, `user_id` *(olemassa)* - `task_checklist_items` *(V3)*: `task_id`, `text`, `is_done`, `sort_order` - `task_comments` *(V3)*: `task_id`, `user_id`, `body` - `task_images` *(V3)*: `task_id`, `user_id`, `path`, `original_name` -- `task_columns` *(V3)*: `service_unit_id` (nullable = oletus), `name`, `status_key`, `sort_order` -- `workflow_templates` *(V3)*: `work_type_id`, `name`; `workflow_template_steps`: `workflow_template_id`, `title`, `description`, `sort_order` **TimeTracking** - `time_entries`: `user_id`, `task_id`, `customer_job_id` (denormalisoitu), `work_type_id` (tehtävän työtehtävä kirjaushetkellä), `worked_on`, `hours`, `note` *(olemassa; uniikki käyttäjä + tehtävä + päivä)*, `approved_at`, `approved_by`, `billing_export_id` (laskuaineisto, jolla tunnit laskutettiin) *(V2, olemassa)* @@ -407,7 +409,7 @@ Tunnit kirjataan tehtäville, joten perustehtävät ja palveluyksiköiden työte Hinnasto ja tuotteet, rahakentät ja henkilökohtaiset näkyvyysoikeudet, kulut, tuntien hyväksyntä ja lukitus, laskuaineiston vienti Fennoaan (CSV/Excel), kuukausilaskutusrivit, pikamyynti. **Vaihe 3 – tehtävien hallinta** -Tehtävien Kanban-sarakkeet asetuksista palveluyksiköittäin, tarkistuslistat *(valmis)*, kommentit, kuvat, työnkulkupohjat, kalenterinäkymä, kenttien yksinkertaistus palveluyksiköittäin. +Tarkistuslistat *(valmis)*, kommentit, kuvat, työnkulkupohjat *(valmis)*, tehtäväkalenteri henkilöittäin ja arkipyhät *(valmis; korvaa tehtävien Kanban-sarakkeet, K34)*, kenttien yksinkertaistus palveluyksiköittäin. **Vaihe 4 – laajennukset** Alihankkijoiden näkymät ja rajaukset, raportit, ilmoitukset, Fennoa-rajapinta, PWA. @@ -424,6 +426,7 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t - Asiakkaalle voi lisätä, muokata ja poistaa yhteyshenkilöitä ja laskutusyksiköitä asiakkaan sivulla *(valmis)*. Poisto vahvistetaan dialogissa. - Kun asiakastyö viittaa yhteyshenkilöön tai laskutusyksikköön, sen poisto estetään ja asiakassivu kertoo syyn *(valmis)*. - Sisäinen asiakas on merkitty listalla ja asiakassivulla, eikä sitä voi poistaa *(valmis)*. +- Asiakkaan voi poistaa asiakkaan sivulta (vahvistus dialogissa, kaikki paitsi alihankkija), kun siihen ei liity mitään: ei yhteyshenkilöitä, laskutusyksiköitä, asiakastöitä, pikamyyntejä eikä laskuja. Poista asiakas -painike näkyy vain asiakkailla, jotka voi poistaa *(valmis)*. ### 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ä 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ä). @@ -502,6 +505,23 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t - Muut kuin alihankkijat lisäävät kohtia (1–255 merkkiä), muokkaavat niitä rivillä, järjestävät ne Siirrä ylös / Siirrä alas -painikkeilla ja poistavat ne. Kohdan poistoa ei vahvisteta dialogissa; muutokset ilmoitetaan ruudunlukijalle, ja fokus pysyy käytetyssä painikkeessa tai siirtyy lisäyskenttään. - Kohdat poistuvat tehtävän mukana. +### 18.2 Työnkulkupohjat *(valmis)* +- Pohjatiedot-sivulta linkki Työnkulkupohjat-sivulle (`/catalog/workflow-templates`, pääkäyttäjä ja johto): pohjat palveluyksiköittäin (nimi, työtehtävä, vaiheiden määrä), lisäys, muokkaus ja käytöstä poisto valintaruudulla. +- Pohjan lomake: nimi, työtehtävä ja vaiheet (tehtävän nimi 1–255 merkkiä, työtehtävä, kuvaus). Vaiheen voi lisätä, siirtää Siirrä ylös / Siirrä alas -painikkeilla ja poistaa (vähintään yksi vaihe jää); muutokset ilmoitetaan ruudunlukijalle, ja fokus siirtyy uuden vaiheen nimeen tai pysyy käytetyssä painikkeessa. Kaikki tallennetaan kerralla. +- Työn sivulla "Lisää tehtävät pohjasta" (`/jobs/{työ}/tasks/from-template`, muille kuin alihankkijoille, kun tehtäviä voi lisätä): valitaan käytössä oleva pohja, jonka työtehtävä kuuluu työn palveluyksiköihin tai kaikille yhteisiin; vaiheet näkyvät valinnan kuvauksessa. Kun pohja on valittu, sen tehtävät näytetään taulukossa, jossa jokaiselle voi antaa vapaaehtoisen määräpäivän ja arvioidun ajan (h); virheet näytetään solussa. Jokaisesta vaiheesta lisätään tehtävä järjestyksessä tilaan Odottaa, tekijänä lisääjä, ja ilmoitus kertoo lisättyjen määrän. + +### 18.3 Tehtäväkalenteri *(valmis)* +- Valikon Kalenteri (`/jobs/calendar`, kaikki kirjautuneet): rullaava kaksi viikkoa tästä päivästä, painikkeet Edelliset 2 viikkoa / Tänään / Seuraavat 2 viikkoa. Rivi jokaiselle aktiiviselle käyttäjälle (oma rivi ensin) ja rivi Ei tekijää; suodattimet palveluyksikkö ja Vain oma rivi. Alihankkija näkee vain oman rivinsä ja liitettyjen töidensä tehtävät, ja hän voi vaihtaa vain tilaa. +- Tehtävällä on aikataulu (suunniteltu alku ja loppu), joka näkyy palkkina jokaisen tekijän rivillä. Päällekkäiset tehtävät pinotaan omille kaistoilleen, joten samalle päivälle voi asettaa useita lyhyitä tehtäviä. Palkissa näkyvät nimi, työn numero, tila tekstinä ja tunnit; jos aikataulu päättyy määräpäivän jälkeen, palkissa on "Myöhässä" kuvakkeineen. +- **Päiväkuorma:** tehtävän arvioitu aika varataan jokaiselta tekijältä (jokainen kantaa koko arvion) ja jaetaan tasan jakson arkipäiville; arkipäiviä eivät ole la, su eivätkä käytössä olevat arkipyhät. Jos jaksossa on vain viikonloppu- tai pyhäpäiviä, arvio jaetaan niille. Henkilön päivään varataan enintään päiväkatto (8 h, asetus `jobs.daily_capacity_hours`) miinus muiden avoimien tehtävien varaukset; ylittävä osa siirtyy seuraavalle arkipäivälle, ja tehtävän loppu siirtyy myöhemmäksi (ilmoitetaan). Muiden tehtävien varaukset eivät muutu. Valmiit tehtävät eivät vie kapasiteettia. Päivän solussa näkyy kuorma, esim. "6 / 8 h". Ilman arviota tehtävä ei kuormita. +- **Muutokset hiirellä:** palkin rungosta vetämällä tehtävä siirtyy ajassa ja toisen henkilön riville (rivin henkilö korvataan tekijänä, muut tekijät säilyvät); reunoista vetämällä muuttuu alku tai loppu. Aikatauluttamattomat avoimet tehtävät listataan kalenterin alla, ja ne voi vetää päivälle; ilman loppua tehtävä saa niin monta arkipäivää kuin arvio päiväkatolla vaatii. +- **Näppäimistöllä:** jokainen palkki on painike, joka avaa dialogin: alkaa, päättyy, tekijä, tila, linkit työhön ja tehtävän muokkaukseen sekä Poista aikataulu. Muutos ilmoitetaan `aria-live`-alueella ja fokus palaa palkkiin. Puhelimella ja kapeassa ikkunassa ruudukon sijaan näytetään lista henkilöittäin samoin dialogein. +- Tehtävän lomakkeella on kentät Aikataulu alkaa ja Aikataulu päättyy, ja työn sivun tehtäväkortissa näkyy aikataulu. + +### 18.4 Arkipyhät *(valmis)* +- Valikon Arkipyhät (`/settings/holidays`, pääkäyttäjä): Suomen arkipyhät lasketaan automaattisesti joka vuodelle (uudenvuodenpäivä, loppiainen, pitkäperjantai, 2. pääsiäispäivä, vappu, helatorstai, juhannusaatto, itsenäisyyspäivä, jouluaatto, joulupäivä, tapaninpäivä). Laskettu pyhä poistetaan käytöstä tai otetaan takaisin käyttöön, ja yrityksen omia vapaapäiviä lisätään (päivä ja nimi) ja poistetaan. +- Tehtäväkalenteri näyttää arkipyhät viikonlopun värillä ja nimellä, eivätkä ne ole kuormanjaon arkipäiviä, mutta niillekin voi aikatauluttaa tehtäviä. Muutos ei siirrä jo tehtyjä varauksia. + ## 19. Avoimet kysymykset 1. ~~**Lukitus**~~: ratkaistu – vain johto avaa valmiin työn lukituksen siirtämällä työn aiempaan tilaan, ja avaus näkyy muutoshistoriassa (5.3). diff --git a/lang/fi/catalog.php b/lang/fi/catalog.php index 0e0bb1f..e92a42c 100644 --- a/lang/fi/catalog.php +++ b/lang/fi/catalog.php @@ -12,6 +12,55 @@ return [ 'yes' => 'Kyllä', 'no' => 'Ei', 'prices_link' => 'Hinnasto: tuntihinnat, tuotteet ja km-hinta', + 'workflows_link' => 'Työnkulkupohjat: valmiit tehtävälistat työtehtäville', + + 'workflows' => [ + 'title' => 'Työnkulkupohjat', + 'intro' => 'Pohjasta luodaan asiakastyölle valmis tehtävälista, esim. videokuvaus: suunnittelu → kuvaus → editointi → tarkastus → toimitus. Pohjan muutos ei muuta jo luotuja tehtäviä. Pohjia ei poisteta, vaan ne poistetaan käytöstä.', + 'back_to_catalog' => 'Takaisin pohjatietoihin', + 'none' => 'Ei vielä pohjia.', + 'add' => 'Lisää pohja', + 'create_title' => 'Uusi työnkulkupohja', + 'edit_title' => 'Muokkaa työnkulkupohjaa', + 'name_help' => 'Esim. Lyhyt video. Samalla työtehtävällä voi olla useita pohjia.', + 'work_type' => 'Työtehtävä', + 'work_type_help' => 'Pohja tarjotaan töille, joiden palveluyksikössä työtehtävä on (kaikille yhteisten työtehtävien pohjat kaikille töille).', + 'choose_work_type' => 'Valitse työtehtävä', + 'step_count' => 'Vaiheita', + 'steps' => 'Vaiheet', + 'steps_help' => 'Jokaisesta vaiheesta tulee tehtävä tässä järjestyksessä.', + 'step_legend' => 'Vaihe :number', + 'step_title' => 'Tehtävän nimi', + 'step_work_type' => 'Tehtävän työtehtävä', + 'step_work_type_named' => 'Tehtävän työtehtävä, vaihe :number', + 'step_work_type_help' => 'Tunnit hinnoitellaan tämän työtehtävän tuntihinnalla.', + 'template_work_type' => 'Pohjan työtehtävä', + 'step_description' => 'Kuvaus', + 'add_step' => 'Lisää vaihe', + 'move_up' => 'Siirrä ylös', + 'move_down' => 'Siirrä alas', + 'move_up_named' => 'Siirrä ylös: vaihe :number', + 'move_down_named' => 'Siirrä alas: vaihe :number', + 'remove_step' => 'Poista vaihe', + 'remove_step_named' => 'Poista vaihe :number', + 'status' => [ + 'step_added' => 'Vaihe :number lisätty.', + 'step_moved' => 'Vaihe :from siirretty kohtaan :to.', + 'step_removed' => 'Vaihe :number poistettu.', + 'already_first' => 'Vaihe :number on jo ensimmäisenä.', + 'already_last' => 'Vaihe :number on jo viimeisenä.', + 'deactivated' => ':name poistettu käytöstä. Sitä ei tarjota töille.', + ], + 'errors' => [ + 'name_taken' => 'Työtehtävällä on jo tämänniminen pohja.', + 'work_type_required' => 'Valitse työtehtävä.', + 'steps_required' => 'Lisää pohjaan vähintään yksi vaihe.', + 'step_title_required' => 'Anna tehtävän nimi.', + 'invalid_step_title' => 'Tehtävän nimen pituus voi olla enintään 255 merkkiä.', + 'step_work_type_not_allowed' => 'Valitse käytössä oleva työtehtävä pohjan palveluyksiköstä tai kaikille yhteisistä.', + 'description_too_long' => 'Kuvauksen pituus voi olla enintään 5 000 merkkiä.', + ], + ], 'actions' => [ 'edit' => 'Muokkaa', diff --git a/lang/fi/customers.php b/lang/fi/customers.php index 1c251f9..4c853a0 100644 --- a/lang/fi/customers.php +++ b/lang/fi/customers.php @@ -19,6 +19,7 @@ return [ 'updated' => 'Asiakkaan :name tiedot tallennettu.', 'edit_details' => 'Muokkaa tietoja', 'remove' => 'Poista', + 'remove_customer' => 'Poista asiakas', 'customer_label' => 'Asiakas', 'internal' => 'Sisäinen', 'internal_description' => 'Oma yritys. Sen asiakastöille kirjataan sisäinen työ, kuten hallinto, myynti ja koulutus.', @@ -69,11 +70,15 @@ return [ 'removal' => [ 'title' => 'Vahvista poisto', + 'question_customer' => 'Poistetaanko asiakas :name? Poistoa ei voi perua.', 'question_contact' => 'Poistetaanko yhteyshenkilö :name? Poistoa ei voi perua.', 'question_billing_unit' => 'Poistetaanko laskutusyksikkö :name? Poistoa ei voi perua.', + 'removed_customer' => 'Asiakas :name poistettu.', 'removed_contact' => 'Yhteyshenkilö :name poistettu.', 'removed_billing_unit' => 'Laskutusyksikkö :name poistettu.', 'already_removed' => 'Riviä ei löytynyt. Se on ehkä jo poistettu.', + 'in_use_customer' => 'Asiakasta :name ei poistettu, koska sillä on yhteyshenkilöitä, laskutusyksiköitä, asiakastöitä, myyntejä tai laskuja. Asiakkaan voi poistaa vain, kun siihen ei liity mitään.', + 'internal_customer' => 'Sisäistä asiakasta ei voi poistaa.', 'in_use_contact' => 'Yhteyshenkilöä :name ei poistettu, koska se on valittu asiakastyölle. Vaihda asiakastyölle ensin toinen yhteyshenkilö.', 'in_use_billing_unit' => 'Laskutusyksikköä :name ei poistettu, koska se on valittu asiakastyölle. Vaihda asiakastyölle ensin toinen laskutusyksikkö.', ], diff --git a/lang/fi/holidays.php b/lang/fi/holidays.php new file mode 100644 index 0000000..b6285f2 --- /dev/null +++ b/lang/fi/holidays.php @@ -0,0 +1,68 @@ + 'Arkipyhät', + 'intro' => 'Suomen arkipyhät lasketaan automaattisesti joka vuodelle. Tehtäväkalenteri näyttää ne viikonlopun tapaan, mutta niillekin voi aikatauluttaa tehtäviä. Pyhän voi poistaa käytöstä, ja yrityksen omia vapaapäiviä voi lisätä.', + 'year_heading' => 'Vuosi :year', + 'previous_year' => 'Edellinen vuosi', + 'next_year' => 'Seuraava vuosi', + 'showing_year' => 'Näytetään vuoden :year arkipyhät.', + 'columns' => [ + 'date' => 'Päivä', + 'name' => 'Nimi', + 'kind' => 'Laji', + 'state' => 'Tila', + 'actions' => 'Toiminnot', + ], + 'kinds' => [ + 'public' => 'Arkipyhä', + 'company' => 'Yrityksen vapaapäivä', + ], + 'in_use' => 'Käytössä', + 'not_in_use' => 'Ei käytössä', + 'disable' => 'Poista käytöstä', + 'enable' => 'Ota käyttöön', + 'remove' => 'Poista', + 'disable_named' => 'Poista käytöstä: :name, :day', + 'enable_named' => 'Ota käyttöön: :name, :day', + 'remove_named' => 'Poista: :name, :day', + 'disabled' => ':name (:day) poistettu käytöstä.', + 'enabled' => ':name (:day) otettu käyttöön.', + 'removed' => ':name (:day) poistettu.', + 'added' => ':name (:day) lisätty.', + 'not_changed' => 'Päivää ei voitu muuttaa. Lataa sivu uudelleen.', + 'add_heading' => 'Lisää yrityksen vapaapäivä', + 'add' => 'Lisää', + 'fields' => [ + 'date' => 'Päivä', + 'name' => 'Nimi', + 'name_hint' => 'Esimerkiksi "Yrityksen virkistyspäivä".', + ], + 'errors' => [ + 'date' => 'Anna päivä muodossa pp.kk.vvvv vuosilta 2000–2100.', + 'name' => 'Anna nimi (enintään 100 merkkiä).', + 'exists' => 'Päivä on jo arkipyhä tai vapaapäivä.', + ], + 'names' => [ + 'new_years_day' => 'Uudenvuodenpäivä', + 'epiphany' => 'Loppiainen', + 'good_friday' => 'Pitkäperjantai', + 'easter_monday' => '2. pääsiäispäivä', + 'may_day' => 'Vappu', + 'ascension_day' => 'Helatorstai', + 'midsummer_eve' => 'Juhannusaatto', + 'independence_day' => 'Itsenäisyyspäivä', + 'christmas_eve' => 'Jouluaatto', + 'christmas_day' => 'Joulupäivä', + 'st_stephens_day' => 'Tapaninpäivä', + ], + 'weekdays' => [ + 1 => 'ma', + 2 => 'ti', + 3 => 'ke', + 4 => 'to', + 5 => 'pe', + 6 => 'la', + 7 => 'su', + ], +]; diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index 22dc1b4..f287011 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -35,6 +35,24 @@ return [ 'has_time_entries' => 'Tehtävää :title ei poistettu, koska sille on kirjattu tunteja.', 'book_time' => 'Kirjaa tunnit', 'book_time_named' => 'Kirjaa tunnit tehtävälle :title', + 'from_template' => [ + 'title' => 'Lisää tehtävät pohjasta', + 'intro' => 'Valitse työnkulkupohja. Jokaisesta vaiheesta lisätään tehtävä tilaan Odottaa, ja tekijäksi tulet sinä. Tehtäviä voi muokata lisäyksen jälkeen.', + 'template' => 'Työnkulkupohja', + 'option' => ':name (:work_type)', + 'steps' => 'Vaiheet: :steps', + 'table_caption' => 'Pohjan :name tehtävät', + 'schedule_help' => 'Määräpäivä ja arvioitu aika ovat vapaaehtoisia. Ne voi lisätä myös myöhemmin tehtävän lomakkeella.', + 'task' => 'Tehtävä', + 'due_on_of' => 'Määräpäivä: :title', + 'hours_of' => 'Arvioitu aika (h): :title', + 'none' => 'Työn palveluyksiköille ei ole käytössä olevia työnkulkupohjia. Pohjia lisäävät pääkäyttäjä ja johto pohjatiedoissa.', + 'back' => 'Takaisin työhön', + 'submit' => 'Lisää tehtävät', + 'choose' => 'Valitse pohja.', + 'not_available' => 'Pohja ei ole enää käytettävissä tälle työlle. Valitse toinen.', + 'added' => '{1} Lisättiin 1 tehtävä pohjasta :name.|[2,*] Lisättiin :count tehtävää pohjasta :name.', + ], 'fields' => [ 'title' => 'Nimi', 'work_type' => 'Työtehtävä', @@ -44,7 +62,13 @@ return [ 'due_on' => 'Määräpäivä', 'estimated_hours' => 'Arvioitu aika (h)', 'description' => 'Kuvaus', + 'planned_from' => 'Aikataulu alkaa', + 'planned_to' => 'Aikataulu päättyy', + 'planned_hint' => 'Tehtävä näkyy tekijöidensä riveillä tehtäväkalenterissa. Ilman loppua tehtävä kestää yhden päivän.', ], + 'schedule' => 'Aikataulu', + 'schedule_range' => ':from–:to', + 'extended' => 'Tekijän päivät olivat täynnä, joten aikataulu jatkuu :to asti.', 'statuses' => [ 'waiting' => 'Odottaa', 'in_progress' => 'Työn alla', @@ -104,6 +128,58 @@ return [ 'unlock_not_allowed' => 'Työtä :job ei siirretty tilaan :status: valmiin työn tunnit ja kulut on lukittu, ja lukituksen voi avata vain johto.', ], + 'calendar' => [ + 'title' => 'Tehtäväkalenteri', + 'intro' => 'Tehtävät tekijöittäin aikataulun mukaan. Siirrä tehtävää vetämällä palkkia, muuta kestoa vetämällä palkin reunasta tai avaa palkki painikkeena, jolloin aikataulun, tekijän ja tilan voi muuttaa lomakkeella.', + 'range' => ':from–:to', + 'previous' => 'Edelliset 2 viikkoa', + 'next' => 'Seuraavat 2 viikkoa', + 'today' => 'Tänään', + 'today_marker' => 'tänään', + 'showing' => 'Näytetään :from–:to.', + 'only_mine' => 'Vain oma rivi', + 'subcontractor_note' => 'Näet omat tehtäväsi töistä, joihin sinut on liitetty.', + 'people' => 'Tekijät', + 'no_assignee' => 'Ei tekijää', + 'load' => ':booked / :capacity h', + 'load_of' => ':day: varattu :booked / :capacity h', + 'over_capacity' => 'yli', + 'holiday' => 'Arkipyhä', + 'no_tasks' => 'Ei tehtäviä tällä aikavälillä.', + 'bar_label' => ':title, :job, :status, :from–:to:hours', + 'bar_hours' => ', :hours h', + 'continues' => 'jatkuu', + 'unscheduled' => 'Aikatauluttamattomat tehtävät', + 'unscheduled_intro' => 'Avoimet tehtävät ilman aikataulua. Vedä tehtävä kalenteriin tai valitse Aikatauluta.', + 'unscheduled_none' => 'Kaikki avoimet tehtävät on aikataulutettu.', + 'schedule' => 'Aikatauluta', + 'schedule_named' => 'Aikatauluta tehtävä :title', + 'dialog_title' => 'Tehtävän aikataulu', + 'dialog_task' => ':title (:job)', + 'fields' => [ + 'from' => 'Alkaa', + 'to' => 'Päättyy', + 'to_hint' => 'Tyhjänä tehtävä saa niin monta arkipäivää kuin arvio vaatii.', + 'assignee' => 'Tekijä', + 'assignee_hint' => 'Korvaa tämän rivin tekijän. Muut tekijät säilyvät.', + 'status' => 'Tila', + ], + 'save' => 'Tallenna', + 'clear' => 'Poista aikataulu', + 'open_job' => 'Avaa työ', + 'edit_task' => 'Muokkaa tehtävää', + 'moved' => 'Tehtävä :title: :person :from–:to.', + 'moved_extended' => 'Tehtävä :title: :person :from–:to. Päivät olivat täynnä, joten tehtävä jatkuu :to asti.', + 'status_changed' => 'Tehtävän :title tila on nyt :status.', + 'cleared' => 'Tehtävän :title aikataulu poistettu.', + 'not_changed' => 'Tehtävää ei muutettu. Päivitä sivu ja yritä uudelleen.', + 'inactive_person' => 'Tehtävää ei siirretty: valittu henkilö ei ole enää käytössä.', + 'errors' => [ + 'from' => 'Anna alkupäivä.', + 'to' => 'Loppu ei voi olla ennen alkua.', + ], + ], + 'quick' => [ 'title' => 'Pikavastaanotto', 'intro' => 'Kirjaa uusi työ nopeasti. Muut tiedot voi täydentää myöhemmin työn sivulla.', diff --git a/lang/fi/layout.php b/lang/fi/layout.php index b907f74..abf1eb5 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -7,6 +7,7 @@ return [ 'jobs' => 'Asiakastyöt', 'quick_intake' => 'Pikavastaanotto', 'board' => 'Kanban', + 'calendar' => 'Kalenteri', 'time' => 'Tuntikirjaus', 'approvals' => 'Hyväksyntä', 'expenses' => 'Kulut', @@ -15,6 +16,7 @@ return [ 'customers' => 'Asiakkaat', 'users' => 'Käyttäjät', 'company' => 'Yritystiedot', + 'holidays' => 'Arkipyhät', 'catalog' => 'Pohjatiedot', 'prices' => 'Hinnasto', 'signed_in_as' => 'Kirjautuneena: :name', diff --git a/resources/js/app.js b/resources/js/app.js index 8337712..dc1bcaf 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -1 +1 @@ -// +import './task-calendar'; diff --git a/resources/js/task-calendar.js b/resources/js/task-calendar.js new file mode 100644 index 0000000..eb8adb0 --- /dev/null +++ b/resources/js/task-calendar.js @@ -0,0 +1,149 @@ +/** + * Drag and drop for the task calendar (jobs::calendar). + * + * A bar is dragged by its body (move in time or to another person's row) + * or by its edges (change the start or the end). Unscheduled tasks are + * dropped on a day to place them. The day and the person come from the + * grid cell under the pointer (data-calendar-day / data-calendar-user). + * Dragging is only a shortcut: every bar is a button whose dialog makes + * the same changes with the keyboard. Escape cancels a drag. + */ +const DRAG_THRESHOLD_PX = 5; +const DAY_MS = 24 * 60 * 60 * 1000; + +function toDate(value) { + const [year, month, day] = value.split('-').map(Number); + + return Date.UTC(year, month - 1, day); +} + +function shift(value, days) { + return new Date(toDate(value) + days * DAY_MS).toISOString().slice(0, 10); +} + +function daysBetween(from, to) { + return Math.round((toDate(to) - toDate(from)) / DAY_MS); +} + +function userOf(value) { + return value === '' || value === undefined || value === null ? null : Number(value); +} + +export function taskCalendar(canManage) { + return { + drag: null, + target: null, + dragged: false, + + begin(event, mode, bar) { + if (!canManage || event.button !== 0 || event.pointerType === 'touch') { + return; + } + + const cell = this.cellAt(event); + + this.drag = { + mode, + bar, + x: event.clientX, + y: event.clientY, + originDay: cell?.day ?? bar.from, + moved: false, + }; + this.target = null; + this.dragged = false; + }, + + track(event) { + if (!this.drag) { + return; + } + + if (!this.drag.moved && Math.hypot(event.clientX - this.drag.x, event.clientY - this.drag.y) < DRAG_THRESHOLD_PX) { + return; + } + + this.drag.moved = true; + this.target = this.cellAt(event); + }, + + drop(event) { + const drag = this.drag; + this.drag = null; + + if (!drag || !drag.moved) { + this.target = null; + + return; + } + + const cell = this.cellAt(event) ?? this.target; + this.target = null; + this.dragged = true; + + if (!cell) { + return; + } + + const bar = drag.bar; + let from = bar.from; + let to = bar.to; + let toUser = bar.user; + + if (drag.mode === 'move') { + const delta = daysBetween(drag.originDay, cell.day); + from = shift(bar.from, delta); + to = shift(bar.to, delta); + toUser = cell.user; + } else if (drag.mode === 'start') { + from = cell.day > bar.to ? bar.to : cell.day; + } else if (drag.mode === 'end') { + to = cell.day < bar.from ? bar.from : cell.day; + } else if (drag.mode === 'place') { + from = cell.day; + to = null; + toUser = cell.user; + } + + if (drag.mode !== 'place' && from === bar.from && to === bar.to && toUser === bar.user) { + return; + } + + this.$wire.reschedule(bar.task, bar.job, bar.user, toUser, from, to); + }, + + cancel() { + if (this.drag) { + this.drag = null; + this.target = null; + this.dragged = true; + } + }, + + /** + * A click right after a drag is the end of the drag, not a request to open the dialog. + */ + consumeDrag() { + const dragged = this.dragged; + this.dragged = false; + + return dragged; + }, + + isTarget(day, user) { + return this.target !== null && this.target.day === day && this.target.user === userOf(user); + }, + + cellAt(event) { + const element = document + .elementsFromPoint(event.clientX, event.clientY) + .find((candidate) => candidate.dataset && candidate.dataset.calendarDay !== undefined); + + return element ? { day: element.dataset.calendarDay, user: userOf(element.dataset.calendarUser) } : null; + }, + }; +} + +document.addEventListener('alpine:init', () => { + window.Alpine.data('taskCalendar', taskCalendar); +}); diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index e9f536c..d6a2401 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -59,6 +59,8 @@ @include('partials.nav-item', ['route' => 'jobs.board', 'pattern' => 'jobs.board', 'label' => __('layout.board')]) + @include('partials.nav-item', ['route' => 'jobs.calendar', 'pattern' => 'jobs.calendar', 'label' => __('layout.calendar')]) + @include('partials.nav-item', ['route' => 'time.week', 'pattern' => ['time.week', 'time.task'], 'label' => __('layout.time')]) @include('partials.nav-item', ['route' => 'expenses.mine', 'pattern' => 'expenses.*', 'label' => __('layout.expenses')]) @@ -96,7 +98,9 @@ @endcan @can('settings.manage') - @include('partials.nav-item', ['route' => 'settings.company', 'pattern' => 'settings.*', 'label' => __('layout.company')]) + @include('partials.nav-item', ['route' => 'settings.company', 'pattern' => 'settings.company', 'label' => __('layout.company')]) + + @include('partials.nav-item', ['route' => 'settings.holidays', 'pattern' => 'settings.holidays', 'label' => __('layout.holidays')]) @endcan diff --git a/tests/Browser/CatalogAccessibilityTest.php b/tests/Browser/CatalogAccessibilityTest.php index 0921009..51aee49 100644 --- a/tests/Browser/CatalogAccessibilityTest.php +++ b/tests/Browser/CatalogAccessibilityTest.php @@ -1,6 +1,9 @@ update(['hourly_rate_cents' => 9500]); $product = ProductModel::factory()->consumer()->create(['name' => 'Passikuvat', 'auto_hours' => 0.25, 'work_type_id' => WorkTypeModel::query()->where('name', 'passikuvat')->sole()->id]); ProductModel::factory()->inactive()->create(['name' => 'Vanha tuloste']); + $templateId = app(AddWorkflowTemplate::class)->execute(new WorkflowTemplateData('Lyhyt video', $workType->id, [ + new WorkflowStepData('Suunnittelu', null, WorkTypeModel::query()->where('name', 'suunnittelu')->sole()->id), + new WorkflowStepData('Kuvaus', 'Kuvauspäivä asiakkaalla'), + ])); $url = match ($page) { 'catalog' => route('catalog.index'), @@ -31,6 +38,9 @@ it('has no accessibility issues on the catalog pages', function (string $page, s 'edit product' => route('catalog.products.edit', $product->id), 'edit VAT rate' => route('catalog.vat-rates.edit', VatRateModel::query()->where('is_default', true)->value('id')), 'read-only price list' => route('catalog.price-list'), + 'workflow templates' => route('catalog.workflow-templates'), + 'new workflow template' => route('catalog.workflow-templates.create'), + 'edit workflow template' => route('catalog.workflow-templates.edit', $templateId), }; $visit = visit($url); @@ -39,7 +49,7 @@ it('has no accessibility issues on the catalog pages', function (string $page, s $visit->assertNoJavaScriptErrors() ->assertNoAccessibilityIssues(level: 2); -})->with(['catalog', 'new service unit', 'new service', 'edit work type', 'price list', 'new product', 'edit product', 'edit VAT rate', 'read-only price list'])->with([ +})->with(['catalog', 'new service unit', 'new service', 'edit work type', 'price list', 'new product', 'edit product', 'edit VAT rate', 'read-only price list', 'workflow templates', 'new workflow template', 'edit workflow template'])->with([ 'desktop, light' => ['desktop', 'light'], 'desktop, dark' => ['desktop', 'dark'], 'mobile, light' => ['mobile', 'light'], @@ -96,3 +106,17 @@ it('has no accessibility issues on the price list of an employee without the pri 'mobile, light' => ['mobile', 'light'], 'mobile, dark' => ['mobile', 'dark'], ]); + +it('adds and moves workflow steps with the keyboard, keeping focus and announcing it', function () { + visit(route('catalog.workflow-templates.create')) + ->type('#step-1-title', 'Kuvaus') + ->keys('#add-step', 'Enter') + ->assertSee('Vaihe 2 lisätty.') + ->assertScript('document.activeElement.id', 'step-2-title') + ->type('#step-2-title', 'Suunnittelu') + ->keys('#step-2-up', 'Enter') + ->assertSee('Vaihe 2 siirretty kohtaan 1.') + ->assertScript('document.activeElement.id', 'step-2-up') + ->assertScript('document.querySelector("ol input").value', 'Suunnittelu') + ->assertNoAccessibilityIssues(level: 2); +}); diff --git a/tests/Browser/CustomersAccessibilityTest.php b/tests/Browser/CustomersAccessibilityTest.php index 369ed54..e7e297e 100644 --- a/tests/Browser/CustomersAccessibilityTest.php +++ b/tests/Browser/CustomersAccessibilityTest.php @@ -137,6 +137,30 @@ it('removes a contact with the keyboard, in a dialog that keeps and returns focu ->assertSee('Pekka'); })->with(['light', 'dark']); +it('removes a customer with nothing linked to it with the keyboard, and offers no removal for one with a contact', function (string $colorScheme) { + $empty = CustomerModel::factory()->create(['name' => 'Turha Oy']); + $linked = CustomerModel::factory()->create(['name' => 'Mainos Oy']); + CustomerContactModel::factory()->create(['customer_id' => $linked->id, 'name' => 'Maija']); + + $removeCustomer = '[wire\:click^="confirmRemoval(\'customer\'"]'; + + visit(route('customers.show', $linked->id)) + ->assertSee('Maija') + ->assertDontSee('Poista asiakas'); + + $page = visit(route('customers.show', $empty->id)); + $page = $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode(); + + // Removed: the dialog takes focus, then the list shows a status message. + $page->keys($removeCustomer, 'Enter') + ->assertSee('Poistetaanko asiakas Turha Oy?') + ->assertScript('document.getElementById("remove-dialog").contains(document.activeElement)', true) + ->assertNoAccessibilityIssues(level: 2) + ->click('#remove-dialog [wire\:click="remove"]') + ->assertSee('Asiakas Turha Oy poistettu.') + ->assertNoAccessibilityIssues(level: 2); +})->with(['light', 'dark']); + it('has no accessibility issues with a consumer\'s personal identity code', function (string $page, string $device, string $colorScheme) { $this->actingAs(User::factory()->management()->create()); $consumer = CustomerModel::factory()->consumer()->create([ diff --git a/tests/Browser/JobsAccessibilityTest.php b/tests/Browser/JobsAccessibilityTest.php index 188fc13..4114b13 100644 --- a/tests/Browser/JobsAccessibilityTest.php +++ b/tests/Browser/JobsAccessibilityTest.php @@ -1,6 +1,9 @@ assertScript('document.activeElement.id', 'checklist-new-'.$task->id) ->assertNoAccessibilityIssues(level: 2); }); + +it('adds tasks from a workflow template with the keyboard, without accessibility issues', function (string $device, string $colorScheme) { + $this->job->update(['status' => 'order']); + $workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole(); + $templateId = app(AddWorkflowTemplate::class)->execute(new WorkflowTemplateData('Lyhyt video', $workType->id, [ + new WorkflowStepData('Suunnittelu', null, WorkTypeModel::query()->where('name', 'suunnittelu')->sole()->id), + new WorkflowStepData('Kuvaus'), + ])); + + $visit = visit(route('jobs.tasks.from-template', $this->job->id)); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2) + ->keys('[value="'.$templateId.'"]', 'Space') + ->assertSee('Pohjan Lyhyt video tehtävät') + ->assertNoAccessibilityIssues(level: 2) + ->type('#row-1-hours', '2,5') + ->keys('main form button[type="submit"]', 'Enter') + ->assertSee('Lisättiin 2 tehtävää pohjasta Lyhyt video (videokuvaus).') + ->assertSee('Suunnittelu') + ->assertNoAccessibilityIssues(level: 2); + + expect(TaskModel::query()->where('customer_job_id', $this->job->id)->orderBy('id')->pluck('estimated_hours')->map(fn ($hours) => $hours === null ? null : (float) $hours)->all())->toBe([null, 2.5]); +})->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); diff --git a/tests/Browser/TaskCalendarAccessibilityTest.php b/tests/Browser/TaskCalendarAccessibilityTest.php new file mode 100644 index 0000000..f062af7 --- /dev/null +++ b/tests/Browser/TaskCalendarAccessibilityTest.php @@ -0,0 +1,87 @@ +user = User::factory()->management()->create(['name' => 'Johanna Johto']); + $this->other = User::factory()->create(['name' => 'Aino Ahkera']); + $this->actingAs($this->user); + $job = CustomerJobModel::factory()->create(['name' => 'Messuvideo', 'status' => 'order', 'responsible_user_id' => $this->user->id]); + $workType = WorkTypeModel::query()->where('name', 'graafinen työ')->sole(); + + $this->task = TaskModel::factory()->assignedTo([$this->user->id])->create([ + 'customer_job_id' => $job->id, + 'work_type_id' => $workType->id, + 'title' => 'Leikkaus', + 'estimated_hours' => 4, + 'due_on' => now()->addDay()->toDateString(), + 'planned_from' => now()->toDateString(), + 'planned_to' => now()->addDays(2)->toDateString(), + ]); + TaskModel::factory()->assignedTo([$this->other->id])->create(['customer_job_id' => $job->id, 'work_type_id' => $workType->id, 'title' => 'Värimäärittely']); +}); + +it('has no accessibility issues on the task calendar', function (string $device, string $colorScheme) { + $visit = visit(route('jobs.calendar')); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertNoJavaScriptErrors() + ->assertSee('Leikkaus') + ->assertSee('Värimäärittely') + ->assertNoAccessibilityIssues(level: 2); +})->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); + +it('reschedules a task with the keyboard and returns focus to its bar', function () { + $key = $this->task->id.'-'.$this->user->id; + + visit(route('jobs.calendar')) + ->on()->desktop() + ->keys('#bar-'.$key, 'Enter') + ->assertSee('Tehtävän aikataulu') + ->assertNoAccessibilityIssues(level: 2) + ->type('#task-schedule-dialog [wire\:model="plannedFrom"]', now()->addDay()->format('Y-m-d')) + ->type('#task-schedule-dialog [wire\:model="plannedTo"]', now()->addDays(3)->format('Y-m-d')) + ->press('#task-schedule-dialog [wire\:click="saveDialog"]') + ->assertSee('Tehtävä Leikkaus: Johanna Johto '.now()->addDay()->format('j.n.Y').'–'.now()->addDays(3)->format('j.n.Y').'.') + ->assertScript('document.activeElement.id', 'bar-'.$key); + + expect($this->task->refresh()->planned_from?->format('Y-m-d'))->toBe(now()->addDay()->toDateString()); +}); + +it('moves a task to another person by dragging its bar', function () { + // The bar (today – today + 2) is grabbed at its middle day, so dropping it + // on today + 4 moves it three days later. + $day = now()->addDays(4)->toDateString(); + + visit(route('jobs.calendar')) + ->on()->desktop() + ->drag('#bar-'.$this->task->id.'-'.$this->user->id, '[data-calendar-day="'.$day.'"][data-calendar-user="'.$this->other->id.'"]') + ->assertSee('Tehtävä Leikkaus: Aino Ahkera'); + + expect($this->task->refresh()->planned_from?->format('Y-m-d'))->toBe(now()->addDays(3)->toDateString()) + ->and(DB::table('task_assignees')->where('task_id', $this->task->id)->pluck('user_id')->all())->toBe([$this->other->id]); +}); + +it('has no accessibility issues on the holidays page', function (string $colorScheme) { + $this->actingAs(User::factory()->admin()->create()); + + $visit = visit(route('settings.holidays')); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertNoJavaScriptErrors() + ->assertSee('Itsenäisyyspäivä') + ->assertNoAccessibilityIssues(level: 2); +})->with(['light', 'dark']); diff --git a/tests/Fakes/FakeCustomerReferences.php b/tests/Fakes/FakeCustomerReferences.php new file mode 100644 index 0000000..a3abed3 --- /dev/null +++ b/tests/Fakes/FakeCustomerReferences.php @@ -0,0 +1,18 @@ + + */ + public array $referencedIds = []; + + public function refersTo(int $customerId): bool + { + return in_array($customerId, $this->referencedIds, true); + } +} diff --git a/tests/Fakes/FakeWorkflowTemplateQueries.php b/tests/Fakes/FakeWorkflowTemplateQueries.php new file mode 100644 index 0000000..aae7fb2 --- /dev/null +++ b/tests/Fakes/FakeWorkflowTemplateQueries.php @@ -0,0 +1,67 @@ + */ + public array $templates = []; + + /** + * @param list $steps Title and the step's own work type. + */ + public function addTemplate(int $id, string $name, int $workTypeId, int $serviceUnitId, array $steps, bool $active = true): void + { + $this->templates[$id] = new WorkflowTemplateDetails( + $id, + $name, + $workTypeId, + 'työtehtävä '.$workTypeId, + $serviceUnitId, + $active, + array_map(fn (array $step): WorkflowStepSummary => new WorkflowStepSummary( + $step[0], + null, + $step[1] ?? null, + $step[1] ?? $workTypeId, + 'työtehtävä '.($step[1] ?? $workTypeId), + ), $steps), + ); + } + + public function all(): array + { + return array_values(array_map(fn (WorkflowTemplateDetails $template): WorkflowTemplateSummary => new WorkflowTemplateSummary( + $template->id, + $template->name, + $template->workTypeId, + $template->workTypeName, + $template->serviceUnitId, + 'yksikkö '.$template->serviceUnitId, + $template->isActive, + count($template->steps), + ), $this->templates)); + } + + public function find(int $id): ?WorkflowTemplateDetails + { + return $this->templates[$id] ?? null; + } + + /** + * Unit 9 plays the shared unit. + */ + public function activeFor(array $serviceUnitIds): array + { + return array_values(array_filter( + $this->templates, + fn (WorkflowTemplateDetails $template): bool => $template->isActive + && (in_array($template->serviceUnitId, $serviceUnitIds, true) || $template->serviceUnitId === 9), + )); + } +} diff --git a/tests/Fakes/InMemoryBillingUnitRepository.php b/tests/Fakes/InMemoryBillingUnitRepository.php index 56ac077..dd279c4 100644 --- a/tests/Fakes/InMemoryBillingUnitRepository.php +++ b/tests/Fakes/InMemoryBillingUnitRepository.php @@ -43,4 +43,15 @@ class InMemoryBillingUnitRepository implements BillingUnitRepository { unset($this->billingUnits[$billingUnit->id()]); } + + public function existsForCustomer(int $customerId): bool + { + foreach ($this->billingUnits as $billingUnit) { + if ($billingUnit->customerId() === $customerId) { + return true; + } + } + + return false; + } } diff --git a/tests/Fakes/InMemoryCustomerContactRepository.php b/tests/Fakes/InMemoryCustomerContactRepository.php index f8b351e..6f04d53 100644 --- a/tests/Fakes/InMemoryCustomerContactRepository.php +++ b/tests/Fakes/InMemoryCustomerContactRepository.php @@ -43,4 +43,15 @@ class InMemoryCustomerContactRepository implements CustomerContactRepository { unset($this->contacts[$contact->id()]); } + + public function existsForCustomer(int $customerId): bool + { + foreach ($this->contacts as $contact) { + if ($contact->customerId() === $customerId) { + return true; + } + } + + return false; + } } diff --git a/tests/Fakes/InMemoryCustomerRepository.php b/tests/Fakes/InMemoryCustomerRepository.php index 888a299..12b36e7 100644 --- a/tests/Fakes/InMemoryCustomerRepository.php +++ b/tests/Fakes/InMemoryCustomerRepository.php @@ -31,6 +31,11 @@ class InMemoryCustomerRepository implements CustomerRepository return clone $stored; } + public function delete(Customer $customer): void + { + unset($this->customers[$customer->id()]); + } + public function isPersonalIdentityCodeTaken(PersonalIdentityCode $code, ?int $exceptCustomerId = null): bool { foreach ($this->customers as $id => $customer) { diff --git a/tests/Fakes/InMemoryHolidayOverrides.php b/tests/Fakes/InMemoryHolidayOverrides.php new file mode 100644 index 0000000..1cdc5c5 --- /dev/null +++ b/tests/Fakes/InMemoryHolidayOverrides.php @@ -0,0 +1,34 @@ + */ + public array $overrides = []; + + public function between(string $from, string $to): array + { + ksort($this->overrides); + + return array_values(array_filter($this->overrides, fn (HolidayOverride $override): bool => $override->date >= $from && $override->date <= $to)); + } + + public function find(string $date): ?HolidayOverride + { + return $this->overrides[$date] ?? null; + } + + public function save(HolidayOverride $override): void + { + $this->overrides[$override->date] = $override; + } + + public function delete(string $date): void + { + unset($this->overrides[$date]); + } +} diff --git a/tests/Fakes/InMemoryTaskBookingRepository.php b/tests/Fakes/InMemoryTaskBookingRepository.php new file mode 100644 index 0000000..2074e55 --- /dev/null +++ b/tests/Fakes/InMemoryTaskBookingRepository.php @@ -0,0 +1,60 @@ +>> task id => user id => day => minutes */ + public array $bookings = []; + + public function __construct(private InMemoryTaskRepository $tasks) {} + + public function replaceFor(int $taskId, int $userId, array $minutesByDay): void + { + $this->bookings[$taskId][$userId] = array_filter($minutesByDay, fn (int $minutes): bool => $minutes > 0); + } + + public function deleteForTask(int $taskId, array $keepUserIds = []): void + { + foreach (array_keys($this->bookings[$taskId] ?? []) as $userId) { + if (! in_array($userId, $keepUserIds, true)) { + unset($this->bookings[$taskId][$userId]); + } + } + } + + public function otherOpenMinutes(int $userId, string $from, string $to, int $exceptTaskId): array + { + $minutes = []; + + foreach ($this->bookings as $taskId => $users) { + if ($taskId === $exceptTaskId || ($this->tasks->tasks[$taskId] ?? null)?->status() === TaskStatus::Done) { + continue; + } + + foreach ($users[$userId] ?? [] as $day => $booked) { + if ($day >= $from && $day <= $to) { + $minutes[$day] = ($minutes[$day] ?? 0) + $booked; + } + } + } + + ksort($minutes); + + return $minutes; + } + + /** + * @return array + */ + public function of(int $taskId, int $userId): array + { + $days = $this->bookings[$taskId][$userId] ?? []; + ksort($days); + + return $days; + } +} diff --git a/tests/Fakes/InMemoryTaskRepository.php b/tests/Fakes/InMemoryTaskRepository.php index 4fbacf8..110b160 100644 --- a/tests/Fakes/InMemoryTaskRepository.php +++ b/tests/Fakes/InMemoryTaskRepository.php @@ -44,6 +44,8 @@ class InMemoryTaskRepository implements TaskRepository $task->estimatedHours(), $task->assigneeUserIds(), $task->createdBy(), + $task->plannedFrom(), + $task->plannedTo(), ); return clone $this->tasks[$id]; diff --git a/tests/Fakes/InMemoryWorkflowTemplateRepository.php b/tests/Fakes/InMemoryWorkflowTemplateRepository.php new file mode 100644 index 0000000..548fddd --- /dev/null +++ b/tests/Fakes/InMemoryWorkflowTemplateRepository.php @@ -0,0 +1,38 @@ + */ + public array $items = []; + + private int $nextId = 1; + + public function findById(int $id): ?WorkflowTemplate + { + return isset($this->items[$id]) ? clone $this->items[$id] : null; + } + + public function save(WorkflowTemplate $template): WorkflowTemplate + { + $id = $template->id() ?? $this->nextId++; + $this->items[$id] = WorkflowTemplate::reconstitute($id, $template->workTypeId(), $template->name(), $template->isActive(), $template->steps()); + + return clone $this->items[$id]; + } + + public function isNameTaken(int $workTypeId, string $name, ?int $exceptId = null): bool + { + foreach ($this->items as $id => $template) { + if ($id !== $exceptId && $template->workTypeId() === $workTypeId && mb_strtolower($template->name()->value) === mb_strtolower($name)) { + return true; + } + } + + return false; + } +} diff --git a/tests/Feature/Modules/Catalog/WorkflowTemplatesTest.php b/tests/Feature/Modules/Catalog/WorkflowTemplatesTest.php new file mode 100644 index 0000000..d6fad47 --- /dev/null +++ b/tests/Feature/Modules/Catalog/WorkflowTemplatesTest.php @@ -0,0 +1,160 @@ +actingAs(User::factory()->management()->create()); + $this->workType = fn (string $name, string $unit = 'Mediatuotanto', ?string $service = 'Videotuotanto') => WorkTypeModel::query() + ->where('name', $name) + ->where('service_unit_id', ServiceUnitModel::query()->where('name', $unit)->sole()->id) + ->where('service_id', $service === null ? null : ServiceModel::query()->where('name', $service)->sole()->id) + ->sole(); + $this->videography = ($this->workType)('videokuvaus'); + $this->editing = ($this->workType)('editointi'); + $this->planning = ($this->workType)('suunnittelu', 'Kaikille yhteiset', null); + + $this->addTemplate = fn (string $name, int $workTypeId, array $steps): int => app(AddWorkflowTemplate::class)->execute(new WorkflowTemplateData( + $name, + $workTypeId, + array_map(fn (array $step): WorkflowStepData => new WorkflowStepData(...$step), $steps), + )); +}); + +it('shows the template pages to admins and management only', function (string $role, int $status) { + $this->actingAs(User::factory()->{$role}()->create()); + + $this->get(route('catalog.workflow-templates'))->assertStatus($status); + $this->get(route('catalog.workflow-templates.create'))->assertStatus($status); +})->with([ + 'admin' => ['admin', 200], + 'management' => ['management', 200], + 'employee' => ['employee', 403], + 'subcontractor' => ['subcontractor', 403], +]); + +it('links the templates from the catalog page', function () { + $this->get(route('catalog.index'))->assertSee(route('catalog.workflow-templates')); +}); + +it('adds a template with steps added, moved and removed on the form', function () { + Livewire::test('catalog::workflow-template-form') + ->set('form.name', 'Lyhyt video') + ->set('form.work_type_id', (string) $this->videography->id) + ->assertSee('editointi') + ->assertSee('suunnittelu') + ->set('form.steps.0.title', 'Kuvaus') + ->call('addStep') + ->assertSee('Vaihe 2 lisätty.') + ->set('form.steps.1.title', 'Suunnittelu') + ->set('form.steps.1.work_type_id', (string) $this->planning->id) + ->call('moveStep', 1, 'up') + ->assertSee('Vaihe 2 siirretty kohtaan 1.') + ->call('addStep') + ->set('form.steps.2.title', 'Turha') + ->call('removeStep', 2) + ->assertSee('Vaihe 3 poistettu.') + ->call('addStep') + ->set('form.steps.2.title', 'Editointi') + ->set('form.steps.2.work_type_id', (string) $this->editing->id) + ->set('form.steps.2.description', 'Leikkaus ja värimäärittely') + ->call('save') + ->assertHasNoErrors() + ->assertRedirect(route('catalog.workflow-templates')); + + $template = app(WorkflowTemplateQueries::class)->all()[0]; + $details = app(WorkflowTemplateQueries::class)->find($template->id); + + expect($template->name)->toBe('Lyhyt video') + ->and($template->workTypeName)->toBe('videokuvaus') + ->and($template->serviceUnitName)->toBe('Mediatuotanto') + ->and($template->stepCount)->toBe(3) + ->and(array_map(fn ($step) => [$step->title, $step->workTypeId, $step->effectiveWorkTypeId, $step->workTypeName, $step->description], $details->steps))->toBe([ + ['Suunnittelu', $this->planning->id, $this->planning->id, 'suunnittelu', null], + ['Kuvaus', null, $this->videography->id, 'videokuvaus', null], + ['Editointi', $this->editing->id, $this->editing->id, 'editointi', 'Leikkaus ja värimäärittely'], + ]); + + $this->get(route('catalog.workflow-templates'))->assertSee('Lyhyt video')->assertSee('videokuvaus'); +}); + +it('shows Finnish errors on the right fields', function () { + ($this->addTemplate)('Lyhyt video', $this->videography->id, [['Kuvaus']]); + + Livewire::test('catalog::workflow-template-form') + ->call('save') + ->assertHasErrors(['form.name', 'form.work_type_id', 'form.steps.0.title']) + ->assertSee('Anna nimi.') + ->assertSee('Valitse työtehtävä.') + ->assertSee('Anna tehtävän nimi.'); + + Livewire::test('catalog::workflow-template-form') + ->set('form.name', 'lyhyt video') + ->set('form.work_type_id', (string) $this->videography->id) + ->set('form.steps.0.title', 'Kuvaus') + ->call('save') + ->assertHasErrors(['form.name']) + ->assertSee('Työtehtävällä on jo tämänniminen pohja.'); + + Livewire::test('catalog::workflow-template-form') + ->set('form.name', 'Video ja grafiikka') + ->set('form.work_type_id', (string) $this->videography->id) + ->set('form.steps.0.title', 'Grafiikka') + ->set('form.steps.0.work_type_id', (string) ($this->workType)('graafinen työ', 'Markkinointi', null)->id) + ->call('save') + ->assertHasErrors(['form.steps.0.work_type_id']) + ->assertSee('Valitse käytössä oleva työtehtävä pohjan palveluyksiköstä tai kaikille yhteisistä.'); +}); + +it('edits a template and keeps tasks offered only while it is in use', function () { + $id = ($this->addTemplate)('Lyhyt video', $this->videography->id, [['Kuvaus'], ['Editointi', null, $this->editing->id]]); + + Livewire::test('catalog::workflow-template-form', ['template' => $id]) + ->assertSet('form.name', 'Lyhyt video') + ->assertSet('form.steps.1.work_type_id', (string) $this->editing->id) + ->call('removeStep', 0) + ->set('form.name', 'Pelkkä editointi') + ->call('save') + ->assertHasNoErrors(); + + expect(array_map(fn ($step) => $step->title, app(WorkflowTemplateQueries::class)->find($id)->steps))->toBe(['Editointi']); + + $media = ServiceUnitModel::query()->where('name', 'Mediatuotanto')->sole()->id; + $marketing = ServiceUnitModel::query()->where('name', 'Markkinointi')->sole()->id; + + expect(array_map(fn ($template) => $template->name, app(WorkflowTemplateQueries::class)->activeFor([$media])))->toBe(['Pelkkä editointi']) + ->and(app(WorkflowTemplateQueries::class)->activeFor([$marketing]))->toBe([]); + + Livewire::test('catalog::workflow-templates') + ->call('toggleActive', $id) + ->assertSee('Pelkkä editointi poistettu käytöstä.'); + + expect(app(WorkflowTemplateQueries::class)->activeFor([$media]))->toBe([]); +}); + +it('offers shared work type templates to every job', function () { + ($this->addTemplate)('Työpaja', $this->planning->id, [['Valmistelu'], ['Työpaja']]); + + $marketing = ServiceUnitModel::query()->where('name', 'Markkinointi')->sole()->id; + + expect(array_map(fn ($template) => $template->name, app(WorkflowTemplateQueries::class)->activeFor([$marketing])))->toBe(['Työpaja']); +}); + +it('returns 404 for an unknown template', function () { + $this->get(route('catalog.workflow-templates.edit', 999))->assertNotFound(); +}); + +it('locks the template id', function () { + Livewire::test('catalog::workflow-template-form')->set('templateId', 1); +})->throws(CannotUpdateLockedPropertyException::class); diff --git a/tests/Feature/Modules/Customers/ContactsAndBillingUnitsTest.php b/tests/Feature/Modules/Customers/ContactsAndBillingUnitsTest.php index 6645fdf..f5ec48d 100644 --- a/tests/Feature/Modules/Customers/ContactsAndBillingUnitsTest.php +++ b/tests/Feature/Modules/Customers/ContactsAndBillingUnitsTest.php @@ -5,6 +5,8 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\BillingUnitModel; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerContactModel; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel; +use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel; +use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel; use Illuminate\Foundation\Testing\RefreshDatabase; use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException; use Livewire\Livewire; @@ -184,3 +186,73 @@ it('deletes the contacts and billing units of a deleted customer', function () { expect(CustomerContactModel::query()->count())->toBe(0) ->and(BillingUnitModel::query()->count())->toBe(0); }); + +it('removes a customer that has nothing linked to it and returns to the list', function () { + Livewire::test('customers::show', ['customer' => $this->customer->id]) + ->call('confirmRemoval', 'customer', $this->customer->id) + ->assertSee('Poistetaanko asiakas Mainos Oy?') + ->call('remove') + ->assertRedirect(route('customers.index')); + + expect($this->customer->fresh())->toBeNull() + ->and(session('status'))->toBe('Asiakas Mainos Oy poistettu.'); +}); + +it('keeps a customer that has a contact or a customer job and tells why', function (string $link) { + match ($link) { + 'contact' => CustomerContactModel::factory()->create(['customer_id' => $this->customer->id]), + 'customer job' => CustomerJobModel::factory()->create(['customer_id' => $this->customer->id]), + }; + + Livewire::test('customers::show', ['customer' => $this->customer->id]) + ->call('confirmRemoval', 'customer', $this->customer->id) + ->call('remove') + ->assertNoRedirect() + ->assertSee('Asiakasta Mainos Oy ei poistettu'); + + expect($this->customer->fresh())->not->toBeNull(); +})->with(['contact', 'customer job']); + +it('has no remove button for the internal customer and does not remove it', function () { + $internal = CustomerModel::query()->where('is_internal', true)->sole(); + + Livewire::test('customers::show', ['customer' => $internal->id]) + ->assertDontSee('Poista asiakas') + ->call('confirmRemoval', 'customer', $internal->id) + ->call('remove') + ->assertSee('Sisäistä asiakasta ei voi poistaa.'); + + expect($internal->fresh())->not->toBeNull(); +}); + +it('does not remove another customer than the one on the page', function () { + $other = CustomerModel::factory()->create(); + + Livewire::test('customers::show', ['customer' => $this->customer->id]) + ->call('confirmRemoval', 'customer', $other->id) + ->assertSet('removalId', null) + ->call('remove'); + + expect($other->fresh())->not->toBeNull() + ->and($this->customer->fresh())->not->toBeNull(); +}); + +it('shows the remove customer button only when nothing is linked to the customer', function (?string $link) { + match ($link) { + null => null, + 'contact' => CustomerContactModel::factory()->create(['customer_id' => $this->customer->id]), + 'billing unit' => BillingUnitModel::factory()->create(['customer_id' => $this->customer->id]), + 'customer job' => CustomerJobModel::factory()->create(['customer_id' => $this->customer->id]), + 'quick sale' => QuickSaleModel::factory()->create(['customer_id' => $this->customer->id]), + }; + + $page = Livewire::test('customers::show', ['customer' => $this->customer->id]); + + $link === null ? $page->assertSee('Poista asiakas') : $page->assertDontSee('Poista asiakas'); +})->with([ + 'nothing' => [null], + 'contact' => ['contact'], + 'billing unit' => ['billing unit'], + 'customer job' => ['customer job'], + 'quick sale' => ['quick sale'], +]); diff --git a/tests/Feature/Modules/Customers/EloquentCustomerRepositoryTest.php b/tests/Feature/Modules/Customers/EloquentCustomerRepositoryTest.php index 28e4403..85a991c 100644 --- a/tests/Feature/Modules/Customers/EloquentCustomerRepositoryTest.php +++ b/tests/Feature/Modules/Customers/EloquentCustomerRepositoryTest.php @@ -1,13 +1,19 @@ and($queries->paginate(null)->total())->toBe(4) // and the internal customer ->and($queries->search('100%'))->toBe([]); }); + +it('deletes a customer that nothing refers to', function () { + $repository = app(CustomerRepository::class); + $customer = $repository->save(Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company)); + + $repository->delete($customer); + + expect($repository->findById((int) $customer->id()))->toBeNull(); +}); + +it('refuses to delete a customer that a customer job or a quick sale refers to', function (string $reference) { + $customer = CustomerModel::factory()->create(); + + match ($reference) { + 'customer job' => CustomerJobModel::factory()->create(['customer_id' => $customer->id]), + 'quick sale' => QuickSaleModel::factory()->create(['customer_id' => $customer->id]), + }; + + $repository = app(CustomerRepository::class); + + expect(fn () => $repository->delete($repository->findById($customer->id)))->toThrow(CustomerInUse::class) + ->and($customer->fresh())->not->toBeNull(); +})->with(['customer job', 'quick sale']); + +it('tells whether customer jobs, quick sales or invoices refer to a customer', function (string $reference) { + $customer = CustomerModel::factory()->create(); + $references = app(CustomerReferences::class); + + expect($references->refersTo($customer->id))->toBeFalse(); + + match ($reference) { + 'customer job' => CustomerJobModel::factory()->create(['customer_id' => $customer->id]), + 'quick sale' => QuickSaleModel::factory()->create(['customer_id' => $customer->id]), + 'invoice' => DB::table('billing_invoices')->insert([ + 'billing_export_id' => DB::table('billing_exports')->insertGetId(['status' => 'draft', 'created_by' => User::factory()->create()->id, 'created_at' => now(), 'updated_at' => now()]), + 'customer_id' => $customer->id, + 'created_at' => now(), + 'updated_at' => now(), + ]), + }; + + expect($references->refersTo($customer->id))->toBeTrue(); +})->with(['customer job', 'quick sale', 'invoice']); diff --git a/tests/Feature/Modules/Jobs/TaskCalendarTest.php b/tests/Feature/Modules/Jobs/TaskCalendarTest.php new file mode 100644 index 0000000..43d28da --- /dev/null +++ b/tests/Feature/Modules/Jobs/TaskCalendarTest.php @@ -0,0 +1,139 @@ +travelTo(new DateTimeImmutable('2026-12-21 09:00')); + + $this->employee = User::factory()->create(['name' => 'Eero Työntekijä']); + $this->other = User::factory()->create(['name' => 'Aino Ahkera']); + $this->actingAs($this->employee); + $marketing = ServiceUnitModel::query()->where('name', 'Markkinointi')->sole(); + $this->job = CustomerJobModel::factory()->create(['name' => 'Kampanja', 'status' => 'order', 'responsible_user_id' => $this->employee->id]); + DB::table('customer_job_service_unit')->where('customer_job_id', $this->job->id)->update(['service_unit_id' => $marketing->id]); + $this->graphic = WorkTypeModel::query()->where('name', 'graafinen työ')->sole(); +}); + +function calendarTaskModel(array $attributes, array $assignees): TaskModel +{ + return TaskModel::factory()->assignedTo($assignees)->create($attributes); +} + +it('shows the two weeks from today with holidays, rows and bars', function () { + calendarTaskModel(['customer_job_id' => test()->job->id, 'work_type_id' => test()->graphic->id, 'title' => 'Mainoskuvat', 'planned_from' => '2026-12-22', 'planned_to' => '2026-12-23'], [test()->other->id]); + calendarTaskModel(['customer_job_id' => test()->job->id, 'work_type_id' => test()->graphic->id, 'title' => 'Ilman aikataulua'], [test()->employee->id]); + + $this->get(route('jobs.calendar')) + ->assertOk() + ->assertSee('Tehtäväkalenteri') + ->assertSee('21.12.2026–3.1.2027') + ->assertSee('Jouluaatto') + ->assertSee('Uudenvuodenpäivä') + ->assertSeeInOrder(['Eero Työntekijä', 'Aino Ahkera', 'Ei tekijää']) + ->assertSee('Mainoskuvat') + ->assertSee('Aikatauluttamattomat tehtävät') + ->assertSee('Ilman aikataulua'); +}); + +it('moves a task to another person by dropping it and books their days', function () { + $task = calendarTaskModel(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Mainoskuvat', 'estimated_hours' => 12], [$this->employee->id]); + + Livewire::test('jobs::calendar') + ->call('reschedule', $task->id, $this->job->id, $this->employee->id, $this->other->id, '2026-12-28', null) + ->assertSee('Tehtävä Mainoskuvat: Aino Ahkera 28.12.2026–29.12.2026.'); + + expect($task->refresh()->planned_from?->format('Y-m-d'))->toBe('2026-12-28') + ->and($task->planned_to?->format('Y-m-d'))->toBe('2026-12-29') + ->and(DB::table('task_assignees')->where('task_id', $task->id)->pluck('user_id')->all())->toBe([$this->other->id]) + ->and(DB::table('task_bookings')->where('task_id', $task->id)->orderBy('day')->pluck('minutes', 'day')->all())->toBe(['2026-12-28' => 360, '2026-12-29' => 360]); +}); + +it('continues a task on the next working day when the day is full', function () { + calendarTaskModel(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Kuvaus', 'estimated_hours' => 6], [$this->employee->id]); + $first = TaskModel::query()->sole(); + Livewire::test('jobs::calendar')->call('reschedule', $first->id, $this->job->id, $this->employee->id, $this->employee->id, '2026-12-23', '2026-12-23'); + $task = calendarTaskModel(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Taitto', 'estimated_hours' => 4], [$this->employee->id]); + + // 24.–27.12. are holidays and a weekend, so the rest goes to Monday. + Livewire::test('jobs::calendar') + ->call('reschedule', $task->id, $this->job->id, $this->employee->id, $this->employee->id, '2026-12-23', '2026-12-23') + ->assertSee('Päivät olivat täynnä, joten tehtävä jatkuu 28.12.2026 asti.') + ->assertSee('8 / 8 h'); + + expect($task->refresh()->planned_to?->format('Y-m-d'))->toBe('2026-12-28'); +}); + +it('changes the schedule and status in the dialog and takes a task out of the calendar', function () { + $task = calendarTaskModel(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Mainoskuvat', 'planned_from' => '2026-12-22', 'planned_to' => '2026-12-22'], [$this->employee->id]); + + Livewire::test('jobs::calendar') + ->call('openDialog', $task->id, $this->employee->id) + ->assertSet('plannedFrom', '2026-12-22') + ->set('plannedFrom', '2026-12-29') + ->set('plannedTo', '2026-12-28') + ->call('saveDialog') + ->assertHasErrors('plannedTo') + ->set('plannedTo', '2026-12-30') + ->set('status', 'in_progress') + ->call('saveDialog') + ->assertHasNoErrors() + ->assertSee('Tehtävän Mainoskuvat tila on nyt Työn alla.') + ->call('openDialog', $task->id, $this->employee->id) + ->call('clearSchedule') + ->assertSee('Tehtävän Mainoskuvat aikataulu poistettu.'); + + expect($task->refresh()->status->value)->toBe('in_progress') + ->and($task->planned_from)->toBeNull(); +}); + +it('shows a subcontractor only their own row and lets them change only the status', function () { + $subcontractor = User::factory()->subcontractor()->create(['name' => 'Ville Alihankkija']); + DB::table('customer_job_members')->insert(['customer_job_id' => $this->job->id, 'user_id' => $subcontractor->id]); + $own = calendarTaskModel(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Oma tehtävä', 'planned_from' => '2026-12-22', 'planned_to' => '2026-12-22'], [$subcontractor->id]); + calendarTaskModel(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Toisen tehtävä', 'planned_from' => '2026-12-22', 'planned_to' => '2026-12-22'], [$this->employee->id]); + $this->actingAs($subcontractor); + + $this->get(route('jobs.calendar')) + ->assertOk() + ->assertSee('Oma tehtävä') + ->assertDontSee('Toisen tehtävä') + ->assertDontSee('Eero Työntekijä') + ->assertDontSee('Ei tekijää'); + + Livewire::test('jobs::calendar') + ->call('reschedule', $own->id, $this->job->id, $subcontractor->id, $subcontractor->id, '2026-12-28', null) + ->assertForbidden(); + + Livewire::test('jobs::calendar') + ->call('openDialog', $own->id, $subcontractor->id) + ->set('status', 'done') + ->call('saveDialog') + ->assertSee('Tehtävän Oma tehtävä tila on nyt Valmis.'); + + expect($own->refresh()->status->value)->toBe('done') + ->and($own->planned_from?->format('Y-m-d'))->toBe('2026-12-22'); +}); + +it('adds a schedule on the task form', function () { + Livewire::test('jobs::task-form', ['job' => $this->job->id]) + ->set('form.title', 'Mainoskuvat') + ->set('form.work_type_id', (string) $this->graphic->id) + ->set('form.estimated_hours', '4') + ->set('form.planned_from', '2026-12-28') + ->call('save') + ->assertHasNoErrors(); + + $task = TaskModel::query()->sole(); + + expect($task->planned_to?->format('Y-m-d'))->toBe('2026-12-28') + ->and(DB::table('task_bookings')->where('task_id', $task->id)->sum('minutes'))->toBe(240); +}); diff --git a/tests/Feature/Modules/Jobs/TasksFromTemplateTest.php b/tests/Feature/Modules/Jobs/TasksFromTemplateTest.php new file mode 100644 index 0000000..85e850b --- /dev/null +++ b/tests/Feature/Modules/Jobs/TasksFromTemplateTest.php @@ -0,0 +1,145 @@ +employee = User::factory()->create(['name' => 'Eero Työntekijä']); + $this->actingAs($this->employee); + $this->marketing = ServiceUnitModel::query()->where('name', 'Markkinointi')->sole(); + $this->job = CustomerJobModel::factory()->create(['name' => 'Kampanja', 'status' => 'order', 'responsible_user_id' => $this->employee->id]); + DB::table('customer_job_service_unit')->where('customer_job_id', $this->job->id)->update(['service_unit_id' => $this->marketing->id]); + $this->graphic = WorkTypeModel::query()->where('name', 'graafinen työ')->sole(); + $this->planning = WorkTypeModel::query()->where('name', 'suunnittelu')->sole(); + $printing = WorkTypeModel::query()->where('name', 'painotyö')->sole(); + + $add = fn (string $name, int $workTypeId, array $steps): int => app(AddWorkflowTemplate::class)->execute(new WorkflowTemplateData( + $name, + $workTypeId, + array_map(fn (array $step): WorkflowStepData => new WorkflowStepData(...$step), $steps), + )); + + $this->campaign = $add('Somekampanja', $this->graphic->id, [['Suunnittelu', 'Kohderyhmä ja viestit', $this->planning->id], ['Kuvat'], ['Julkaisu']]); + $this->print = $add('Esite', $printing->id, [['Painatus']]); +}); + +it('adds the steps of a template as tasks of the job', function () { + $this->get(route('jobs.show', $this->job->id))->assertSee(route('jobs.tasks.from-template', $this->job->id)); + + Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id]) + ->assertSee('Somekampanja (graafinen työ)') + ->assertSee('Vaiheet: Suunnittelu (suunnittelu) → Kuvat → Julkaisu') + ->assertDontSee('Esite') + ->set('templateId', (string) $this->campaign) + ->call('add') + ->assertHasNoErrors() + ->assertRedirect(route('jobs.show', $this->job->id).'#tasks'); + + $tasks = TaskModel::query()->orderBy('id')->get(); + + expect($tasks->map(fn ($task) => [$task->title, $task->work_type_id, $task->status->value, $task->description])->all())->toBe([ + ['Suunnittelu', $this->planning->id, 'waiting', 'Kohderyhmä ja viestit'], + ['Kuvat', $this->graphic->id, 'waiting', null], + ['Julkaisu', $this->graphic->id, 'waiting', null], + ]) + ->and(DB::table('task_assignees')->pluck('user_id')->unique()->values()->all())->toBe([$this->employee->id]); + + $this->get(route('jobs.show', $this->job->id))->assertSee('Lisättiin 3 tehtävää pohjasta Somekampanja (graafinen työ).'); +}); + +it('needs a template that is still available', function () { + Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id]) + ->call('add') + ->assertHasErrors(['templateId']) + ->assertSee('Valitse pohja.'); + + $component = Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id])->set('templateId', (string) $this->campaign); + app(SetWorkflowTemplateActive::class)->execute($this->campaign, false); + + $component->call('add') + ->assertHasErrors(['templateId']) + ->assertSee('Pohja ei ole enää käytettävissä tälle työlle. Valitse toinen.'); + + Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id]) + ->set('templateId', (string) $this->print) + ->call('add') + ->assertHasErrors(['templateId']); + + expect(TaskModel::query()->count())->toBe(0); +}); + +it('is not for subcontractors, jobs before a quote request or archived jobs', function () { + $this->job->update(['status' => 'tentative']); + $this->get(route('jobs.tasks.from-template', $this->job->id))->assertNotFound(); + + $this->job->update(['status' => 'archived']); + $this->get(route('jobs.tasks.from-template', $this->job->id))->assertNotFound(); + + $this->job->update(['status' => 'order']); + $subcontractor = User::factory()->subcontractor()->create(); + DB::table('customer_job_members')->insert(['customer_job_id' => $this->job->id, 'user_id' => $subcontractor->id]); + + $this->actingAs($subcontractor)->get(route('jobs.tasks.from-template', $this->job->id))->assertForbidden(); +}); + +it('locks the job id', function () { + Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id])->set('jobId', 999); +})->throws(CannotUpdateLockedPropertyException::class); + +it('shows a table of the chosen template tasks and saves their due dates and estimates', function () { + Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id]) + ->assertDontSee('Pohjan Somekampanja tehtävät') + ->set('templateId', (string) $this->campaign) + ->assertSet('rows', array_fill(0, 3, ['due_on' => '', 'estimated_hours' => ''])) + ->assertSee('Pohjan Somekampanja tehtävät') + ->assertSee('Määräpäivä: Kuvat') + ->assertSee('Arvioitu aika (h): Julkaisu') + ->set('rows.0.due_on', '2026-06-01') + ->set('rows.0.estimated_hours', '1,5') + ->set('rows.2.estimated_hours', '2') + ->call('add') + ->assertHasNoErrors(); + + $tasks = TaskModel::query()->orderBy('id')->get(); + + expect($tasks->map(fn ($task) => [$task->title, $task->due_on?->format('Y-m-d'), $task->estimated_hours === null ? null : (float) $task->estimated_hours])->all())->toBe([ + ['Suunnittelu', '2026-06-01', 1.5], + ['Kuvat', null, null], + ['Julkaisu', null, 2.0], + ]); +}); + +it('shows errors in the table cells and adds nothing', function () { + Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id]) + ->set('templateId', (string) $this->campaign) + ->set('rows.1.due_on', '1.6.2026') + ->set('rows.2.estimated_hours', 'paljon') + ->call('add') + ->assertHasErrors(['rows.1.due_on', 'rows.2.estimated_hours']) + ->assertSee('aria-invalid="true"', escape: false); + + expect(TaskModel::query()->count())->toBe(0); +}); + +it('empties the rows when another template is chosen', function () { + Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id]) + ->set('templateId', (string) $this->campaign) + ->set('rows.0.estimated_hours', '3') + ->set('templateId', '') + ->assertSet('rows', []) + ->set('templateId', (string) $this->campaign) + ->assertSet('rows.0.estimated_hours', ''); +}); diff --git a/tests/Feature/Modules/Shared/HolidaysTest.php b/tests/Feature/Modules/Shared/HolidaysTest.php new file mode 100644 index 0000000..7447589 --- /dev/null +++ b/tests/Feature/Modules/Shared/HolidaysTest.php @@ -0,0 +1,44 @@ +actingAs(User::factory()->management()->create()); + $this->get(route('settings.holidays'))->assertForbidden(); + + $this->actingAs(User::factory()->admin()->create()); + $this->get(route('settings.holidays', ['year' => 2026])) + ->assertOk() + ->assertSee('Arkipyhät') + ->assertSee('Vuosi 2026') + ->assertSee('pe 3.4.2026') + ->assertSee('Pitkäperjantai') + ->assertSee('Juhannusaatto'); +}); + +it('takes a holiday out of use and adds and removes a company day off', function () { + $this->actingAs(User::factory()->admin()->create()); + + Livewire::test('shared::holidays', ['year' => 2026]) + ->call('disable', '2026-12-24') + ->assertSee('Jouluaatto (to 24.12.2026) poistettu käytöstä.') + ->assertSee('Ei käytössä') + ->set('date', '2026-12-23') + ->set('name', 'Pikkujoulu') + ->call('add') + ->assertHasNoErrors() + ->assertSee('Pikkujoulu (ke 23.12.2026) lisätty.') + ->set('date', '2026-12-25') + ->set('name', 'Joulu') + ->call('add') + ->assertHasErrors('date') + ->call('remove', '2026-12-23') + ->assertSee('Pikkujoulu (ke 23.12.2026) poistettu.'); + + $this->assertDatabaseHas('holiday_overrides', ['date' => '2026-12-24', 'is_holiday' => false]); + $this->assertDatabaseMissing('holiday_overrides', ['date' => '2026-12-23']); +}); diff --git a/tests/Unit/Modules/Catalog/Application/WorkflowTemplateUseCasesTest.php b/tests/Unit/Modules/Catalog/Application/WorkflowTemplateUseCasesTest.php new file mode 100644 index 0000000..0ad77d3 --- /dev/null +++ b/tests/Unit/Modules/Catalog/Application/WorkflowTemplateUseCasesTest.php @@ -0,0 +1,136 @@ +workTypes = new InMemoryWorkTypeRepository; + $this->templates = new InMemoryWorkflowTemplateRepository; + $transactions = new FakeTransactionManager; + $builder = new WorkflowStepBuilder($this->workTypes, $units); + + $this->add = new AddWorkflowTemplate($this->templates, $this->workTypes, $builder, $transactions); + $this->update = new UpdateWorkflowTemplate($this->templates, $this->workTypes, $builder, $transactions); + $this->setActive = new SetWorkflowTemplateActive($this->templates, $transactions); + $this->setWorkTypeActive = new SetCatalogItemActive($units, $services, $this->workTypes, $transactions); + + $addUnit = new AddServiceUnit($units, $transactions); + $addWorkType = new AddWorkType($units, $services, $this->workTypes, $transactions); + $media = $addUnit->execute('Mediatuotanto'); + $marketing = $addUnit->execute('Markkinointi'); + $shared = (int) $units->save(ServiceUnit::create(new CatalogName('Kaikille yhteiset'), 3, shared: true))->id(); + + $this->videography = $addWorkType->execute($media, null, 'videokuvaus'); + $this->editing = $addWorkType->execute($media, null, 'editointi'); + $this->graphics = $addWorkType->execute($marketing, null, 'graafinen työ'); + $this->planning = $addWorkType->execute($shared, null, 'suunnittelu'); + + $this->data = fn (string $name, array $steps, ?int $workTypeId = null): WorkflowTemplateData => new WorkflowTemplateData( + $name, + $workTypeId ?? $this->videography, + array_map(fn (array $step): WorkflowStepData => new WorkflowStepData(...$step), $steps), + ); +}); + +it('adds a template with steps in order and their own work types', function () { + $id = $this->add->execute(($this->data)('Lyhyt video', [ + ['Suunnittelu', null, $this->planning], + [' Kuvaus ', 'Kuvauspäivä asiakkaalla'], + ['Editointi', '', $this->editing], + ])); + + $template = $this->templates->findById($id); + + expect($template?->name()->value)->toBe('Lyhyt video') + ->and($template?->isActive())->toBeTrue() + ->and(array_map(fn ($step) => [$step->title->value, $step->description, $step->workTypeId], $template?->steps() ?? []))->toBe([ + ['Suunnittelu', null, $this->planning], + ['Kuvaus', 'Kuvauspäivä asiakkaalla', null], + ['Editointi', null, $this->editing], + ]); +}); + +it('needs at least one step with a title, and tells which step is wrong', function () { + expect(fn () => $this->add->execute(($this->data)('Tyhjä', [])))->toThrow(WorkflowTemplateNeedsSteps::class); + + try { + $this->add->execute(($this->data)('Lyhyt video', [['Kuvaus'], [' ']])); + $this->fail('The empty title was accepted.'); + } catch (InvalidWorkflowStepTitle $exception) { + expect($exception->stepIndex)->toBe(1); + } +}); + +it('rejects a name the work type already has, but allows it for another work type', function () { + $this->add->execute(($this->data)('Lyhyt video', [['Kuvaus']])); + $this->add->execute(($this->data)('lyhyt video', [['Kuvaus']], $this->editing)); + + expect(fn () => $this->add->execute(($this->data)('LYHYT VIDEO', [['Kuvaus']])))->toThrow(WorkflowTemplateNameTaken::class); +}); + +it('allows a step work type only from the same unit or the shared unit, and in use', function () { + try { + $this->add->execute(($this->data)('Lyhyt video', [['Kuvaus'], ['Grafiikka', null, $this->graphics]])); + $this->fail('A work type of another unit was accepted.'); + } catch (WorkflowStepWorkTypeNotAllowed $exception) { + expect($exception->stepIndex)->toBe(1); + } + + $this->setWorkTypeActive->execute(CatalogLevel::WorkType, $this->editing, false); + + expect(fn () => $this->add->execute(($this->data)('Lyhyt video', [['Editointi', null, $this->editing]]))) + ->toThrow(WorkflowStepWorkTypeNotAllowed::class); +}); + +it('needs a template work type in use', function () { + $this->setWorkTypeActive->execute(CatalogLevel::WorkType, $this->videography, false); + + $this->add->execute(($this->data)('Lyhyt video', [['Kuvaus']])); +})->throws(CatalogItemNotFound::class); + +it('updates name and steps, keeping step work types taken out of use since', function () { + $id = $this->add->execute(($this->data)('Lyhyt video', [['Kuvaus'], ['Editointi', null, $this->editing]])); + $this->setWorkTypeActive->execute(CatalogLevel::WorkType, $this->editing, false); + + $this->update->execute($id, ($this->data)('Lyhyt video 2', [['Editointi', null, $this->editing], ['Toimitus']])); + + $template = $this->templates->findById($id); + + expect($template?->name()->value)->toBe('Lyhyt video 2') + ->and(array_map(fn ($step) => $step->title->value, $template?->steps() ?? []))->toBe(['Editointi', 'Toimitus']); + + expect(fn () => $this->update->execute(999, ($this->data)('X', [['Kuvaus']])))->toThrow(WorkflowTemplateNotFound::class); +}); + +it('takes a template out of use and back', function () { + $id = $this->add->execute(($this->data)('Lyhyt video', [['Kuvaus']])); + + $this->setActive->execute($id, false); + expect($this->templates->findById($id)?->isActive())->toBeFalse(); + + $this->setActive->execute($id, true); + expect($this->templates->findById($id)?->isActive())->toBeTrue(); +}); diff --git a/tests/Unit/Modules/Customers/Application/RemoveCustomerTest.php b/tests/Unit/Modules/Customers/Application/RemoveCustomerTest.php new file mode 100644 index 0000000..6278d72 --- /dev/null +++ b/tests/Unit/Modules/Customers/Application/RemoveCustomerTest.php @@ -0,0 +1,70 @@ +customers = new InMemoryCustomerRepository; + $this->contacts = new InMemoryCustomerContactRepository; + $this->billingUnits = new InMemoryBillingUnitRepository; + $this->references = new FakeCustomerReferences; + $this->removal = new CustomerRemoval($this->customers, $this->contacts, $this->billingUnits, $this->references); + $this->removeCustomer = new RemoveCustomer($this->customers, $this->removal, new FakeTransactionManager); + + $this->customerId = $this->customers->save(Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company))->id(); +}); + +it('removes a customer that has nothing but its name', function () { + expect($this->removal->canRemove($this->customerId))->toBeTrue(); + + $this->removeCustomer->execute($this->customerId); + + expect($this->customers->findById($this->customerId))->toBeNull() + ->and($this->removal->canRemove($this->customerId))->toBeFalse(); +}); + +it('does not remove an unknown customer', function () { + $this->removeCustomer->execute(999); +})->throws(CustomerNotFound::class); + +it('does not remove the internal customer', function () { + $internalId = $this->customers->save(Customer::reconstitute(50, new CustomerName('Oma Oy'), CustomerType::Company, null, null, true))->id(); + + expect($this->removal->canRemove($internalId))->toBeFalse() + ->and(fn () => $this->removeCustomer->execute($internalId))->toThrow(InternalCustomerCannotBeRemoved::class) + ->and($this->customers->findById($internalId))->not->toBeNull(); +}); + +it('does not remove a customer that has a contact or a billing unit', function (string $row) { + match ($row) { + 'contact' => $this->contacts->save(CustomerContact::create($this->customerId, new ContactName('Maija'))), + 'billing unit' => $this->billingUnits->save(BillingUnit::create($this->customerId, new BillingUnitName('Mainos Oy'))), + }; + + expect($this->removal->canRemove($this->customerId))->toBeFalse() + ->and(fn () => $this->removeCustomer->execute($this->customerId))->toThrow(CustomerInUse::class) + ->and($this->customers->findById($this->customerId))->not->toBeNull(); +})->with(['contact', 'billing unit']); + +it('does not remove a customer that other modules refer to', function () { + $this->references->referencedIds = [$this->customerId]; + + expect($this->removal->canRemove($this->customerId))->toBeFalse() + ->and(fn () => $this->removeCustomer->execute($this->customerId))->toThrow(CustomerInUse::class) + ->and($this->customers->findById($this->customerId))->not->toBeNull(); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TaskCalendarLayoutTest.php b/tests/Unit/Modules/Jobs/Application/TaskCalendarLayoutTest.php new file mode 100644 index 0000000..a0db7cf --- /dev/null +++ b/tests/Unit/Modules/Jobs/Application/TaskCalendarLayoutTest.php @@ -0,0 +1,35 @@ + $assignments + */ +function calendarTask(int $id, string $from, string $to, array $assignments, ?string $dueOn = null): CalendarTask +{ + return new CalendarTask($id, 1, '2026-001', 'Kampanja', 'Tehtävä '.$id, TaskStatus::Waiting, $dueOn, null, $from, $to, $assignments); +} + +it('puts each task on its assignees rows and overlapping tasks on their own lanes', function () { + $days = ['2026-12-07', '2026-12-08', '2026-12-09', '2026-12-10']; + $tasks = [ + calendarTask(1, '2026-12-07', '2026-12-08', [new CalendarAssignment(10, '2026-12-07', '2026-12-08', 480), new CalendarAssignment(11, '2026-12-07', '2026-12-09', 480)]), + calendarTask(2, '2026-12-08', '2026-12-08', [new CalendarAssignment(10, '2026-12-08', '2026-12-08', 120)]), + calendarTask(3, '2026-12-09', '2026-12-20', [new CalendarAssignment(10, null, null, 0)], dueOn: '2026-12-15'), + calendarTask(4, '2026-12-01', '2026-12-07', []), + ]; + $people = [['id' => 10, 'name' => 'Eero'], ['id' => 11, 'name' => 'Aino'], ['id' => null, 'name' => 'Ei tekijää']]; + + $rows = TaskCalendarLayout::build($days, $people, $tasks, [10 => ['2026-12-08' => 360]]); + $bars = fn (int $row): array => array_map(fn ($bar) => [$bar->task->taskId, $bar->start, $bar->span, $bar->lane, $bar->late], $rows[$row]->bars); + + expect($bars(0))->toBe([[1, 0, 2, 0, false], [2, 1, 1, 1, false], [3, 2, 2, 0, true]]) + ->and($rows[0]->lanes)->toBe(2) + ->and($rows[0]->minutesByDay)->toBe(['2026-12-07' => 0, '2026-12-08' => 360, '2026-12-09' => 0, '2026-12-10' => 0]) + ->and($bars(1))->toBe([[1, 0, 3, 0, false]]) + ->and($bars(2))->toBe([[4, 0, 1, 0, false]]) + ->and(array_map(fn ($bar) => $bar->task->taskId, $rows[0]->barsOn(1)))->toBe([1, 2]); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php index d4e51db..f9c8666 100644 --- a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php +++ b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php @@ -3,28 +3,36 @@ use App\Modules\Jobs\Application\DTOs\CustomerJobData; use App\Modules\Jobs\Application\DTOs\TaskData; use App\Modules\Jobs\Application\Services\JobDetailsFactory; +use App\Modules\Jobs\Application\Services\TaskPlanner; use App\Modules\Jobs\Application\Services\TaskReferenceChecker; use App\Modules\Jobs\Application\UseCases\AddTask; use App\Modules\Jobs\Application\UseCases\ChangeJobStatus; use App\Modules\Jobs\Application\UseCases\ChangeTaskStatus; +use App\Modules\Jobs\Application\UseCases\ClearTaskSchedule; use App\Modules\Jobs\Application\UseCases\CreateCustomerJob; use App\Modules\Jobs\Application\UseCases\RemoveTask; +use App\Modules\Jobs\Application\UseCases\ScheduleTask; use App\Modules\Jobs\Application\UseCases\UpdateTask; use App\Modules\Jobs\Domain\Enums\JobStatus; use App\Modules\Jobs\Domain\Enums\TaskStatus; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskTitle; +use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart; use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries; use App\Modules\Jobs\Domain\Exceptions\TaskNotFound; use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet; use App\Modules\Jobs\Domain\ValueObjects\TaskTitle; +use App\Modules\Shared\Application\UseCases\HolidayCalendar; use Tests\Fakes\FakeCatalogQueries; use Tests\Fakes\FakeClock; use Tests\Fakes\FakeCustomerQueries; +use Tests\Fakes\FakeSettings; use Tests\Fakes\FakeTaskUsage; use Tests\Fakes\FakeTransactionManager; use Tests\Fakes\FakeUserAccountQueries; use Tests\Fakes\InMemoryCustomerJobRepository; +use Tests\Fakes\InMemoryHolidayOverrides; +use Tests\Fakes\InMemoryTaskBookingRepository; use Tests\Fakes\InMemoryTaskRepository; beforeEach(function () { @@ -50,8 +58,12 @@ beforeEach(function () { $this->tentativeJobId = $createJob->execute(new CustomerJobData('Alustava', 1, [1], 10, 'one_off', 'tentative', 'normal'), 10); $checker = new TaskReferenceChecker($this->catalog, $this->users); - $this->addTask = new AddTask($this->jobs, $this->tasks, $checker, $transactions); - $this->updateTask = new UpdateTask($this->jobs, $this->tasks, $checker, $transactions); + $this->bookings = new InMemoryTaskBookingRepository($this->tasks); + $this->planner = new TaskPlanner($this->bookings, new HolidayCalendar(new InMemoryHolidayOverrides), new FakeSettings); + $this->addTask = new AddTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions); + $this->updateTask = new UpdateTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions); + $this->scheduleTask = new ScheduleTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions); + $this->clearSchedule = new ClearTaskSchedule($this->tasks, $this->planner, $transactions); $this->changeTaskStatus = new ChangeTaskStatus($this->tasks, $transactions); $this->usage = new FakeTaskUsage; $this->removeTask = new RemoveTask($this->tasks, $this->usage, $transactions); @@ -136,3 +148,61 @@ it('does not remove a task with time entries', function () { ->and(JobStatus::Done->locksTime())->toBeTrue() ->and(JobStatus::OnHold->locksTime())->toBeFalse(); }); + +it('books a scheduled task evenly from the working days of its period', function () { + $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '12', assigneeUserIds: [10], plannedFrom: '2026-12-04', plannedTo: '2026-12-07'), 10); + $oneDayId = $this->addTask->execute($this->jobId, new TaskData('Palaveri', 91, 'waiting', assigneeUserIds: [10], plannedFrom: '2026-12-08'), 10); + + expect($this->bookings->of($taskId, 10))->toBe(['2026-12-04' => 360, '2026-12-07' => 360]) + ->and($this->tasks->findForJob($this->jobId, $oneDayId)?->plannedTo()?->format('Y-m-d'))->toBe('2026-12-08') + ->and($this->bookings->of($oneDayId, 10))->toBe([]); +}); + +it('moves what does not fit in a full day to the next working day', function () { + $this->addTask->execute($this->jobId, new TaskData('Kuvaus', 11, 'waiting', estimatedHours: '6', assigneeUserIds: [10], plannedFrom: '2026-12-04'), 10); + $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserIds: [10]), 10); + + $result = $this->scheduleTask->execute($this->jobId, $taskId, 10, 10, '2026-12-04', '2026-12-04'); + + expect($result->extended)->toBeTrue() + ->and($result->plannedTo)->toBe('2026-12-07') + ->and($this->bookings->of($taskId, 10))->toBe(['2026-12-04' => 120, '2026-12-07' => 120]); +}); + +it('does not count done tasks in the day load', function () { + $doneId = $this->addTask->execute($this->jobId, new TaskData('Kuvaus', 11, 'waiting', estimatedHours: '8', assigneeUserIds: [10], plannedFrom: '2026-12-04'), 10); + $this->changeTaskStatus->execute($this->jobId, $doneId, TaskStatus::Done); + $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '8', assigneeUserIds: [10], plannedFrom: '2026-12-04'), 10); + + expect($this->bookings->of($taskId, 10))->toBe(['2026-12-04' => 480]); +}); + +it('moves a task to another person and gives it the days its estimate needs', function () { + $this->users->addUser(11, 'Aino'); + $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '20', assigneeUserIds: [10], plannedFrom: '2026-12-01'), 10); + + $result = $this->scheduleTask->execute($this->jobId, $taskId, 10, 11, '2026-12-11', null); + + expect($this->tasks->findForJob($this->jobId, $taskId)?->assigneeUserIds())->toBe([11]) + ->and($result->plannedFrom)->toBe('2026-12-11') + ->and($result->plannedTo)->toBe('2026-12-15') + ->and($result->extended)->toBeFalse() + ->and($this->bookings->of($taskId, 10))->toBe([]) + ->and(array_sum($this->bookings->of($taskId, 11)))->toBe(1200); +}); + +it('rejects moving a task to an inactive person or ending it before it starts', function () { + $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', assigneeUserIds: [10]), 10); + + expect(fn () => $this->scheduleTask->execute($this->jobId, $taskId, 10, 12, '2026-12-07', '2026-12-07'))->toThrow(InvalidTaskReference::class) + ->and(fn () => $this->scheduleTask->execute($this->jobId, $taskId, 10, 10, '2026-12-07', '2026-12-04'))->toThrow(PlanEndsBeforeStart::class); +}); + +it('takes a task out of the calendar', function () { + $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserIds: [10], plannedFrom: '2026-12-07'), 10); + + $this->clearSchedule->execute($this->jobId, $taskId); + + expect($this->tasks->findForJob($this->jobId, $taskId)?->isScheduled())->toBeFalse() + ->and($this->bookings->of($taskId, 10))->toBe([]); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php b/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php new file mode 100644 index 0000000..2bbdc58 --- /dev/null +++ b/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php @@ -0,0 +1,96 @@ +jobs = new InMemoryCustomerJobRepository; + $this->tasks = new InMemoryTaskRepository; + $customers = new FakeCustomerQueries; + $catalog = new FakeCatalogQueries; + $users = new FakeUserAccountQueries; + $this->templates = new FakeWorkflowTemplateQueries; + $transactions = new FakeTransactionManager; + + $customers->customers = [1 => 'Mainos Oy']; + $catalog->addServiceUnit(1, 'Mediatuotanto'); + $catalog->addServiceUnit(2, 'Painotuotanto'); + $catalog->addServiceUnit(9, 'Kaikille yhteiset', shared: true); + $catalog->addWorkType(11, 1, 'videokuvaus'); + $catalog->addWorkType(12, 1, 'editointi'); + $catalog->addWorkType(21, 2, 'painotyö'); + $catalog->addWorkType(91, 9, 'suunnittelu'); + $users->addUser(10, 'Eero'); + + $createJob = new CreateCustomerJob($this->jobs, $this->jobs, new JobDetailsFactory($customers, $catalog, $users), $transactions, new FakeClock(new DateTimeImmutable('2026-05-01'))); + $this->jobId = $createJob->execute(new CustomerJobData('Video', 1, [1], 10, 'one_off', 'quote_request', 'normal'), 10); + $this->tentativeJobId = $createJob->execute(new CustomerJobData('Alustava', 1, [1], 10, 'one_off', 'tentative', 'normal'), 10); + + $this->templates->addTemplate(1, 'Lyhyt video', 11, 1, [['Suunnittelu', 91], ['Kuvaus'], ['Editointi', 12]]); + $this->templates->addTemplate(2, 'Painos', 21, 2, [['Painatus']]); + $this->templates->addTemplate(3, 'Vanha', 11, 1, [['Kuvaus']], active: false); + $this->templates->addTemplate(4, 'Rikki', 11, 1, [['Painatus', 21]]); + + $this->addTasks = new AddTasksFromWorkflowTemplate($this->jobs, $this->tasks, $this->templates, new TaskReferenceChecker($catalog, $users), $transactions); +}); + +it('adds a waiting task per step in order, with the step work type and the adder as assignee', function () { + expect($this->addTasks->execute($this->jobId, 1, 10))->toBe(3); + + $tasks = array_values($this->tasks->tasks); + + expect(array_map(fn (Task $task): array => [$task->title()->value, $task->workTypeId(), $task->status(), $task->assigneeUserIds()], $tasks))->toBe([ + ['Suunnittelu', 91, TaskStatus::Waiting, [10]], + ['Kuvaus', 11, TaskStatus::Waiting, [10]], + ['Editointi', 12, TaskStatus::Waiting, [10]], + ]); +}); + +it('rejects a template out of use or for other service units', function (int $templateId) { + $this->addTasks->execute($this->jobId, $templateId, 10); +})->with([3, 2, 999])->throws(WorkflowTemplateNotAvailable::class); + +it('rejects a step whose work type is not available for the job', function () { + expect(fn () => $this->addTasks->execute($this->jobId, 4, 10))->toThrow(InvalidTaskReference::class); +}); + +it('adds no tasks before the job is a quote request', function () { + $this->addTasks->execute($this->tentativeJobId, 1, 10); +})->throws(TasksNotAllowedYet::class); + +it('gives each task the due date and estimate entered for its step', function () { + $this->addTasks->execute($this->jobId, 1, 10, [ + new TemplateTaskSchedule('2026-05-10', '1,5'), + new TemplateTaskSchedule(null, '8'), + ]); + + $tasks = array_values($this->tasks->tasks); + + expect(array_map(fn (Task $task): array => [$task->dueOn()?->format('Y-m-d'), $task->estimatedHours()?->format()], $tasks))->toBe([ + ['2026-05-10', '1.5'], + [null, '8'], + [null, null], + ]); +}); + +it('rejects an estimate that is not a number', function () { + $this->addTasks->execute($this->jobId, 1, 10, [new TemplateTaskSchedule(null, 'paljon')]); +})->throws(InvalidEstimatedHours::class); diff --git a/tests/Unit/Modules/Jobs/Domain/TaskSchedulerTest.php b/tests/Unit/Modules/Jobs/Domain/TaskSchedulerTest.php new file mode 100644 index 0000000..c4a3fcf --- /dev/null +++ b/tests/Unit/Modules/Jobs/Domain/TaskSchedulerTest.php @@ -0,0 +1,47 @@ +minutesByDay)->toBe(['2026-12-04' => 210, '2026-12-07' => 195, '2026-12-08' => 195]) + ->and($schedule->end->format('Y-m-d'))->toBe('2026-12-08') + ->and($schedule->extended)->toBeFalse(); +}); + +it('skips holidays and uses weekend days when the period has nothing else', function () { + $overHolidays = TaskScheduler::schedule(scheduleDay('2026-12-24'), scheduleDay('2026-12-28'), 240, [], 480, ['2026-12-24', '2026-12-25']); + $weekend = TaskScheduler::schedule(scheduleDay('2026-12-05'), scheduleDay('2026-12-06'), 300, [], 480, []); + + expect($overHolidays->minutesByDay)->toBe(['2026-12-28' => 240]) + ->and($weekend->minutesByDay)->toBe(['2026-12-05' => 150, '2026-12-06' => 150]); +}); + +it('moves what does not fit to the next working days and ends later', function () { + $schedule = TaskScheduler::schedule(scheduleDay('2026-12-04'), scheduleDay('2026-12-04'), 600, ['2026-12-04' => 300, '2026-12-07' => 480], 480, []); + + expect($schedule->minutesByDay)->toBe(['2026-12-04' => 180, '2026-12-08' => 420]) + ->and($schedule->end->format('Y-m-d'))->toBe('2026-12-08') + ->and($schedule->extended)->toBeTrue(); +}); + +it('books nothing without an estimate', function () { + $schedule = TaskScheduler::schedule(scheduleDay('2026-12-07'), scheduleDay('2026-12-09'), 0, [], 480, []); + + expect($schedule->minutesByDay)->toBe([]) + ->and($schedule->end->format('Y-m-d'))->toBe('2026-12-09'); +}); + +it('gives a placed task the working days its estimate needs', function () { + expect(TaskScheduler::defaultEnd(scheduleDay('2026-12-07'), 240, 480, [])->format('Y-m-d'))->toBe('2026-12-07') + ->and(TaskScheduler::defaultEnd(scheduleDay('2026-12-04'), 1200, 480, [])->format('Y-m-d'))->toBe('2026-12-08') + ->and(TaskScheduler::defaultEnd(scheduleDay('2026-12-23'), 960, 480, ['2026-12-24', '2026-12-25'])->format('Y-m-d'))->toBe('2026-12-28') + ->and(TaskScheduler::defaultEnd(scheduleDay('2026-12-05'), 0, 480, [])->format('Y-m-d'))->toBe('2026-12-05'); +}); diff --git a/tests/Unit/Modules/Shared/FinnishHolidaysTest.php b/tests/Unit/Modules/Shared/FinnishHolidaysTest.php new file mode 100644 index 0000000..846f6d3 --- /dev/null +++ b/tests/Unit/Modules/Shared/FinnishHolidaysTest.php @@ -0,0 +1,65 @@ +format('Y-m-d'))->toBe($easter) + ->and(array_search('midsummer_eve', $holidays, true))->toBe($midsummerEve); +})->with([ + [2025, '2025-04-20', '2025-06-20'], + [2026, '2026-04-05', '2026-06-19'], + [2027, '2027-03-28', '2027-06-25'], +]); + +it('lists the holidays of a year in date order', function () { + expect(FinnishHolidays::forYear(2026))->toBe([ + '2026-01-01' => 'new_years_day', + '2026-01-06' => 'epiphany', + '2026-04-03' => 'good_friday', + '2026-04-06' => 'easter_monday', + '2026-05-01' => 'may_day', + '2026-05-14' => 'ascension_day', + '2026-06-19' => 'midsummer_eve', + '2026-12-06' => 'independence_day', + '2026-12-24' => 'christmas_eve', + '2026-12-25' => 'christmas_day', + '2026-12-26' => 'st_stephens_day', + ]); +}); + +it('takes holidays out of use and adds company days off', function () { + $calendar = new HolidayCalendar(new InMemoryHolidayOverrides); + + $calendar->disable('2026-12-24'); + $calendar->addCompanyDay('2026-12-23', ' Pikkujoulu '); + + $december = $calendar->between('2026-12-20', '2026-12-31'); + + expect(array_map(fn ($holiday) => [$holiday->date, $holiday->key, $holiday->name, $holiday->active], $december))->toBe([ + ['2026-12-23', null, 'Pikkujoulu', true], + ['2026-12-24', 'christmas_eve', null, false], + ['2026-12-25', 'christmas_day', null, true], + ['2026-12-26', 'st_stephens_day', null, true], + ])->and($calendar->activeDatesBetween('2026-12-20', '2026-12-31'))->toBe(['2026-12-23', '2026-12-25', '2026-12-26']); + + $calendar->enable('2026-12-24'); + $calendar->removeCompanyDay('2026-12-23'); + + expect($calendar->activeDatesBetween('2026-12-20', '2026-12-31'))->toBe(['2026-12-24', '2026-12-25', '2026-12-26']); +}); + +it('rejects invalid holiday changes', function () { + $calendar = new HolidayCalendar(new InMemoryHolidayOverrides); + + expect(fn () => $calendar->disable('2026-12-23'))->toThrow(NotAHoliday::class) + ->and(fn () => $calendar->removeCompanyDay('2026-12-25'))->toThrow(NotAHoliday::class) + ->and(fn () => $calendar->addCompanyDay('2026-12-25', 'Joulu'))->toThrow(HolidayAlreadyExists::class) + ->and(fn () => $calendar->addCompanyDay('2026-12-23', ' '))->toThrow(InvalidHolidayName::class); +});