From 4fb8ea1c5f7fa23db101f4e9ad245284a5499c3a Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Wed, 25 Nov 2026 07:31:53 +0200 Subject: [PATCH] Add comments to tasks Everyone who may change a task's status (attached subcontractors too) comments on it on the job page. Authors edit and remove their own comments; admin and management may remove anyone's (jobs.remove-any-task-comment). Edited comments show when they were edited, and task cards show the number of comments. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 4 +- .../Contracts/TaskCommentQueries.php | 18 + .../Application/DTOs/TaskCommentSummary.php | 21 + .../Jobs/Application/DTOs/TaskSummary.php | 1 + .../Services/TaskCommentFinder.php | 44 +++ .../Application/UseCases/AddTaskComment.php | 44 +++ .../Application/UseCases/EditTaskComment.php | 46 +++ .../UseCases/RemoveTaskComment.php | 40 ++ .../Contracts/TaskCommentRepository.php | 19 + .../Jobs/Domain/Entities/TaskComment.php | 110 ++++++ .../Exceptions/InvalidTaskCommentBody.php | 15 + .../Exceptions/NotTaskCommentAuthor.php | 19 + .../Domain/Exceptions/TaskCommentNotFound.php | 18 + .../Domain/ValueObjects/TaskCommentBody.php | 32 ++ .../Persistence/Eloquent/TaskCommentModel.php | 38 ++ .../EloquentTaskCommentQueries.php | 44 +++ .../EloquentTaskCommentRepository.php | 51 +++ .../Repositories/EloquentTaskQueries.php | 6 + .../Providers/JobsServiceProvider.php | 10 + .../Presentation/Livewire/⚡show.blade.php | 18 + .../Livewire/⚡task-comments.blade.php | 365 ++++++++++++++++++ ...1_25_052338_create_task_comments_table.php | 34 ++ docs/maarittely.md | 4 +- lang/en/jobs.php | 28 ++ lang/fi/jobs.php | 28 ++ tests/Browser/JobsAccessibilityTest.php | 36 ++ tests/Fakes/InMemoryTaskCommentRepository.php | 34 ++ .../Feature/Modules/Jobs/TaskCommentsTest.php | 148 +++++++ .../Application/TaskCommentUseCasesTest.php | 83 ++++ 29 files changed, 1354 insertions(+), 4 deletions(-) create mode 100644 app/Modules/Jobs/Application/Contracts/TaskCommentQueries.php create mode 100644 app/Modules/Jobs/Application/DTOs/TaskCommentSummary.php create mode 100644 app/Modules/Jobs/Application/Services/TaskCommentFinder.php create mode 100644 app/Modules/Jobs/Application/UseCases/AddTaskComment.php create mode 100644 app/Modules/Jobs/Application/UseCases/EditTaskComment.php create mode 100644 app/Modules/Jobs/Application/UseCases/RemoveTaskComment.php create mode 100644 app/Modules/Jobs/Domain/Contracts/TaskCommentRepository.php create mode 100644 app/Modules/Jobs/Domain/Entities/TaskComment.php create mode 100644 app/Modules/Jobs/Domain/Exceptions/InvalidTaskCommentBody.php create mode 100644 app/Modules/Jobs/Domain/Exceptions/NotTaskCommentAuthor.php create mode 100644 app/Modules/Jobs/Domain/Exceptions/TaskCommentNotFound.php create mode 100644 app/Modules/Jobs/Domain/ValueObjects/TaskCommentBody.php create mode 100644 app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskCommentModel.php create mode 100644 app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCommentQueries.php create mode 100644 app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCommentRepository.php create mode 100644 app/Modules/Jobs/Presentation/Livewire/⚡task-comments.blade.php create mode 100644 database/migrations/2026_11_25_052338_create_task_comments_table.php create mode 100644 tests/Fakes/InMemoryTaskCommentRepository.php create mode 100644 tests/Feature/Modules/Jobs/TaskCommentsTest.php create mode 100644 tests/Unit/Modules/Jobs/Application/TaskCommentUseCasesTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 2ebd7b4..f3939a0 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; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); 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 with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, 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 (its running number `billing_exports.number` is reserved only when it is created, so discarded drafts leave no gaps, and a draft has none): 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, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); 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 with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, task comments (`jobs::task-comments`: anyone with `jobs.update-task-status` comments, authors edit and remove their own, `jobs.remove-any-task-comment` removes anyone's), and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, 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 (its running number `billing_exports.number` is reserved only when it is created, so discarded drafts leave no gaps, and a draft has none): 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 is in Finnish. The UI is in Finnish (default) and English: every UI string lives in `lang/fi/*.php` **and** `lang/en/*.php` with the same keys and placeholders (`tests/Unit/TranslationFilesTest.php` fails otherwise). Number, money and date formats stay Finnish in both languages; the quick sale receipt is always Finnish. @@ -23,7 +23,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`, `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]`. +- **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`, `jobs.remove-any-task-comment`, `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. - **Main menu**: the layout renders the groups of `App\View\MainMenu` (Työt, Oma kirjaus, Asiakkaat ja myynti, Hallinto, Ylläpito) as disclosure popovers (`resources/views/components/nav-group.blade.php`). A new page is added to `MainMenu::definition()` with the Gate ability of its route; groups with no allowed links disappear. - **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`). diff --git a/app/Modules/Jobs/Application/Contracts/TaskCommentQueries.php b/app/Modules/Jobs/Application/Contracts/TaskCommentQueries.php new file mode 100644 index 0000000..288dc49 --- /dev/null +++ b/app/Modules/Jobs/Application/Contracts/TaskCommentQueries.php @@ -0,0 +1,18 @@ + + */ + public function commentsOf(int $jobId, int $taskId): array; +} diff --git a/app/Modules/Jobs/Application/DTOs/TaskCommentSummary.php b/app/Modules/Jobs/Application/DTOs/TaskCommentSummary.php new file mode 100644 index 0000000..b9e892e --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/TaskCommentSummary.php @@ -0,0 +1,21 @@ +ensureTask($jobId, $taskId); + + return $this->comments->findForTask($taskId, $commentId) ?? throw new TaskCommentNotFound($taskId, $commentId); + } + + /** + * @throws TaskNotFound + */ + public function ensureTask(int $jobId, int $taskId): void + { + if ($this->tasks->findForJob($jobId, $taskId) === null) { + throw new TaskNotFound($jobId, $taskId); + } + } +} diff --git a/app/Modules/Jobs/Application/UseCases/AddTaskComment.php b/app/Modules/Jobs/Application/UseCases/AddTaskComment.php new file mode 100644 index 0000000..acb15e9 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/AddTaskComment.php @@ -0,0 +1,44 @@ +transactions->run(function () use ($jobId, $taskId, $userId, $body): int { + $this->finder->ensureTask($jobId, $taskId); + + return (int) $this->comments->save(TaskComment::create($taskId, $userId, $body, $this->clock->now()))->id(); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/EditTaskComment.php b/app/Modules/Jobs/Application/UseCases/EditTaskComment.php new file mode 100644 index 0000000..89be106 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/EditTaskComment.php @@ -0,0 +1,46 @@ +transactions->run(function () use ($jobId, $taskId, $commentId, $userId, $body): void { + $comment = $this->finder->find($jobId, $taskId, $commentId); + $comment->edit($userId, $body, $this->clock->now()); + + $this->comments->save($comment); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/RemoveTaskComment.php b/app/Modules/Jobs/Application/UseCases/RemoveTaskComment.php new file mode 100644 index 0000000..a9375db --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/RemoveTaskComment.php @@ -0,0 +1,40 @@ +transactions->run(function () use ($jobId, $taskId, $commentId, $userId, $mayRemoveOthers): void { + $comment = $this->finder->find($jobId, $taskId, $commentId); + $comment->ensureRemovableBy($userId, $mayRemoveOthers); + + $this->comments->delete($comment); + }); + } +} diff --git a/app/Modules/Jobs/Domain/Contracts/TaskCommentRepository.php b/app/Modules/Jobs/Domain/Contracts/TaskCommentRepository.php new file mode 100644 index 0000000..b33f417 --- /dev/null +++ b/app/Modules/Jobs/Domain/Contracts/TaskCommentRepository.php @@ -0,0 +1,19 @@ +ensureAuthor($userId); + + if ($body->value === $this->body->value) { + return; + } + + $this->body = $body; + $this->editedAt = $at; + } + + /** + * @throws NotTaskCommentAuthor + */ + public function ensureRemovableBy(int $userId, bool $mayRemoveOthers): void + { + if (! $mayRemoveOthers) { + $this->ensureAuthor($userId); + } + } + + public function isWrittenBy(int $userId): bool + { + return $this->authorId === $userId; + } + + public function id(): ?int + { + return $this->id; + } + + public function taskId(): int + { + return $this->taskId; + } + + public function authorId(): ?int + { + return $this->authorId; + } + + public function body(): TaskCommentBody + { + return $this->body; + } + + public function createdAt(): DateTimeImmutable + { + return $this->createdAt; + } + + public function editedAt(): ?DateTimeImmutable + { + return $this->editedAt; + } + + /** + * @throws NotTaskCommentAuthor + */ + private function ensureAuthor(int $userId): void + { + if (! $this->isWrittenBy($userId)) { + throw new NotTaskCommentAuthor((int) $this->id, $userId); + } + } +} diff --git a/app/Modules/Jobs/Domain/Exceptions/InvalidTaskCommentBody.php b/app/Modules/Jobs/Domain/Exceptions/InvalidTaskCommentBody.php new file mode 100644 index 0000000..87fa7b6 --- /dev/null +++ b/app/Modules/Jobs/Domain/Exceptions/InvalidTaskCommentBody.php @@ -0,0 +1,15 @@ + self::MAX_LENGTH) { + throw new InvalidTaskCommentBody; + } + + $this->value = $value; + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskCommentModel.php b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskCommentModel.php new file mode 100644 index 0000000..7fb409f --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskCommentModel.php @@ -0,0 +1,38 @@ + + */ + protected function casts(): array + { + return [ + 'task_id' => 'integer', + 'user_id' => 'integer', + 'edited_at' => 'immutable_datetime', + 'created_at' => 'immutable_datetime', + 'updated_at' => 'immutable_datetime', + ]; + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCommentQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCommentQueries.php new file mode 100644 index 0000000..c3c4be6 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCommentQueries.php @@ -0,0 +1,44 @@ +where('task_id', $taskId) + ->whereExists(fn ($query) => $query->selectRaw('1')->from('tasks') + ->whereColumn('tasks.id', 'task_comments.task_id') + ->where('tasks.customer_job_id', $jobId)) + ->orderBy('id') + ->get(); + + $names = $this->users->namesByIds($models->pluck('user_id')->filter()->unique()->values()->all()); + + return $models + ->map(fn (TaskCommentModel $model): TaskCommentSummary => new TaskCommentSummary( + $model->id, + $model->user_id, + $model->user_id === null ? '' : ($names[$model->user_id] ?? ''), + $model->body, + $this->localTime($model->created_at), + $model->edited_at === null ? null : $this->localTime($model->edited_at), + )) + ->values() + ->all(); + } + + private function localTime(CarbonImmutable $moment): string + { + return $moment->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCommentRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCommentRepository.php new file mode 100644 index 0000000..6ff8a6f --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCommentRepository.php @@ -0,0 +1,51 @@ +where('task_id', $taskId)->find($commentId); + + return $model === null ? null : $this->toEntity($model); + } + + public function save(TaskComment $comment): TaskComment + { + $model = $comment->id() === null ? new TaskCommentModel : TaskCommentModel::query()->findOrFail($comment->id()); + + $model->fill([ + 'task_id' => $comment->taskId(), + 'user_id' => $comment->authorId(), + 'body' => $comment->body()->value, + 'edited_at' => $comment->editedAt(), + 'created_at' => $comment->createdAt(), + ])->save(); + + return $this->toEntity($model->refresh()); + } + + public function delete(TaskComment $comment): void + { + TaskCommentModel::query()->whereKey($comment->id())->delete(); + } + + private function toEntity(TaskCommentModel $model): TaskComment + { + return TaskComment::reconstitute( + $model->id, + $model->task_id, + $model->user_id, + new TaskCommentBody($model->body), + DateTimeImmutable::createFromInterface($model->created_at), + $model->edited_at === null ? null : DateTimeImmutable::createFromInterface($model->edited_at), + ); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php index 595bcef..787bf1b 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php @@ -147,6 +147,11 @@ class EloquentTaskQueries implements TaskQueries $userNames = $this->users->namesByIds($members->flatten()->pluck('user_id') ->merge($models->pluck('assignee_user_id')->filter()) ->map(fn ($id): int => (int) $id)->unique()->values()->all()); + $commentCounts = DB::table('task_comments') + ->whereIn('task_id', $models->pluck('id')->all()) + ->groupBy('task_id') + ->selectRaw('task_id, count(*) as aggregate') + ->pluck('aggregate', 'task_id'); $workTypeNames = []; foreach ($models->pluck('work_type_id')->unique() as $workTypeId) { @@ -170,6 +175,7 @@ class EloquentTaskQueries implements TaskQueries ->all(), plannedFrom: $model->planned_from?->format('Y-m-d'), plannedTo: $model->planned_to?->format('Y-m-d'), + commentCount: (int) ($commentCounts[$model->id] ?? 0), ))->values()->all(); } } diff --git a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php index fb690be..a38fd62 100644 --- a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php +++ b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php @@ -8,12 +8,14 @@ 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\TaskCommentQueries; 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\TaskCommentRepository; use App\Modules\Jobs\Domain\Contracts\TaskRepository; use App\Modules\Jobs\Infrastructure\CustomerReferencesFromJobs; use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs; @@ -25,6 +27,8 @@ use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJob 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\EloquentTaskCommentQueries; +use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCommentRepository; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskRepository; use App\Modules\Users\Domain\Enums\Role; @@ -52,6 +56,8 @@ class JobsServiceProvider extends ServiceProvider TaskCalendarQueries::class => EloquentTaskCalendarQueries::class, ChecklistItemRepository::class => EloquentChecklistItemRepository::class, ChecklistQueries::class => EloquentChecklistQueries::class, + TaskCommentRepository::class => EloquentTaskCommentRepository::class, + TaskCommentQueries::class => EloquentTaskCommentQueries::class, // Replaced by the TimeTracking module, which knows which tasks have time entries. TaskUsage::class => NothingUsesTasks::class, ]; @@ -96,6 +102,10 @@ class JobsServiceProvider extends ServiceProvider Gate::define('jobs.update-task-status', fn (User $user, int $jobId): bool => $user->role !== Role::Subcontractor || app(CustomerJobQueries::class)->isMember($jobId, $user->id)); + // Commenting on tasks follows jobs.update-task-status (spec 2.4); authors edit and remove + // their own comments, and admin and management may remove anyone's. + Gate::define('jobs.remove-any-task-comment', $isManager); + // "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/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index 8c2e171..f1a7d08 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -18,6 +18,7 @@ use Illuminate\Support\Facades\Gate; use App\Modules\Shared\Domain\ValueObjects\Money; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; +use Livewire\Attributes\On; use Livewire\Component; /** @@ -79,6 +80,15 @@ new class extends Component return app(TaskQueries::class)->tasksOf($this->jobId); } + /** + * A task's comments changed: the task cards show their number. + */ + #[On('task-comments-changed')] + public function refreshTasks(): void + { + unset($this->tasks); + } + public function changeTaskStatus(int $taskId, string $status, ChangeTaskStatus $changeStatus): void { $this->authorize('jobs.update-task-status', $this->jobId); @@ -403,6 +413,12 @@ new class extends Component
{{ __('jobs.tasks.fields.status') }}:
{{ __('jobs.tasks.statuses.'.$task->status->value) }}
+ @if ($task->commentCount > 0) +
+
{{ __('jobs.tasks.comments.title') }}:
+
{{ $task->commentCount }}
+
+ @endif @@ -438,6 +454,8 @@ new class extends Component + +
@if ($canChangeStatus)
diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡task-comments.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡task-comments.blade.php new file mode 100644 index 0000000..766a190 --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡task-comments.blade.php @@ -0,0 +1,365 @@ +authorize('jobs.view-job', $jobId); + + $this->jobId = $jobId; + $this->taskId = $taskId; + $this->taskTitle = $taskTitle; + } + + /** + * @return list + */ + #[Computed] + public function comments(): array + { + return app(TaskCommentQueries::class)->commentsOf($this->jobId, $this->taskId); + } + + public function add(AddTaskComment $addComment): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + $this->resetErrorBag(); + + if (trim($this->newComment) === '') { + $this->addError('newComment', __('jobs.tasks.comments.errors.body_required')); + + return; + } + + try { + $addComment->execute($this->jobId, $this->taskId, (int) auth()->id(), $this->newComment); + } catch (InvalidTaskCommentBody) { + $this->addError('newComment', __('jobs.tasks.comments.errors.invalid_body')); + + return; + } catch (TaskNotFound) { + $this->notFound(); + + return; + } + + $this->reset('newComment'); + $this->changed(__('jobs.tasks.comments.added')); + } + + public function startEdit(int $commentId): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + + $comment = $this->comment($commentId); + + if ($comment === null) { + return; + } + + if (! $this->isOwn($comment)) { + $this->message = __('jobs.tasks.comments.errors.not_author'); + + return; + } + + $this->editingCommentId = $comment->id; + $this->editingBody = $comment->body; + $this->resetErrorBag(); + $this->js("document.getElementById('comment-edit-{$comment->id}')?.focus()"); + } + + public function saveEdit(EditTaskComment $editComment): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + $this->resetErrorBag(); + + if ($this->editingCommentId === null) { + return; + } + + if (trim($this->editingBody) === '') { + $this->addError('editingBody', __('jobs.tasks.comments.errors.body_required')); + + return; + } + + try { + $editComment->execute($this->jobId, $this->taskId, $this->editingCommentId, (int) auth()->id(), $this->editingBody); + } catch (InvalidTaskCommentBody) { + $this->addError('editingBody', __('jobs.tasks.comments.errors.invalid_body')); + + return; + } catch (NotTaskCommentAuthor) { + $this->cancelEdit(); + $this->message = __('jobs.tasks.comments.errors.not_author'); + + return; + } catch (TaskNotFound|TaskCommentNotFound) { + $this->reset('editingCommentId', 'editingBody'); + $this->notFound(); + + return; + } + + $this->cancelEdit(); + $this->changed(__('jobs.tasks.comments.saved')); + } + + public function cancelEdit(): void + { + $commentId = $this->editingCommentId; + + $this->reset('editingCommentId', 'editingBody'); + $this->resetErrorBag(); + + if ($commentId !== null) { + $this->js("document.getElementById('comment-edit-button-{$commentId}')?.focus()"); + } + } + + public function confirmRemoval(int $commentId): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + + $comment = $this->comment($commentId); + + if ($comment === null) { + return; + } + + if (! $this->mayRemove($comment)) { + $this->message = __('jobs.tasks.comments.errors.not_author'); + + return; + } + + $this->removalCommentId = $comment->id; + $this->js("document.getElementById('remove-comment-dialog-{$this->taskId}').showModal()"); + } + + public function remove(RemoveTaskComment $removeComment): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + + if ($this->removalCommentId === null) { + return; + } + + $commentId = $this->removalCommentId; + $this->reset('removalCommentId'); + $this->js("document.getElementById('remove-comment-dialog-{$this->taskId}').close()"); + + try { + $removeComment->execute($this->jobId, $this->taskId, $commentId, (int) auth()->id(), Gate::allows('jobs.remove-any-task-comment')); + } catch (NotTaskCommentAuthor) { + $this->message = __('jobs.tasks.comments.errors.not_author'); + + return; + } catch (TaskNotFound|TaskCommentNotFound) { + $this->notFound(); + + return; + } + + if ($this->editingCommentId === $commentId) { + $this->reset('editingCommentId', 'editingBody'); + } + + $this->changed(__('jobs.tasks.comments.removed')); + + // The removed comment's buttons are gone: move focus to the field for a new comment. + $this->js("document.getElementById('comment-new-{$this->taskId}')?.focus()"); + } + + public function isOwn(TaskCommentSummary $comment): bool + { + return $comment->authorId !== null && $comment->authorId === (int) auth()->id(); + } + + public function mayRemove(TaskCommentSummary $comment): bool + { + return $this->isOwn($comment) || Gate::allows('jobs.remove-any-task-comment'); + } + + /** + * "25.11.2026 klo 14.05" from "2026-11-25 14:05". + */ + public function formatTime(string $moment): string + { + $time = CarbonImmutable::createFromFormat('Y-m-d H:i', $moment); + + return __('jobs.tasks.comments.at', ['date' => $time->format('j.n.Y'), 'time' => $time->format('H.i')]); + } + + public function authorName(TaskCommentSummary $comment): string + { + return $comment->authorName === '' ? __('jobs.tasks.comments.unknown_author') : $comment->authorName; + } + + private function comment(int $commentId): ?TaskCommentSummary + { + foreach ($this->comments as $comment) { + if ($comment->id === $commentId) { + return $comment; + } + } + + $this->notFound(); + + return null; + } + + /** + * Refreshes the list and tells the job page, whose task cards show the + * number of comments. + */ + private function changed(string $message): void + { + unset($this->comments); + $this->message = $message; + $this->dispatch('task-comments-changed'); + } + + private function notFound(): void + { + $this->changed(__('jobs.tasks.comments.not_found')); + } +}; +?> + +{{-- Named by the task, so the comments of a job's tasks are distinguishable landmarks. --}} +
+ @php($canComment = Gate::allows('jobs.update-task-status', $jobId)) + +

