diff --git a/CLAUDE.md b/CLAUDE.md index 2dc46e0..e675f47 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. -- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. +- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). - `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`. - Generate module files with Artisan, then edit them: `php artisan make:class Modules////` for classes, `make:test --pest [--unit] Modules//Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files. diff --git a/app/Modules/Jobs/Application/Contracts/TaskQueries.php b/app/Modules/Jobs/Application/Contracts/TaskQueries.php new file mode 100644 index 0000000..a07c311 --- /dev/null +++ b/app/Modules/Jobs/Application/Contracts/TaskQueries.php @@ -0,0 +1,22 @@ + + */ + public function tasksOf(int $jobId): array; + + /** + * Null when the task does not exist or belongs to another job. + */ + public function findTask(int $jobId, int $taskId): ?TaskSummary; +} diff --git a/app/Modules/Jobs/Application/DTOs/TaskData.php b/app/Modules/Jobs/Application/DTOs/TaskData.php new file mode 100644 index 0000000..e0ca86b --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/TaskData.php @@ -0,0 +1,24 @@ + $assigneeUserIds + */ + public function __construct( + public string $title, + public int $workTypeId, + public string $status, + public ?string $description = null, + public ?string $dueOn = null, + public ?string $estimatedHours = null, + public array $assigneeUserIds = [], + ) {} +} diff --git a/app/Modules/Jobs/Application/DTOs/TaskSummary.php b/app/Modules/Jobs/Application/DTOs/TaskSummary.php new file mode 100644 index 0000000..d59af75 --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/TaskSummary.php @@ -0,0 +1,28 @@ + $assignees + */ + public function __construct( + public int $id, + public int $jobId, + public string $title, + public ?string $description, + public TaskStatus $status, + public ?string $dueOn, + public ?string $estimatedHours, + public NamedId $workType, + public array $assignees, + ) {} +} diff --git a/app/Modules/Jobs/Application/Services/TaskReferenceChecker.php b/app/Modules/Jobs/Application/Services/TaskReferenceChecker.php new file mode 100644 index 0000000..8a06723 --- /dev/null +++ b/app/Modules/Jobs/Application/Services/TaskReferenceChecker.php @@ -0,0 +1,66 @@ + $assigneeUserIds + * + * @throws InvalidTaskReference + */ + public function check(CustomerJob $job, int $workTypeId, array $assigneeUserIds, ?Task $current = null): void + { + if ($workTypeId !== $current?->workTypeId() && ! in_array($workTypeId, $this->workTypeIdsFor($job), true)) { + throw new InvalidTaskReference('work_type'); + } + + $activeIds = array_map(fn ($option): int => $option->id, $this->users->activeUserOptions()); + + foreach ($assigneeUserIds as $userId) { + if (! in_array($userId, $activeIds, true) && ! in_array($userId, $current?->assigneeUserIds() ?? [], true)) { + throw new InvalidTaskReference('assignees'); + } + } + } + + /** + * @return list + */ + private function workTypeIdsFor(CustomerJob $job): array + { + $ids = []; + + foreach ($this->catalog->activeWorkTypesFor($job->details()->serviceUnitIds) as $unit) { + foreach ($unit->workTypes as $workType) { + $ids[] = $workType->id; + } + + foreach ($unit->services as $service) { + foreach ($service->workTypes as $workType) { + $ids[] = $workType->id; + } + } + } + + return $ids; + } +} diff --git a/app/Modules/Jobs/Application/UseCases/AddTask.php b/app/Modules/Jobs/Application/UseCases/AddTask.php new file mode 100644 index 0000000..ae5a87f --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/AddTask.php @@ -0,0 +1,59 @@ +title); + + return $this->transactions->run(function () use ($jobId, $data, $title, $actorUserId): int { + $job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId); + $this->references->check($job, $data->workTypeId, $data->assigneeUserIds); + + $task = Task::create( + $jobId, + $job->details()->status, + $data->workTypeId, + $title, + $data->description, + TaskStatus::from($data->status), + TaskInput::date($data->dueOn), + TaskInput::hours($data->estimatedHours), + $data->assigneeUserIds, + $actorUserId, + ); + + return (int) $this->tasks->save($task)->id(); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/ChangeTaskStatus.php b/app/Modules/Jobs/Application/UseCases/ChangeTaskStatus.php new file mode 100644 index 0000000..3a976b1 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/ChangeTaskStatus.php @@ -0,0 +1,30 @@ +transactions->run(function () use ($jobId, $taskId, $status): void { + $task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId); + $task->changeStatus($status); + $this->tasks->save($task); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/RemoveTask.php b/app/Modules/Jobs/Application/UseCases/RemoveTask.php new file mode 100644 index 0000000..c65cd45 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/RemoveTask.php @@ -0,0 +1,32 @@ +transactions->run(function () use ($jobId, $taskId): void { + $task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId); + $this->tasks->delete($task); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/TaskInput.php b/app/Modules/Jobs/Application/UseCases/TaskInput.php new file mode 100644 index 0000000..bfe69ba --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/TaskInput.php @@ -0,0 +1,41 @@ +format('Y-m-d') !== $value) { + throw new InvalidArgumentException("Not a Y-m-d date: {$value}"); + } + + return $date; + } + + public static function hours(?string $value): ?EstimatedHours + { + $value = $value === null ? '' : trim($value); + + return $value === '' ? null : EstimatedHours::fromString($value); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/UpdateTask.php b/app/Modules/Jobs/Application/UseCases/UpdateTask.php new file mode 100644 index 0000000..070a373 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/UpdateTask.php @@ -0,0 +1,55 @@ +title); + + $this->transactions->run(function () use ($jobId, $taskId, $data, $title): void { + $job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId); + $task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId); + + $this->references->check($job, $data->workTypeId, $data->assigneeUserIds, $task); + + $task->changeDetails( + $data->workTypeId, + $title, + $data->description, + TaskStatus::from($data->status), + TaskInput::date($data->dueOn), + TaskInput::hours($data->estimatedHours), + $data->assigneeUserIds, + ); + + $this->tasks->save($task); + }); + } +} diff --git a/app/Modules/Jobs/Domain/Contracts/TaskRepository.php b/app/Modules/Jobs/Domain/Contracts/TaskRepository.php new file mode 100644 index 0000000..fed134e --- /dev/null +++ b/app/Modules/Jobs/Domain/Contracts/TaskRepository.php @@ -0,0 +1,19 @@ + $assigneeUserIds + */ + private function __construct( + private ?int $id, + private int $jobId, + private int $workTypeId, + private TaskTitle $title, + private ?string $description, + private TaskStatus $status, + private ?DateTimeImmutable $dueOn, + private ?EstimatedHours $estimatedHours, + private array $assigneeUserIds, + private int $createdBy, + ) { + $this->assigneeUserIds = self::normaliseIds($assigneeUserIds); + } + + /** + * @param list $assigneeUserIds + * + * @throws TasksNotAllowedYet + */ + public static function create( + int $jobId, + JobStatus $jobStatus, + int $workTypeId, + TaskTitle $title, + ?string $description, + TaskStatus $status, + ?DateTimeImmutable $dueOn, + ?EstimatedHours $estimatedHours, + array $assigneeUserIds, + int $createdBy, + ): self { + if (! $jobStatus->allowsTasks()) { + throw new TasksNotAllowedYet; + } + + return new self(null, $jobId, $workTypeId, $title, self::text($description), $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy); + } + + /** + * @param list $assigneeUserIds + */ + public static function reconstitute( + int $id, + int $jobId, + int $workTypeId, + TaskTitle $title, + ?string $description, + TaskStatus $status, + ?DateTimeImmutable $dueOn, + ?EstimatedHours $estimatedHours, + array $assigneeUserIds, + int $createdBy, + ): self { + return new self($id, $jobId, $workTypeId, $title, $description, $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy); + } + + /** + * @param list $assigneeUserIds + */ + public function changeDetails( + int $workTypeId, + TaskTitle $title, + ?string $description, + TaskStatus $status, + ?DateTimeImmutable $dueOn, + ?EstimatedHours $estimatedHours, + array $assigneeUserIds, + ): void { + $this->workTypeId = $workTypeId; + $this->title = $title; + $this->description = self::text($description); + $this->status = $status; + $this->dueOn = $dueOn; + $this->estimatedHours = $estimatedHours; + $this->assigneeUserIds = self::normaliseIds($assigneeUserIds); + } + + public function changeStatus(TaskStatus $status): void + { + $this->status = $status; + } + + public function id(): ?int + { + return $this->id; + } + + public function jobId(): int + { + return $this->jobId; + } + + public function workTypeId(): int + { + return $this->workTypeId; + } + + public function title(): TaskTitle + { + return $this->title; + } + + public function description(): ?string + { + return $this->description; + } + + public function status(): TaskStatus + { + return $this->status; + } + + public function dueOn(): ?DateTimeImmutable + { + return $this->dueOn; + } + + public function estimatedHours(): ?EstimatedHours + { + return $this->estimatedHours; + } + + /** + * @return list + */ + public function assigneeUserIds(): array + { + return $this->assigneeUserIds; + } + + public function createdBy(): int + { + return $this->createdBy; + } + + /** + * @param list $ids + * @return list + */ + private static function normaliseIds(array $ids): array + { + $ids = array_values(array_unique($ids)); + sort($ids); + + return $ids; + } + + private static function text(?string $value): ?string + { + $value = $value === null ? '' : trim($value); + + return $value === '' ? null : $value; + } +} diff --git a/app/Modules/Jobs/Domain/Enums/JobStatus.php b/app/Modules/Jobs/Domain/Enums/JobStatus.php index b06613f..abea0f8 100644 --- a/app/Modules/Jobs/Domain/Enums/JobStatus.php +++ b/app/Modules/Jobs/Domain/Enums/JobStatus.php @@ -30,6 +30,14 @@ enum JobStatus: string return $this === self::Invoiced || $this === self::Billed; } + /** + * Tasks can be added from a quote request on (K36), not to an archived job. + */ + public function allowsTasks(): bool + { + return ! in_array($this, [self::Prospect, self::Tentative, self::Archived], true); + } + /** * The Kanban columns: every status except archived. * diff --git a/app/Modules/Jobs/Domain/Enums/TaskStatus.php b/app/Modules/Jobs/Domain/Enums/TaskStatus.php new file mode 100644 index 0000000..404fc92 --- /dev/null +++ b/app/Modules/Jobs/Domain/Enums/TaskStatus.php @@ -0,0 +1,16 @@ + self::MAX_LENGTH) { + throw new InvalidTaskTitle; + } + + $this->value = $value; + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php new file mode 100644 index 0000000..4c238fe --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php @@ -0,0 +1,49 @@ + */ + use HasFactory; + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'customer_job_id' => 'integer', + 'work_type_id' => 'integer', + 'status' => TaskStatus::class, + 'due_on' => 'immutable_date', + 'created_by' => 'integer', + ]; + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php index d3f0d58..bb7a660 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php @@ -236,7 +236,8 @@ class EloquentCustomerJobQueries implements CustomerJobQueries } /** - * Restricts to jobs where the user is responsible, contact, biller or member. + * Restricts to jobs where the user is responsible, contact, biller, + * member or an assignee of one of the job's tasks. * * @param Builder $query * @return Builder @@ -247,6 +248,10 @@ class EloquentCustomerJobQueries implements CustomerJobQueries ->where('responsible_user_id', $userId) ->orWhere('contact_user_id', $userId) ->orWhere('biller_user_id', $userId) - ->orWhereIn('id', DB::table('customer_job_members')->select('customer_job_id')->where('user_id', $userId))); + ->orWhereIn('id', DB::table('customer_job_members')->select('customer_job_id')->where('user_id', $userId)) + ->orWhereIn('id', DB::table('tasks') + ->join('task_assignees', 'task_assignees.task_id', '=', 'tasks.id') + ->select('tasks.customer_job_id') + ->where('task_assignees.user_id', $userId))); } } diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php new file mode 100644 index 0000000..b0a2eee --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php @@ -0,0 +1,75 @@ +where('customer_job_id', $jobId) + ->orderByRaw('status = ?', [TaskStatus::Done->value]) + ->orderByRaw('due_on IS NULL') + ->orderBy('due_on') + ->orderBy('id') + ->get(); + + return $this->summaries($models); + } + + public function findTask(int $jobId, int $taskId): ?TaskSummary + { + $model = TaskModel::query()->where('customer_job_id', $jobId)->find($taskId); + + return $model === null ? null : $this->summaries(collect([$model]))[0]; + } + + /** + * @param Collection $models + * @return list + */ + private function summaries(Collection $models): array + { + $assignees = DB::table('task_assignees') + ->whereIn('task_id', $models->pluck('id')->all()) + ->get() + ->groupBy('task_id'); + $userNames = $this->users->namesByIds($assignees->flatten()->pluck('user_id')->map(fn ($id): int => (int) $id)->unique()->values()->all()); + + $workTypeNames = []; + foreach ($models->pluck('work_type_id')->unique() as $workTypeId) { + $workTypeNames[$workTypeId] = $this->catalog->findWorkType((int) $workTypeId)->name ?? ''; + } + + return $models->map(fn (TaskModel $model): TaskSummary => new TaskSummary( + id: $model->id, + jobId: $model->customer_job_id, + title: $model->title, + description: $model->description, + status: $model->status, + dueOn: $model->due_on?->format('Y-m-d'), + estimatedHours: $model->estimated_hours === null ? null : rtrim(rtrim($model->estimated_hours, '0'), '.'), + workType: new NamedId($model->work_type_id, $workTypeNames[$model->work_type_id] ?? ''), + assignees: ($assignees->get($model->id) ?? collect()) + ->map(fn ($row): NamedId => new NamedId((int) $row->user_id, $userNames[(int) $row->user_id] ?? '')) + ->sortBy('name') + ->values() + ->all(), + ))->values()->all(); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php new file mode 100644 index 0000000..c9ef0e5 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php @@ -0,0 +1,66 @@ +where('customer_job_id', $jobId)->find($taskId); + + return $model === null ? null : $this->toEntity($model); + } + + public function save(Task $task): Task + { + $model = $task->id() === null ? new TaskModel : TaskModel::query()->findOrFail($task->id()); + + $model->fill([ + 'customer_job_id' => $task->jobId(), + 'work_type_id' => $task->workTypeId(), + 'title' => $task->title()->value, + 'description' => $task->description(), + 'status' => $task->status(), + 'due_on' => $task->dueOn()?->format('Y-m-d'), + 'estimated_hours' => $task->estimatedHours()?->value, + 'created_by' => $task->createdBy(), + ])->save(); + + DB::table('task_assignees')->where('task_id', $model->id)->whereNotIn('user_id', $task->assigneeUserIds())->delete(); + DB::table('task_assignees')->insertOrIgnore(array_map( + fn (int $userId): array => ['task_id' => $model->id, 'user_id' => $userId], + $task->assigneeUserIds(), + )); + + return $this->toEntity($model->refresh()); + } + + public function delete(Task $task): void + { + TaskModel::query()->whereKey($task->id())->delete(); + } + + private function toEntity(TaskModel $model): Task + { + return Task::reconstitute( + $model->id, + $model->customer_job_id, + $model->work_type_id, + 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), + $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, + ); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php index e7e72fc..2a97a9c 100644 --- a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php +++ b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php @@ -5,12 +5,16 @@ namespace App\Modules\Jobs\Infrastructure\Providers; use App\Models\User; use App\Modules\Customers\Application\Contracts\CustomerRowUsage; use App\Modules\Jobs\Application\Contracts\CustomerJobQueries; +use App\Modules\Jobs\Application\Contracts\TaskQueries; use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository; use App\Modules\Jobs\Domain\Contracts\JobNumberSequence; +use App\Modules\Jobs\Domain\Contracts\TaskRepository; use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs; use App\Modules\Jobs\Infrastructure\Persistence\DatabaseJobNumberSequence; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobRepository; +use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskQueries; +use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskRepository; use App\Modules\Users\Domain\Enums\Role; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; @@ -30,6 +34,8 @@ class JobsServiceProvider extends ServiceProvider CustomerJobQueries::class => EloquentCustomerJobQueries::class, JobNumberSequence::class => DatabaseJobNumberSequence::class, CustomerRowUsage::class => CustomerRowUsageFromJobs::class, + TaskRepository::class => EloquentTaskRepository::class, + TaskQueries::class => EloquentTaskQueries::class, ]; public function boot(): void @@ -55,6 +61,13 @@ class JobsServiceProvider extends ServiceProvider Gate::define('jobs.archive', $isManager); + // Adding, changing and removing tasks: everyone but subcontractors. + Gate::define('jobs.manage-tasks', fn (User $user, int $jobId): bool => $user->role !== Role::Subcontractor); + + // A subcontractor may change the status of tasks on the jobs they are attached to (spec 2.4). + Gate::define('jobs.update-task-status', fn (User $user, int $jobId): bool => $user->role !== Role::Subcontractor + || app(CustomerJobQueries::class)->isMember($jobId, $user->id)); + // "Lasku luotu" and "Laskutettu" are set when invoicing: management or the job's biller. // The argument is the job's biller (user id), when known. Gate::define('jobs.set-billing-status', fn (User $user, ?int $billerUserId = null): bool => $isManager($user) diff --git a/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php b/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php new file mode 100644 index 0000000..0e0e8ef --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php @@ -0,0 +1,109 @@ +value; + + public string $due_on = ''; + + public string $estimated_hours = ''; + + public string $description = ''; + + /** @var list */ + public array $assignee_user_ids = []; + + public function fillFromSummary(TaskSummary $task): void + { + $this->title = $task->title; + $this->work_type_id = (string) $task->workType->id; + $this->status = $task->status->value; + $this->due_on = $task->dueOn ?? ''; + $this->estimated_hours = $task->estimatedHours ?? ''; + $this->description = $task->description ?? ''; + $this->assignee_user_ids = array_map(fn (NamedId $user): string => (string) $user->id, $task->assignees); + } + + public function toData(): TaskData + { + $this->validate(); + + return new TaskData( + title: $this->title, + workTypeId: (int) $this->work_type_id, + status: $this->status, + description: trim($this->description) === '' ? null : $this->description, + 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), + ); + } + + public function showDomainError(DomainException $exception): void + { + [$field, $key] = match (true) { + $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 InvalidTaskReference => [$exception->field === 'work_type' ? 'work_type_id' : 'assignee_user_ids', 'jobs.errors.invalid_reference'], + default => throw $exception, + }; + + $this->addError($field, __($key)); + } + + /** + * @return array> + */ + protected function rules(): array + { + return [ + 'title' => ['required', 'string', 'max:255'], + 'work_type_id' => ['required', 'integer'], + 'status' => ['required', Rule::enum(TaskStatus::class)], + 'due_on' => ['nullable', 'date_format:Y-m-d'], + 'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'], + 'description' => ['nullable', 'string', 'max:10000'], + 'assignee_user_ids' => ['array'], + 'assignee_user_ids.*' => ['integer'], + ]; + } + + /** + * @return array + */ + protected function messages(): array + { + return [ + 'title.required' => __('jobs.tasks.errors.title_required'), + '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'), + 'estimated_hours.numeric' => __('jobs.errors.invalid_hours'), + 'estimated_hours.min' => __('jobs.errors.invalid_hours'), + 'estimated_hours.max' => __('jobs.errors.invalid_hours'), + 'description.max' => __('jobs.errors.too_long', ['max' => 10000]), + ]; + } +} diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index 14182cf..c13cb32 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -4,9 +4,16 @@ use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Customers\Application\Contracts\CustomerQueries; use App\Modules\Jobs\Application\Contracts\CustomerJobQueries; use App\Modules\Jobs\Application\DTOs\CustomerJobDetails; +use App\Modules\Jobs\Application\Contracts\TaskQueries; use App\Modules\Jobs\Application\DTOs\JobChangeEntry; +use App\Modules\Jobs\Application\DTOs\TaskSummary; +use App\Modules\Jobs\Application\UseCases\ChangeTaskStatus; +use App\Modules\Jobs\Application\UseCases\RemoveTask; +use App\Modules\Jobs\Domain\Enums\TaskStatus; +use App\Modules\Jobs\Domain\Exceptions\TaskNotFound; use App\Modules\Users\Application\Contracts\UserAccountQueries; use Carbon\CarbonImmutable; +use Illuminate\Support\Facades\Gate; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; use Livewire\Component; @@ -19,6 +26,17 @@ new class extends Component #[Locked] public int $jobId; + /** + * The task the remove dialog asks about. + */ + #[Locked] + public ?int $removalTaskId = null; + + #[Locked] + public string $removalTaskTitle = ''; + + public string $taskStatusMessage = ''; + public function mount(CustomerJobQueries $jobQueries, int $job): void { $this->authorize('jobs.view'); @@ -45,6 +63,82 @@ new class extends Component return app(CustomerJobQueries::class)->changes($this->jobId); } + /** + * @return list + */ + #[Computed] + public function tasks(): array + { + return app(TaskQueries::class)->tasksOf($this->jobId); + } + + public function changeTaskStatus(int $taskId, string $status, ChangeTaskStatus $changeStatus): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + + $newStatus = TaskStatus::tryFrom($status); + $task = app(TaskQueries::class)->findTask($this->jobId, $taskId); + + if ($newStatus === null || $task === null) { + $this->taskStatusMessage = __('jobs.tasks.not_found'); + + return; + } + + try { + $changeStatus->execute($this->jobId, $taskId, $newStatus); + } catch (TaskNotFound) { + $this->taskStatusMessage = __('jobs.tasks.not_found'); + + return; + } + + unset($this->tasks); + $this->taskStatusMessage = __('jobs.tasks.status_changed', ['title' => $task->title, 'status' => __('jobs.tasks.statuses.'.$newStatus->value)]); + + // The list is re-ordered (done tasks last): keep focus on the same select. + $this->js("document.getElementById('task-status-{$taskId}')?.focus()"); + } + + public function confirmTaskRemoval(int $taskId): void + { + $this->authorize('jobs.manage-tasks', $this->jobId); + + $task = app(TaskQueries::class)->findTask($this->jobId, $taskId); + + if ($task === null) { + $this->taskStatusMessage = __('jobs.tasks.not_found'); + + return; + } + + $this->removalTaskId = $task->id; + $this->removalTaskTitle = $task->title; + + $this->js("document.getElementById('remove-task-dialog').showModal()"); + } + + public function removeTask(RemoveTask $removeTask): void + { + $this->authorize('jobs.manage-tasks', $this->jobId); + + if ($this->removalTaskId === null) { + return; + } + + try { + $removeTask->execute($this->jobId, $this->removalTaskId); + $this->taskStatusMessage = __('jobs.tasks.removed', ['title' => $this->removalTaskTitle]); + } catch (TaskNotFound) { + $this->taskStatusMessage = __('jobs.tasks.not_found'); + } + + unset($this->tasks); + $this->reset('removalTaskId', 'removalTaskTitle'); + + $this->js("document.getElementById('remove-task-dialog').close(); document.getElementById('tasks-heading').focus()"); + } + public function formatDate(?string $date): string { return $date === null ? __('jobs.not_set') : CarbonImmutable::parse($date)->format('j.n.Y'); @@ -188,6 +282,113 @@ new class extends Component +
+
+

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

+ + @can('jobs.manage-tasks', $job->id) + @if ($job->status->allowsTasks()) + + @endif + @endcan +
+ + @can('jobs.manage-tasks', $job->id) + @unless ($job->status->allowsTasks()) +

{{ __('jobs.tasks.not_allowed_yet') }}

+ @endunless + @endcan + +

{{ $taskStatusMessage }}

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

{{ __('jobs.tasks.empty') }}

+ @else + @php($canChangeStatus = Gate::allows('jobs.update-task-status', $job->id)) + @php($canManageTasks = Gate::allows('jobs.manage-tasks', $job->id)) + +
    + @foreach ($this->tasks as $task) +
  • +
    +
    +

    {{ $task->title }}

    + {{ __('jobs.tasks.statuses.'.$task->status->value) }} +
    + +
    +
    {{ __('jobs.tasks.fields.work_type') }}
    +
    {{ $task->workType->name }}
    +
    {{ __('jobs.tasks.fields.assignees') }}
    +
    {{ $task->assignees === [] ? __('jobs.not_set') : collect($task->assignees)->pluck('name')->join(', ') }}
    +
    {{ __('jobs.tasks.fields.due_on') }}
    +
    +
    {{ __('jobs.tasks.fields.estimated_hours') }}
    +
    {{ $task->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $task->estimatedHours).' h' }}
    +
    + + @if ($task->description !== null) +

    {{ $task->description }}

    + @endif + +
    + @if ($canChangeStatus) +
    + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + @foreach (TaskStatus::cases() as $status) + + @endforeach + +
    + @endif + + @if ($canManageTasks) + + + @endif +
    +
    +
  • + @endforeach +
+ @endif + + +

+ @if ($removalTaskId !== null) + {{ __('jobs.tasks.remove_question', ['title' => $removalTaskTitle]) }} + @endif +

+ + + + +
+
+
diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php new file mode 100644 index 0000000..683d48e --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php @@ -0,0 +1,218 @@ + */ + #[Locked] + public array $serviceUnitIds = []; + + /** + * The task's work type when editing, offered even if taken out of use. + */ + #[Locked] + public ?int $storedWorkTypeId = null; + + public TaskForm $form; + + public function mount(CustomerJobQueries $jobQueries, TaskQueries $taskQueries, int $job, ?int $task = null): void + { + $details = $jobQueries->findDetails($job); + + abort_if($details === null, 404); + + $this->authorize('jobs.manage-tasks', $details->id); + + $this->jobId = $details->id; + $this->jobTitle = $details->number.' '.$details->name; + $this->serviceUnitIds = array_map(fn (NamedId $unit): int => $unit->id, $details->serviceUnits); + + if ($task === null) { + abort_unless($details->status->allowsTasks(), 404); + $this->form->assignee_user_ids = [(string) auth()->id()]; + + return; + } + + $summary = $taskQueries->findTask($details->id, $task); + + abort_if($summary === null, 404); + + $this->taskId = $summary->id; + $this->storedWorkTypeId = $summary->workType->id; + $this->form->fillFromSummary($summary); + } + + /** + * Work types of the job's service units and the shared ones, grouped + * as "Unit – Service" for . + * + * @return array> + */ + #[Computed] + public function workTypeGroups(): array + { + $catalog = app(CatalogQueries::class); + $groups = []; + $seen = []; + + foreach ($catalog->activeWorkTypesFor($this->serviceUnitIds) as $node) { + if ($node->workTypes !== []) { + $groups[$node->serviceUnit->name] = array_map(fn ($workType): array => ['id' => $workType->id, 'name' => $workType->name], $node->workTypes); + } + + foreach ($node->services as $serviceNode) { + if ($serviceNode->workTypes !== []) { + $groups[$node->serviceUnit->name.' – '.$serviceNode->service->name] = array_map(fn ($workType): array => ['id' => $workType->id, 'name' => $workType->name], $serviceNode->workTypes); + } + } + } + + foreach ($groups as $group) { + foreach ($group as $workType) { + $seen[$workType['id']] = true; + } + } + + if ($this->storedWorkTypeId !== null && ! isset($seen[$this->storedWorkTypeId]) && ($stored = $catalog->findWorkType($this->storedWorkTypeId)) !== null) { + $groups[__('catalog.inactive')] = [['id' => $stored->id, 'name' => $stored->name]]; + } + + return $groups; + } + + /** + * @return list + */ + #[Computed] + public function userOptions(): array + { + return array_map(fn ($user): array => [ + 'value' => $user->id, + 'label' => $user->name, + 'note' => $user->role === Role::Subcontractor ? __('users.roles.subcontractor') : null, + ], app(UserAccountQueries::class)->activeUserOptions()); + } + + public function save(AddTask $addTask, UpdateTask $updateTask): void + { + $this->authorize('jobs.manage-tasks', $this->jobId); + + $data = $this->form->toData(); + + try { + if ($this->taskId === null) { + $addTask->execute($this->jobId, $data, (int) auth()->id()); + session()->flash('status', __('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)])); + } + } catch (CustomerJobNotFound|TaskNotFound) { + abort(404); + } catch (DomainException $exception) { + $this->form->showDomainError($exception); + + return; + } + + $this->redirect(route('jobs.show', $this->jobId).'#tasks', navigate: true); + } + + public function heading(): string + { + return __($this->taskId === null ? 'jobs.tasks.create_title' : 'jobs.tasks.edit_title'); + } + + public function render(): mixed + { + return $this->view()->title($this->heading().' – '.$this->jobTitle); + } +}; +?> + +
+
+

{{ $this->heading() }}

+

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

+
+ +
+ + + {{-- 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 + + + + +
+ + @foreach (TaskStatus::cases() as $status) + + @endforeach + + + + + +
+ + + +
+ + +
+ +
diff --git a/app/Modules/Jobs/Presentation/Routes/web.php b/app/Modules/Jobs/Presentation/Routes/web.php index 3a40c8b..9f67ef5 100644 --- a/app/Modules/Jobs/Presentation/Routes/web.php +++ b/app/Modules/Jobs/Presentation/Routes/web.php @@ -12,4 +12,6 @@ Route::middleware(['web', 'auth', 'can:jobs.view']) Route::livewire('/board', 'jobs::board')->name('board'); 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/{task}/edit', 'jobs::task-form')->whereNumber(['job', 'task'])->name('tasks.edit'); }); diff --git a/database/factories/TaskFactory.php b/database/factories/TaskFactory.php new file mode 100644 index 0000000..f679104 --- /dev/null +++ b/database/factories/TaskFactory.php @@ -0,0 +1,43 @@ + + */ +class TaskFactory extends Factory +{ + protected $model = TaskModel::class; + + /** + * @return array + */ + public function definition(): array + { + return [ + 'customer_job_id' => CustomerJobModel::factory()->state(['status' => 'order']), + 'work_type_id' => fn () => WorkTypeModel::query()->value('id') ?? WorkTypeModel::factory()->create()->id, + 'title' => fake()->sentence(3), + 'status' => TaskStatus::Waiting, + 'created_by' => User::factory(), + ]; + } + + /** + * @param list $userIds + */ + public function assignedTo(array $userIds): static + { + return $this->afterCreating(function (TaskModel $task) use ($userIds): void { + DB::table('task_assignees')->insert(array_map(fn (int $userId): array => ['task_id' => $task->id, 'user_id' => $userId], $userIds)); + }); + } +} diff --git a/database/migrations/2026_11_23_171915_create_tasks_tables.php b/database/migrations/2026_11_23_171915_create_tasks_tables.php new file mode 100644 index 0000000..d34128b --- /dev/null +++ b/database/migrations/2026_11_23_171915_create_tasks_tables.php @@ -0,0 +1,45 @@ +id(); + $table->foreignId('customer_job_id')->constrained()->cascadeOnDelete(); + $table->foreignId('work_type_id')->constrained()->restrictOnDelete(); + $table->string('title'); + $table->text('description')->nullable(); + $table->string('status', 20); + $table->date('due_on')->nullable(); + $table->decimal('estimated_hours', 7, 2)->nullable(); + $table->foreignId('created_by')->constrained('users')->restrictOnDelete(); + $table->timestamps(); + + $table->index(['customer_job_id', 'status']); + }); + + Schema::create('task_assignees', function (Blueprint $table) { + $table->foreignId('task_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->constrained()->restrictOnDelete(); + $table->primary(['task_id', 'user_id']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('task_assignees'); + Schema::dropIfExists('tasks'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 832f64e..e5c62e4 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -337,8 +337,8 @@ 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`, `sort_order`, `created_by` -- `task_assignees`: `task_id`, `user_id` +- `tasks`: `customer_job_id`, `work_type_id`, `title`, `description`, `status`, `due_on`, `estimated_hours`, `created_by` *(olemassa)* +- `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` @@ -421,8 +421,9 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t - Sarakkeet tiloittain, arkistoitu pois. Kortin tila vaihdetaan vetämällä tai kortin valikosta (näppäimistö). Muutos ilmoitetaan `aria-live`-alueella. - Puhelimella sarakkeet allekkain tai yksi sarake kerrallaan, ei vaakavieritystä sivulla. -### 16.7 Tehtävät -- Tehtäviä voi lisätä työlle tarjouspyyntö-tilasta alkaen. Tehtävälle valitaan työtehtävä työn palveluyksiköistä. +### 16.7 Tehtävät *(valmis)* +- Tehtäviä voi lisätä työlle tarjouspyyntö-tilasta alkaen (ei arkistoidulle työlle). Tehtävälle valitaan työtehtävä työn palveluyksiköistä tai kaikille yhteisistä; tekijöiksi oletuksena lisääjä. +- Tehtävät näkyvät työn sivulla: avoimet määräpäivän mukaan, valmiit viimeisenä. Tilan voi vaihtaa suoraan listalta (myös alihankkija liitettyjen töidensä tehtävissä); lisäys, muokkaus ja poisto ovat muille kuin alihankkijoille. Poisto vahvistetaan dialogissa, ja se estetään tuntikirjauksen osassa, jos tehtävällä on kirjauksia. - Tehtävän tila: odottaa, työn alla, tarkastettavana, valmis. Myöhässä oleva tehtävä näytetään tekstillä ja kuvakkeella. ### 16.8 Tuntikirjaus diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index 36ab589..15163f1 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -14,6 +14,46 @@ return [ 'late' => 'Myöhässä', 'opens_in_new_tab' => 'avautuu uuteen välilehteen', + 'tasks' => [ + 'title' => 'Tehtävät', + 'new' => 'Lisää tehtävä', + 'create_title' => 'Uusi tehtävä', + 'edit_title' => 'Muokkaa tehtävää', + 'job_label' => 'Asiakastyö', + 'empty' => 'Ei tehtäviä.', + 'not_allowed_yet' => 'Tehtäviä voi lisätä, kun työ on tarjouspyyntö-tilassa tai myöhemmässä tilassa.', + 'created' => 'Tehtävä :title lisätty.', + 'updated' => 'Tehtävä :title tallennettu.', + 'removed' => 'Tehtävä :title poistettu.', + 'not_found' => 'Tehtävää ei löytynyt. Päivitä sivu.', + 'status_of' => 'Tila: :title', + 'status_changed' => 'Tehtävän :title tila on nyt :status.', + 'edit_named' => 'Muokkaa tehtävää :title', + 'remove_named' => 'Poista tehtävä :title', + 'remove_question' => 'Poistetaanko tehtävä :title? Poistoa ei voi perua.', + 'fields' => [ + 'title' => 'Nimi', + 'work_type' => 'Työtehtävä', + 'work_type_description' => 'Työn palveluyksiköiden ja kaikille yhteiset työtehtävät.', + 'assignees' => 'Tekijät', + 'status' => 'Tila', + 'due_on' => 'Määräpäivä', + 'estimated_hours' => 'Arvioitu aika (h)', + 'description' => 'Kuvaus', + ], + 'statuses' => [ + 'waiting' => 'Odottaa', + 'in_progress' => 'Työn alla', + 'in_review' => 'Tarkastettavana', + 'done' => 'Valmis', + ], + 'errors' => [ + 'title_required' => 'Anna tehtävän nimi.', + 'invalid_title' => 'Nimen pituus voi olla enintään 255 merkkiä.', + 'work_type_required' => 'Valitse työtehtävä.', + ], + ], + 'board' => [ 'title' => 'Kanban', 'link' => 'Näytä Kanban-näkymänä', diff --git a/tests/Browser/JobsAccessibilityTest.php b/tests/Browser/JobsAccessibilityTest.php index c4f3478..40e78a9 100644 --- a/tests/Browser/JobsAccessibilityTest.php +++ b/tests/Browser/JobsAccessibilityTest.php @@ -2,8 +2,10 @@ use App\Models\User; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel; +use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel; +use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\DB; @@ -145,3 +147,47 @@ it('moves a card by dragging it to another column', function () { expect($this->job->fresh()->status->value)->toBe('order'); }); + +it('has no accessibility issues on a job with tasks and on the task form', function (string $page, string $device, string $colorScheme) { + $this->job->update(['status' => 'order']); + $workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole(); + $task = TaskModel::factory() + ->assignedTo([$this->user->id]) + ->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Kuvauspäivä', 'due_on' => now()->subDay()->toDateString(), 'estimated_hours' => 6]); + + $url = match ($page) { + 'job page' => route('jobs.show', $this->job->id), + 'new task' => route('jobs.tasks.create', $this->job->id), + 'edit task' => route('jobs.tasks.edit', [$this->job->id, $task->id]), + }; + + $visit = visit($url); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2); +})->with(['job page', 'new task', 'edit task'])->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); + +it('changes a task status and removes a task with the keyboard', function () { + $this->job->update(['status' => 'order']); + $workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole(); + $task = TaskModel::factory() + ->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Kuvauspäivä']); + + visit(route('jobs.show', $this->job->id)) + ->select('#task-status-'.$task->id, 'in_progress') + ->assertSee('Tehtävän Kuvauspäivä tila on nyt Työn alla.') + ->assertScript('document.activeElement.id', 'task-status-'.$task->id) + ->keys('[aria-label="Poista tehtävä Kuvauspäivä"]', 'Enter') + ->assertScript('document.getElementById("remove-task-dialog").open', true) + ->assertScript('document.getElementById("remove-task-dialog").contains(document.activeElement)', true) + ->click('#remove-task-dialog [wire\\:click="removeTask"]') + ->assertSee('Tehtävä Kuvauspäivä poistettu.') + ->assertScript('document.activeElement.id', 'tasks-heading'); +}); diff --git a/tests/Fakes/FakeCatalogQueries.php b/tests/Fakes/FakeCatalogQueries.php index 835c6d2..4a582bb 100644 --- a/tests/Fakes/FakeCatalogQueries.php +++ b/tests/Fakes/FakeCatalogQueries.php @@ -4,6 +4,7 @@ namespace Tests\Fakes; use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Catalog\Application\DTOs\ServiceSummary; +use App\Modules\Catalog\Application\DTOs\ServiceUnitNode; use App\Modules\Catalog\Application\DTOs\ServiceUnitSummary; use App\Modules\Catalog\Application\DTOs\WorkTypeSummary; @@ -15,6 +16,14 @@ class FakeCatalogQueries implements CatalogQueries /** @var array */ public array $serviceUnits = []; + /** @var array> active work types directly under each unit */ + public array $workTypes = []; + + public function addWorkType(int $id, int $serviceUnitId, string $name): void + { + $this->workTypes[$serviceUnitId][] = new WorkTypeSummary($id, $serviceUnitId, null, $name, true); + } + public function addServiceUnit(int $id, string $name, bool $active = true, bool $shared = false): void { $this->serviceUnits[$id] = new ServiceUnitSummary($id, $name, $shared, $active); @@ -32,7 +41,15 @@ class FakeCatalogQueries implements CatalogQueries public function activeWorkTypesFor(array $serviceUnitIds): array { - return []; + $nodes = []; + + foreach ($this->serviceUnits as $id => $unit) { + if ($unit->isActive && (in_array($id, $serviceUnitIds, true) || $unit->isShared)) { + $nodes[] = new ServiceUnitNode($unit, [], $this->workTypes[$id] ?? []); + } + } + + return $nodes; } public function findServiceUnit(int $id): ?ServiceUnitSummary diff --git a/tests/Fakes/InMemoryTaskRepository.php b/tests/Fakes/InMemoryTaskRepository.php new file mode 100644 index 0000000..007ae0c --- /dev/null +++ b/tests/Fakes/InMemoryTaskRepository.php @@ -0,0 +1,45 @@ + */ + public array $tasks = []; + + private int $nextId = 1; + + public function findForJob(int $jobId, int $taskId): ?Task + { + $task = $this->tasks[$taskId] ?? null; + + return $task !== null && $task->jobId() === $jobId ? clone $task : null; + } + + public function save(Task $task): Task + { + $id = $task->id() ?? $this->nextId++; + $this->tasks[$id] = Task::reconstitute( + $id, + $task->jobId(), + $task->workTypeId(), + $task->title(), + $task->description(), + $task->status(), + $task->dueOn(), + $task->estimatedHours(), + $task->assigneeUserIds(), + $task->createdBy(), + ); + + return clone $this->tasks[$id]; + } + + public function delete(Task $task): void + { + unset($this->tasks[$task->id()]); + } +} diff --git a/tests/Feature/Modules/Jobs/TasksTest.php b/tests/Feature/Modules/Jobs/TasksTest.php new file mode 100644 index 0000000..61eaf92 --- /dev/null +++ b/tests/Feature/Modules/Jobs/TasksTest.php @@ -0,0 +1,119 @@ +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(); +}); + +it('adds a task with work types of the job and the shared ones on offer', function () { + $this->get(route('jobs.tasks.create', $this->job->id)) + ->assertOk() + ->assertSee('graafinen työ') + ->assertSee('suunnittelu') + ->assertDontSee('painotyö'); + + Livewire::test('jobs::task-form', ['job' => $this->job->id]) + ->assertSet('form.assignee_user_ids', [(string) $this->employee->id]) + ->set('form.title', 'Mainoskuvat') + ->set('form.work_type_id', (string) $this->graphic->id) + ->set('form.due_on', '2026-05-20') + ->call('save') + ->assertHasNoErrors() + ->assertRedirect(route('jobs.show', $this->job->id).'#tasks'); + + $task = TaskModel::query()->sole(); + expect($task->work_type_id)->toBe($this->graphic->id) + ->and(DB::table('task_assignees')->where('task_id', $task->id)->pluck('user_id')->all())->toBe([$this->employee->id]); + + $this->get(route('jobs.show', $this->job->id)) + ->assertSee('Mainoskuvat') + ->assertSee('graafinen työ') + ->assertSee('Eero Työntekijä'); +}); + +it('shows Finnish errors on the task form', function () { + Livewire::test('jobs::task-form', ['job' => $this->job->id]) + ->call('save') + ->assertHasErrors(['form.title', 'form.work_type_id']) + ->assertSee('Anna tehtävän nimi.') + ->assertSee('Valitse työtehtävä.'); +}); + +it('does not add tasks before the job is a quote request', function () { + $this->job->update(['status' => 'tentative']); + + $this->get(route('jobs.tasks.create', $this->job->id))->assertNotFound(); + $this->get(route('jobs.show', $this->job->id)) + ->assertSee('Tehtäviä voi lisätä, kun työ on tarjouspyyntö-tilassa') + ->assertDontSee('Lisää tehtävä'); +}); + +it('edits, changes the status of and removes a task on the job page', function () { + $task = TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Mainoskuvat']); + + Livewire::test('jobs::task-form', ['job' => $this->job->id, 'task' => $task->id]) + ->assertSet('form.title', 'Mainoskuvat') + ->set('form.work_type_id', (string) $this->planning->id) + ->call('save') + ->assertHasNoErrors(); + + Livewire::test('jobs::show', ['job' => $this->job->id]) + ->call('changeTaskStatus', $task->id, 'in_review') + ->assertSee('Tehtävän Mainoskuvat tila on nyt Tarkastettavana.') + ->call('confirmTaskRemoval', $task->id) + ->assertSee('Poistetaanko tehtävä Mainoskuvat?') + ->call('removeTask') + ->assertSee('Tehtävä Mainoskuvat poistettu.'); + + expect(TaskModel::query()->count())->toBe(0); +}); + +it('counts task assignees as members in my jobs', function () { + $colleague = User::factory()->create(); + TaskModel::factory()->assignedTo([$colleague->id])->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id]); + + $this->actingAs($colleague); + + Livewire::test('jobs::index')->assertSee('Kampanja'); +}); + +it('lets a subcontractor change task statuses on their jobs, but not add or change tasks', function () { + $subcontractor = User::factory()->subcontractor()->create(); + $task = TaskModel::factory()->assignedTo([$subcontractor->id])->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id]); + + $this->actingAs($subcontractor); + + $this->get(route('jobs.show', $this->job->id))->assertOk()->assertDontSee('Lisää tehtävä'); + $this->get(route('jobs.tasks.create', $this->job->id))->assertForbidden(); + $this->get(route('jobs.tasks.edit', [$this->job->id, $task->id]))->assertForbidden(); + + Livewire::test('jobs::show', ['job' => $this->job->id]) + ->call('changeTaskStatus', $task->id, 'done') + ->assertHasNoErrors() + ->call('confirmTaskRemoval', $task->id) + ->assertForbidden(); + + expect($task->fresh()->status->value)->toBe('done'); +}); + +it('returns 404 for a task of another job', function () { + $other = TaskModel::factory()->create(); + + $this->get(route('jobs.tasks.edit', [$this->job->id, $other->id]))->assertNotFound(); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php new file mode 100644 index 0000000..980472f --- /dev/null +++ b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php @@ -0,0 +1,125 @@ +jobs = new InMemoryCustomerJobRepository; + $this->tasks = new InMemoryTaskRepository; + $customers = new FakeCustomerQueries; + $this->catalog = new FakeCatalogQueries; + $this->users = new FakeUserAccountQueries; + $transactions = new FakeTransactionManager; + + $customers->customers = [1 => 'Mainos Oy']; + $this->catalog->addServiceUnit(1, 'Markkinointi'); + $this->catalog->addServiceUnit(2, 'Painotuotanto'); + $this->catalog->addServiceUnit(9, 'Kaikille yhteiset', shared: true); + $this->catalog->addWorkType(11, 1, 'graafinen työ'); + $this->catalog->addWorkType(21, 2, 'painotyö'); + $this->catalog->addWorkType(91, 9, 'suunnittelu'); + $this->users->addUser(10, 'Eero'); + $this->users->addUser(12, 'Pois', active: false); + + $createJob = new CreateCustomerJob($this->jobs, $this->jobs, new JobDetailsFactory($customers, $this->catalog, $this->users), $transactions, new FakeClock(new DateTimeImmutable('2026-05-01'))); + $this->jobId = $createJob->execute(new CustomerJobData('Kampanja', 1, [1], 10, 'one_off', 'quote_request', 'normal'), 10); + $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->changeTaskStatus = new ChangeTaskStatus($this->tasks, $transactions); + $this->removeTask = new RemoveTask($this->tasks, $transactions); + $this->changeJobStatus = new ChangeJobStatus($this->jobs, $transactions); +}); + +it('allows tasks from a quote request on, not before and not when archived', function () { + expect(JobStatus::Tentative->allowsTasks())->toBeFalse() + ->and(JobStatus::Prospect->allowsTasks())->toBeFalse() + ->and(JobStatus::Archived->allowsTasks())->toBeFalse() + ->and(JobStatus::QuoteRequest->allowsTasks())->toBeTrue() + ->and(JobStatus::Billed->allowsTasks())->toBeTrue() + ->and(fn () => new TaskTitle(' '))->toThrow(InvalidTaskTitle::class); + + expect(fn () => $this->addTask->execute($this->tentativeJobId, new TaskData('Luonnos', 11, 'waiting'), 10)) + ->toThrow(TasksNotAllowedYet::class); +}); + +it('adds a task with a work type of the job or a shared one', function () { + $taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting', dueOn: '2026-05-20', estimatedHours: '3,5', assigneeUserIds: [10]), 10); + $this->addTask->execute($this->jobId, new TaskData('Suunnittelupalaveri', 91, 'waiting'), 10); + + $task = $this->tasks->findForJob($this->jobId, $taskId); + + expect($task?->dueOn()?->format('Y-m-d'))->toBe('2026-05-20') + ->and($task?->estimatedHours()?->format())->toBe('3.5') + ->and($task?->assigneeUserIds())->toBe([10]) + ->and($this->tasks->tasks)->toHaveCount(2); +}); + +it('rejects a work type of another unit and an inactive assignee', function (int $workTypeId, array $assignees, string $field) { + try { + $this->addTask->execute($this->jobId, new TaskData('Työ', $workTypeId, 'waiting', assigneeUserIds: $assignees), 10); + $this->fail('No exception'); + } catch (InvalidTaskReference $exception) { + expect($exception->field)->toBe($field); + } +})->with([ + 'work type of another unit' => [21, [], 'work_type'], + 'inactive assignee' => [11, [12], 'assignees'], +]); + +it('changes, moves through statuses and removes a task', function () { + $taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10); + + $this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat ja banneri', 11, 'in_progress')); + $this->changeTaskStatus->execute($this->jobId, $taskId, TaskStatus::Done); + + $task = $this->tasks->findForJob($this->jobId, $taskId); + expect($task?->title()->value)->toBe('Mainoskuvat ja banneri') + ->and($task?->status())->toBe(TaskStatus::Done); + + $this->removeTask->execute($this->jobId, $taskId); + expect($this->tasks->tasks)->toBeEmpty(); +}); + +it('can still change a task after the job moved back to an earlier status', function () { + $taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10); + $this->changeJobStatus->execute($this->jobId, JobStatus::Tentative, 10); + + $this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat', 11, 'in_review')); + + expect($this->tasks->findForJob($this->jobId, $taskId)?->status())->toBe(TaskStatus::InReview); +}); + +it('does not touch a task of another job', function (string $action) { + $taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10); + + match ($action) { + 'update' => $this->updateTask->execute($this->tentativeJobId, $taskId, new TaskData('X', 11, 'done')), + 'status' => $this->changeTaskStatus->execute($this->tentativeJobId, $taskId, TaskStatus::Done), + 'remove' => $this->removeTask->execute($this->tentativeJobId, $taskId), + }; +})->throws(TaskNotFound::class)->with(['update', 'status', 'remove']);