+ {{ __('jobs.tasks.comments.title') }} + @if ($this->comments !== []) + ({{ count($this->comments) }}) + @endif +

+ +

{{ $message }}

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

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

+ @else +
    + @foreach ($this->comments as $comment) + @php($at = $this->formatTime($comment->createdAt)) + @php($named = ['author' => $this->authorName($comment), 'at' => $at]) +
  1. +

    + {{ $this->authorName($comment) }} + + + @if ($comment->editedAt !== null) + ({{ __('jobs.tasks.comments.edited', ['at' => $this->formatTime($comment->editedAt)]) }}) + @endif + +

    + + @if ($editingCommentId === $comment->id) +
    + +
    + + +
    + + @else +

    {{ $comment->body }}

    + + @if ($canComment && ($this->isOwn($comment) || $this->mayRemove($comment))) +
    + @if ($this->isOwn($comment)) + + @endif + +
    + @endif + @endif +
  2. + @endforeach +
+ @endif + + @if ($canComment) +
+ + + + + +

{{ __('jobs.tasks.comments.remove_question') }}

+ + + + +
+ @endif +
diff --git a/database/migrations/2026_11_25_052338_create_task_comments_table.php b/database/migrations/2026_11_25_052338_create_task_comments_table.php new file mode 100644 index 0000000..56137ee --- /dev/null +++ b/database/migrations/2026_11_25_052338_create_task_comments_table.php @@ -0,0 +1,34 @@ +id(); + $table->foreignId('task_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete(); + $table->text('body'); + $table->timestamp('edited_at')->nullable(); + $table->timestamps(); + + $table->index(['task_id', 'id']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('task_comments'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index c3f4443..9d85068 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -370,7 +370,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `task_bookings` *(V3, olemassa)*: `task_id`, `user_id`, `day`, `minutes` (tehtävän arvion varaus tekijän päivästä) - `task_members`: `task_id`, `user_id` (tehtävän jäsenet; tekijä on `tasks.assignee_user_id`) *(olemassa)* - `task_checklist_items` *(V3)*: `task_id`, `text`, `is_done`, `sort_order` -- `task_comments` *(V3)*: `task_id`, `user_id`, `body` +- `task_comments` *(V3, olemassa)*: `task_id`, `user_id`, `body`, `edited_at` (kirjoittaja muokkaa ja poistaa omiaan, pääkäyttäjä ja johto poistavat kenen tahansa) - `task_images` *(V3)*: `task_id`, `user_id`, `path`, `original_name` **TimeTracking** @@ -409,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** -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. +Tarkistuslistat *(valmis)*, kommentit *(valmis)*, 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. diff --git a/lang/en/jobs.php b/lang/en/jobs.php index e554ffc..0a5d75c 100644 --- a/lang/en/jobs.php +++ b/lang/en/jobs.php @@ -119,6 +119,34 @@ return [ 'invalid_text' => 'The item text may be at most 255 characters.', ], ], + 'comments' => [ + 'title' => 'Comments', + 'list_of' => 'Comments: :title', + 'empty' => 'No comments.', + 'new' => 'New comment', + 'body' => 'Comment', + 'add' => 'Add comment', + 'add_named' => 'Add comment to task :title', + 'save' => 'Save', + 'cancel' => 'Cancel', + 'remove' => 'Remove', + 'edit_named' => 'Edit comment (:author, :at)', + 'remove_named' => 'Remove comment (:author, :at)', + 'remove_title' => 'Remove the comment?', + 'remove_question' => 'The comment will be removed permanently.', + 'at' => ':date at :time', + 'edited' => 'edited :at', + 'unknown_author' => 'Unknown user', + 'added' => 'Comment added.', + 'saved' => 'Comment saved.', + 'removed' => 'Comment removed.', + 'not_found' => 'The comment was not found. Refresh the page.', + 'errors' => [ + 'body_required' => 'Write a comment.', + 'invalid_body' => 'A comment may be at most 5000 characters.', + 'not_author' => 'You can edit and remove only your own comments.', + ], + ], 'errors' => [ 'title_required' => 'Enter the task name.', 'invalid_title' => 'The name may be at most 255 characters.', diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index 30701f7..298d910 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -119,6 +119,34 @@ return [ 'invalid_text' => 'Kohdan teksti voi olla enintään 255 merkkiä.', ], ], + 'comments' => [ + 'title' => 'Kommentit', + 'list_of' => 'Kommentit: :title', + 'empty' => 'Ei kommentteja.', + 'new' => 'Uusi kommentti', + 'body' => 'Kommentti', + 'add' => 'Lisää kommentti', + 'add_named' => 'Lisää kommentti tehtävälle :title', + 'save' => 'Tallenna', + 'cancel' => 'Peruuta', + 'remove' => 'Poista', + 'edit_named' => 'Muokkaa kommenttia (:author, :at)', + 'remove_named' => 'Poista kommentti (:author, :at)', + 'remove_title' => 'Poistetaanko kommentti?', + 'remove_question' => 'Kommentti poistetaan pysyvästi.', + 'at' => ':date klo :time', + 'edited' => 'muokattu :at', + 'unknown_author' => 'Tuntematon käyttäjä', + 'added' => 'Kommentti lisätty.', + 'saved' => 'Kommentti tallennettu.', + 'removed' => 'Kommentti poistettu.', + 'not_found' => 'Kommenttia ei löytynyt. Päivitä sivu.', + 'errors' => [ + 'body_required' => 'Kirjoita kommentti.', + 'invalid_body' => 'Kommentti voi olla enintään 5000 merkkiä.', + 'not_author' => 'Voit muokata ja poistaa vain omia kommenttejasi.', + ], + ], 'errors' => [ 'title_required' => 'Anna tehtävän nimi.', 'invalid_title' => 'Nimen pituus voi olla enintään 255 merkkiä.', diff --git a/tests/Browser/JobsAccessibilityTest.php b/tests/Browser/JobsAccessibilityTest.php index 8f660c2..ae4c4c7 100644 --- a/tests/Browser/JobsAccessibilityTest.php +++ b/tests/Browser/JobsAccessibilityTest.php @@ -9,6 +9,7 @@ use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\ChecklistItemModel; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel; +use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskCommentModel; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\DB; @@ -161,6 +162,8 @@ it('has no accessibility issues on a job with tasks and on the task form', funct ->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Kuvauspäivä', 'due_on' => now()->subDay()->toDateString(), 'estimated_hours' => 6]); ChecklistItemModel::query()->create(['task_id' => $task->id, 'text' => 'Valot', 'sort_order' => 1, 'done_at' => now(), 'done_by' => $this->user->id]); ChecklistItemModel::query()->create(['task_id' => $task->id, 'text' => 'Mikit', 'sort_order' => 2]); + TaskCommentModel::query()->create(['task_id' => $task->id, 'user_id' => $this->user->id, 'body' => 'Valot ok. +Mikit puuttuu.', 'edited_at' => now()]); $url = match ($page) { 'job page' => route('jobs.show', $this->job->id), @@ -279,6 +282,39 @@ it('adds, checks, renames, moves and removes checklist items with the keyboard', ->assertNoAccessibilityIssues(level: 2); }); +it('adds, edits and removes a task comment 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ä']); + + $page = visit(route('jobs.show', $this->job->id)) + ->click('#task-toggle-'.$task->id) + ->type('#comment-new-'.$task->id, 'Valot ok.') + ->keys('[aria-label="Lisää kommentti tehtävälle Kuvauspäivä"]', 'Enter') + ->assertSee('Kommentti lisätty.') + ->assertSeeIn('#task-'.$task->id.'-title + dl', 'Kommentit:'); + + $commentId = TaskCommentModel::query()->sole()->id; + + $page->keys('#comment-edit-button-'.$commentId, 'Enter') + ->assertScript('document.activeElement.id', 'comment-edit-'.$commentId) + ->type('#comment-edit-'.$commentId, 'Valot ja mikit ok.') + ->click('Tallenna') + ->assertSee('Kommentti tallennettu.') + ->assertSee('Valot ja mikit ok.') + ->assertScript('document.activeElement.id', 'comment-edit-button-'.$commentId) + ->keys('[aria-label^="Poista kommentti (Johanna Johto"]', 'Enter') + ->assertScript("document.getElementById('remove-comment-dialog-{$task->id}').open", true) + ->assertNoAccessibilityIssues(level: 2) + ->click('#remove-comment-confirm-'.$task->id) + ->assertSee('Kommentti poistettu.') + ->assertScript('document.activeElement.id', 'comment-new-'.$task->id) + ->assertNoAccessibilityIssues(level: 2); + + expect(TaskCommentModel::query()->count())->toBe(0); +}); + 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(); diff --git a/tests/Fakes/InMemoryTaskCommentRepository.php b/tests/Fakes/InMemoryTaskCommentRepository.php new file mode 100644 index 0000000..c78d9d0 --- /dev/null +++ b/tests/Fakes/InMemoryTaskCommentRepository.php @@ -0,0 +1,34 @@ + */ + public array $comments = []; + + private int $nextId = 1; + + public function findForTask(int $taskId, int $commentId): ?TaskComment + { + $comment = $this->comments[$commentId] ?? null; + + return $comment !== null && $comment->taskId() === $taskId ? clone $comment : null; + } + + public function save(TaskComment $comment): TaskComment + { + $id = $comment->id() ?? $this->nextId++; + $this->comments[$id] = TaskComment::reconstitute($id, $comment->taskId(), $comment->authorId(), $comment->body(), $comment->createdAt(), $comment->editedAt()); + + return clone $this->comments[$id]; + } + + public function delete(TaskComment $comment): void + { + unset($this->comments[$comment->id()]); + } +} diff --git a/tests/Feature/Modules/Jobs/TaskCommentsTest.php b/tests/Feature/Modules/Jobs/TaskCommentsTest.php new file mode 100644 index 0000000..11ef342 --- /dev/null +++ b/tests/Feature/Modules/Jobs/TaskCommentsTest.php @@ -0,0 +1,148 @@ +employee = User::factory()->create(['name' => 'Eetu Esimerkki']); + $this->actingAs($this->employee); + $this->job = CustomerJobModel::factory()->create(['status' => 'order', 'responsible_user_id' => $this->employee->id]); + $workType = WorkTypeModel::query()->where('name', 'graafinen työ')->sole(); + $this->task = TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Mainoskuvat']); + $this->params = ['jobId' => $this->job->id, 'taskId' => $this->task->id, 'taskTitle' => 'Mainoskuvat']; +}); + +function taskComment(int $taskId, int $userId, string $body): TaskCommentModel +{ + return TaskCommentModel::query()->create(['task_id' => $taskId, 'user_id' => $userId, 'body' => $body]); +} + +it('shows the comments with author, time and their number on the job page', function () { + $this->travelTo(now()->setTimezone('Europe/Helsinki')->setDate(2026, 11, 25)->setTime(14, 5)); + taskComment($this->task->id, $this->employee->id, 'Valot ok.'); + taskComment($this->task->id, $this->employee->id, 'Mikit puuttuu.'); + + $this->get(route('jobs.show', $this->job->id)) + ->assertOk() + ->assertSee('Kommentit:') + ->assertSeeInOrder(['Eetu Esimerkki', '25.11.2026 klo 14.05', 'Valot ok.', 'Mikit puuttuu.']); +}); + +it('adds, edits and removes the user\'s own comment', function () { + $component = Livewire::test('jobs::task-comments', $this->params) + ->set('newComment', " Valot ok.\nMikit puuttuu. ") + ->call('add') + ->assertHasNoErrors() + ->assertSet('newComment', '') + ->assertSee('Kommentti lisätty.') + ->assertDispatched('task-comments-changed'); + + $comment = TaskCommentModel::query()->sole(); + + expect($comment->body)->toBe("Valot ok.\nMikit puuttuu.") + ->and($comment->user_id)->toBe($this->employee->id); + + $component->call('startEdit', $comment->id) + ->assertSet('editingBody', "Valot ok.\nMikit puuttuu.") + ->set('editingBody', 'Kaikki ok.') + ->call('saveEdit') + ->assertSee('Kommentti tallennettu.') + ->assertSee('muokattu') + ->assertSet('editingCommentId', null); + + expect($comment->fresh()->body)->toBe('Kaikki ok.') + ->and($comment->fresh()->edited_at)->not->toBeNull(); + + $component->call('confirmRemoval', $comment->id) + ->assertSet('removalCommentId', $comment->id) + ->call('remove') + ->assertSee('Kommentti poistettu.'); + + expect(TaskCommentModel::query()->count())->toBe(0); +}); + +it('shows Finnish errors for empty and too long comments', function () { + Livewire::test('jobs::task-comments', $this->params) + ->call('add') + ->assertHasErrors('newComment') + ->assertSee('Kirjoita kommentti.') + ->set('newComment', str_repeat('a', 5001)) + ->call('add') + ->assertSee('Kommentti voi olla enintään 5000 merkkiä.'); + + expect(TaskCommentModel::query()->count())->toBe(0); +}); + +it('does not let an employee edit or remove another user\'s comment', function () { + $comment = taskComment($this->task->id, User::factory()->create()->id, 'Toisen kommentti'); + + Livewire::test('jobs::task-comments', $this->params) + ->assertDontSee('Muokkaa kommenttia') + ->assertDontSee('Poista kommentti') + ->call('startEdit', $comment->id) + ->assertSet('editingCommentId', null) + ->assertSee('Voit muokata ja poistaa vain omia kommenttejasi.') + ->call('confirmRemoval', $comment->id) + ->assertSet('removalCommentId', null); + + expect($comment->fresh())->not->toBeNull(); +}); + +it('lets management remove anyone\'s comment but not edit it', function () { + $comment = taskComment($this->task->id, $this->employee->id, 'Työntekijän kommentti'); + $this->actingAs(User::factory()->management()->create()); + + Livewire::test('jobs::task-comments', $this->params) + ->assertSee('Poista kommentti') + ->assertDontSee('Muokkaa kommenttia') + ->call('confirmRemoval', $comment->id) + ->call('remove') + ->assertSee('Kommentti poistettu.'); + + expect($comment->fresh())->toBeNull(); +}); + +it('does not change comments of another task through this one', function () { + $other = taskComment(TaskModel::factory()->create()->id, $this->employee->id, 'Vieras'); + + Livewire::test('jobs::task-comments', $this->params) + ->call('confirmRemoval', $other->id) + ->assertSee('Kommenttia ei löytynyt. Päivitä sivu.') + ->assertSet('removalCommentId', null); + + expect($other->fresh())->not->toBeNull(); +}); + +it('lets an attached subcontractor comment', function () { + $subcontractor = User::factory()->subcontractor()->create(); + TaskModel::factory()->assignedTo([$subcontractor->id])->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->task->work_type_id]); + $this->actingAs($subcontractor); + + Livewire::test('jobs::task-comments', $this->params) + ->set('newComment', 'Aineisto toimitettu.') + ->call('add') + ->assertSee('Kommentti lisätty.'); + + expect(TaskCommentModel::query()->sole()->user_id)->toBe($subcontractor->id); +}); + +it('forbids the comments of a job the subcontractor is not attached to', function () { + $this->actingAs(User::factory()->subcontractor()->create()); + + Livewire::test('jobs::task-comments', $this->params)->assertForbidden(); +}); + +it('removes the comments with their task', function () { + taskComment($this->task->id, $this->employee->id, 'Valot ok.'); + + $this->task->delete(); + + expect(TaskCommentModel::query()->count())->toBe(0); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TaskCommentUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/TaskCommentUseCasesTest.php new file mode 100644 index 0000000..adfbf17 --- /dev/null +++ b/tests/Unit/Modules/Jobs/Application/TaskCommentUseCasesTest.php @@ -0,0 +1,83 @@ +comments = new InMemoryTaskCommentRepository; + $transactions = new FakeTransactionManager; + $finder = new TaskCommentFinder($tasks, $this->comments); + $this->clock = new FakeClock(new DateTimeImmutable('2026-11-25')); + + $this->jobId = 5; + $this->taskId = (int) $tasks->save(Task::reconstitute(1, $this->jobId, 11, new TaskTitle('Kuvaus'), null, TaskStatus::Waiting, null, null, null, [], 10))->id(); + + $this->add = new AddTaskComment($finder, $this->comments, $transactions, $this->clock); + $this->edit = new EditTaskComment($finder, $this->comments, $transactions, $this->clock); + $this->remove = new RemoveTaskComment($finder, $this->comments, $transactions); +}); + +it('keeps line breaks of a comment and rejects empty and too long comments', function () { + expect((new TaskCommentBody(" Valot ok.\r\nMikit puuttuu. \n"))->value)->toBe("Valot ok.\nMikit puuttuu.") + ->and(fn () => new TaskCommentBody(" \n "))->toThrow(InvalidTaskCommentBody::class) + ->and(fn () => new TaskCommentBody(str_repeat('a', 5001)))->toThrow(InvalidTaskCommentBody::class); +}); + +it('adds a comment with its author and time', function () { + $commentId = $this->add->execute($this->jobId, $this->taskId, 10, 'Valot ok.'); + $comment = $this->comments->comments[$commentId]; + + expect($comment->authorId())->toBe(10) + ->and($comment->body()->value)->toBe('Valot ok.') + ->and($comment->createdAt()->format('Y-m-d H:i'))->toBe('2026-11-25 12:00') + ->and($comment->editedAt())->toBeNull(); +}); + +it('lets only the author edit a comment and marks it edited', function () { + $commentId = $this->add->execute($this->jobId, $this->taskId, 10, 'Valot ok.'); + + $this->edit->execute($this->jobId, $this->taskId, $commentId, 10, 'Valot ok.'); + expect($this->comments->comments[$commentId]->editedAt())->toBeNull(); + + $this->clock->today = new DateTimeImmutable('2026-11-26'); + $this->edit->execute($this->jobId, $this->taskId, $commentId, 10, 'Valot ja mikit ok.'); + + expect($this->comments->comments[$commentId]->body()->value)->toBe('Valot ja mikit ok.') + ->and($this->comments->comments[$commentId]->editedAt()?->format('Y-m-d'))->toBe('2026-11-26') + ->and(fn () => $this->edit->execute($this->jobId, $this->taskId, $commentId, 12, 'Muutettu'))->toThrow(NotTaskCommentAuthor::class); +}); + +it('lets the author remove a comment, and others only when they may remove anyone\'s', function () { + $own = $this->add->execute($this->jobId, $this->taskId, 10, 'Oma'); + $other = $this->add->execute($this->jobId, $this->taskId, 10, 'Toisen'); + + expect(fn () => $this->remove->execute($this->jobId, $this->taskId, $other, 12, false))->toThrow(NotTaskCommentAuthor::class); + + $this->remove->execute($this->jobId, $this->taskId, $own, 10, false); + $this->remove->execute($this->jobId, $this->taskId, $other, 12, true); + + expect($this->comments->comments)->toBe([]); +}); + +it('does not touch comments of a task through another job', function () { + $commentId = $this->add->execute($this->jobId, $this->taskId, 10, 'Valot ok.'); + + expect(fn () => $this->add->execute(99, $this->taskId, 10, 'Vieras'))->toThrow(TaskNotFound::class) + ->and(fn () => $this->edit->execute(99, $this->taskId, $commentId, 10, 'Vieras'))->toThrow(TaskNotFound::class) + ->and(fn () => $this->remove->execute($this->jobId, $this->taskId, 404, 10, true))->toThrow(TaskCommentNotFound::class); +});