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 <[email protected]>
This commit is contained in:
2026-11-25 07:31:53 +02:00
co-authored by Claude Sonnet 5.5
parent 60cab4b871
commit 4fb8ea1c5f
29 changed files with 1354 additions and 4 deletions
+2 -2
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `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: `<x-input>`, `<x-button>`), 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` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `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`).
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
use App\Modules\Jobs\Application\DTOs\TaskCommentSummary;
interface TaskCommentQueries
{
/**
* The task's comments, oldest first; empty when the task belongs to
* another job.
*
* @return list<TaskCommentSummary>
*/
public function commentsOf(int $jobId, int $taskId): array;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* A task comment with its author's name. Times are in the business time
* zone as "Y-m-d H:i".
*/
final readonly class TaskCommentSummary
{
public function __construct(
public int $id,
public ?int $authorId,
public string $authorName,
public string $body,
public string $createdAt,
public ?string $editedAt,
) {}
}
@@ -27,5 +27,6 @@ final readonly class TaskSummary
public array $members,
public ?string $plannedFrom = null,
public ?string $plannedTo = null,
public int $commentCount = 0,
) {}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Services;
use App\Modules\Jobs\Domain\Contracts\TaskCommentRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Entities\TaskComment;
use App\Modules\Jobs\Domain\Exceptions\TaskCommentNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
/**
* Finds a comment only through its task and the task's job, so a page of
* one job never changes another job's comments.
*/
final readonly class TaskCommentFinder
{
public function __construct(
private TaskRepository $tasks,
private TaskCommentRepository $comments,
) {}
/**
* @throws TaskNotFound
* @throws TaskCommentNotFound
*/
public function find(int $jobId, int $taskId, int $commentId): TaskComment
{
$this->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);
}
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\Services\TaskCommentFinder;
use App\Modules\Jobs\Domain\Contracts\TaskCommentRepository;
use App\Modules\Jobs\Domain\Entities\TaskComment;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskCommentBody;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Domain\ValueObjects\TaskCommentBody;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Adds a comment by the given user to a task.
*/
final class AddTaskComment
{
public function __construct(
private TaskCommentFinder $finder,
private TaskCommentRepository $comments,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The new comment's id.
*
* @throws TaskNotFound
* @throws InvalidTaskCommentBody
*/
public function execute(int $jobId, int $taskId, int $userId, string $body): int
{
$body = new TaskCommentBody($body);
return $this->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();
});
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\Services\TaskCommentFinder;
use App\Modules\Jobs\Domain\Contracts\TaskCommentRepository;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskCommentBody;
use App\Modules\Jobs\Domain\Exceptions\NotTaskCommentAuthor;
use App\Modules\Jobs\Domain\Exceptions\TaskCommentNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Domain\ValueObjects\TaskCommentBody;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Changes the text of the user's own comment and marks it edited.
*/
final class EditTaskComment
{
public function __construct(
private TaskCommentFinder $finder,
private TaskCommentRepository $comments,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @throws TaskNotFound
* @throws TaskCommentNotFound
* @throws NotTaskCommentAuthor
* @throws InvalidTaskCommentBody
*/
public function execute(int $jobId, int $taskId, int $commentId, int $userId, string $body): void
{
$body = new TaskCommentBody($body);
$this->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);
});
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\Services\TaskCommentFinder;
use App\Modules\Jobs\Domain\Contracts\TaskCommentRepository;
use App\Modules\Jobs\Domain\Exceptions\NotTaskCommentAuthor;
use App\Modules\Jobs\Domain\Exceptions\TaskCommentNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Removes the user's own comment, or anyone's when the user may remove
* others' comments (admin and management).
*/
final class RemoveTaskComment
{
public function __construct(
private TaskCommentFinder $finder,
private TaskCommentRepository $comments,
private TransactionManager $transactions,
) {}
/**
* @throws TaskNotFound
* @throws TaskCommentNotFound
* @throws NotTaskCommentAuthor
*/
public function execute(int $jobId, int $taskId, int $commentId, int $userId, bool $mayRemoveOthers): void
{
$this->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);
});
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Contracts;
use App\Modules\Jobs\Domain\Entities\TaskComment;
interface TaskCommentRepository
{
/**
* Null when the comment does not exist or belongs to another task.
*/
public function findForTask(int $taskId, int $commentId): ?TaskComment;
public function save(TaskComment $comment): TaskComment;
public function delete(TaskComment $comment): void;
}
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Entities;
use App\Modules\Jobs\Domain\Exceptions\NotTaskCommentAuthor;
use App\Modules\Jobs\Domain\ValueObjects\TaskCommentBody;
use DateTimeImmutable;
/**
* A comment on a task. Its author may edit and remove it; others may only
* remove it, and only when allowed to remove anyone's comments.
*/
final class TaskComment
{
private function __construct(
private ?int $id,
private int $taskId,
private ?int $authorId,
private TaskCommentBody $body,
private DateTimeImmutable $createdAt,
private ?DateTimeImmutable $editedAt,
) {}
public static function create(int $taskId, int $authorId, TaskCommentBody $body, DateTimeImmutable $at): self
{
return new self(null, $taskId, $authorId, $body, $at, null);
}
/**
* The author is null when the user no longer exists.
*/
public static function reconstitute(int $id, int $taskId, ?int $authorId, TaskCommentBody $body, DateTimeImmutable $createdAt, ?DateTimeImmutable $editedAt): self
{
return new self($id, $taskId, $authorId, $body, $createdAt, $editedAt);
}
/**
* Saving the same text again changes nothing.
*
* @throws NotTaskCommentAuthor
*/
public function edit(int $userId, TaskCommentBody $body, DateTimeImmutable $at): void
{
$this->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);
}
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidTaskCommentBody extends DomainException
{
public function __construct()
{
parent::__construct('A task comment must be 1–5000 characters.');
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* Only the author edits a comment; others than the author may remove it
* only when they may remove anyone's comments.
*/
final class NotTaskCommentAuthor extends DomainException
{
public function __construct(public readonly int $commentId, public readonly int $userId)
{
parent::__construct("User {$userId} is not the author of comment {$commentId}.");
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The comment does not exist or belongs to another task or job.
*/
final class TaskCommentNotFound extends DomainException
{
public function __construct(public readonly int $taskId, public readonly int $commentId)
{
parent::__construct("Comment {$commentId} of task {$taskId} was not found.");
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskCommentBody;
/**
* The text of a task comment: line breaks are kept, surrounding blank space
* is not.
*/
final readonly class TaskCommentBody
{
public const int MAX_LENGTH = 5000;
public string $value;
/**
* @throws InvalidTaskCommentBody
*/
public function __construct(string $value)
{
$value = trim(str_replace(["\r\n", "\r"], "\n", $value));
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidTaskCommentBody;
}
$this->value = $value;
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Eloquent;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model of a task comment, used only inside the Jobs
* Infrastructure layer.
*
* @property int $id
* @property int $task_id
* @property int|null $user_id
* @property string $body
* @property CarbonImmutable|null $edited_at
* @property CarbonImmutable $created_at
*/
#[Table('task_comments')]
#[Fillable(['task_id', 'user_id', 'body', 'edited_at', 'created_at'])]
class TaskCommentModel extends Model
{
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'task_id' => 'integer',
'user_id' => 'integer',
'edited_at' => 'immutable_datetime',
'created_at' => 'immutable_datetime',
'updated_at' => 'immutable_datetime',
];
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Application\Contracts\TaskCommentQueries;
use App\Modules\Jobs\Application\DTOs\TaskCommentSummary;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskCommentModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Carbon\CarbonImmutable;
class EloquentTaskCommentQueries implements TaskCommentQueries
{
public function __construct(private UserAccountQueries $users) {}
public function commentsOf(int $jobId, int $taskId): array
{
$models = TaskCommentModel::query()
->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');
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Domain\Contracts\TaskCommentRepository;
use App\Modules\Jobs\Domain\Entities\TaskComment;
use App\Modules\Jobs\Domain\ValueObjects\TaskCommentBody;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskCommentModel;
use DateTimeImmutable;
class EloquentTaskCommentRepository implements TaskCommentRepository
{
public function findForTask(int $taskId, int $commentId): ?TaskComment
{
$model = TaskCommentModel::query()->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),
);
}
}
@@ -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();
}
}
@@ -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)
@@ -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
<dt class="font-medium">{{ __('jobs.tasks.fields.status') }}:</dt>
<dd>{{ __('jobs.tasks.statuses.'.$task->status->value) }}</dd>
</div>
@if ($task->commentCount > 0)
<div class="flex flex-wrap gap-x-1">
<dt class="font-medium">{{ __('jobs.tasks.comments.title') }}:</dt>
<dd>{{ $task->commentCount }}</dd>
</div>
@endif
</dl>
</div>
@@ -438,6 +454,8 @@ new class extends Component
<livewire:jobs::task-checklist :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'checklist-'.$task->id" />
<livewire:jobs::task-comments :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'comments-'.$task->id" />
<div class="flex flex-wrap items-end gap-3">
@if ($canChangeStatus)
<div class="w-full sm:w-56">
@@ -0,0 +1,365 @@
<?php
use App\Modules\Jobs\Application\Contracts\TaskCommentQueries;
use App\Modules\Jobs\Application\DTOs\TaskCommentSummary;
use App\Modules\Jobs\Application\UseCases\AddTaskComment;
use App\Modules\Jobs\Application\UseCases\EditTaskComment;
use App\Modules\Jobs\Application\UseCases\RemoveTaskComment;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskCommentBody;
use App\Modules\Jobs\Domain\Exceptions\NotTaskCommentAuthor;
use App\Modules\Jobs\Domain\Exceptions\TaskCommentNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* A task's comments on the job page (spec 8.2, K27): everyone who may change
* the task's status (also attached subcontractors) comments; authors edit
* and remove their own comments, admin and management remove anyone's.
*/
new class extends Component
{
#[Locked]
public int $jobId;
#[Locked]
public int $taskId;
#[Locked]
public string $taskTitle = '';
public string $newComment = '';
/**
* The comment being edited, if any.
*/
#[Locked]
public ?int $editingCommentId = null;
public string $editingBody = '';
/**
* The comment the remove dialog asks about.
*/
#[Locked]
public ?int $removalCommentId = null;
public string $message = '';
public function mount(int $jobId, int $taskId, string $taskTitle): void
{
$this->authorize('jobs.view-job', $jobId);
$this->jobId = $jobId;
$this->taskId = $taskId;
$this->taskTitle = $taskTitle;
}
/**
* @return list<TaskCommentSummary>
*/
#[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. --}}
<section aria-label="{{ __('jobs.tasks.comments.list_of', ['title' => $taskTitle]) }}" class="space-y-2">
@php($canComment = Gate::allows('jobs.update-task-status', $jobId))
<h4 class="font-medium">
{{ __('jobs.tasks.comments.title') }}
@if ($this->comments !== [])
<span class="font-normal">({{ count($this->comments) }})</span>
@endif
</h4>
<p role="status" aria-live="polite" class="text-sm">{{ $message }}</p>
@if ($this->comments === [])
<p class="text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.comments.empty') }}</p>
@else
<ol class="space-y-3">
@foreach ($this->comments as $comment)
@php($at = $this->formatTime($comment->createdAt))
@php($named = ['author' => $this->authorName($comment), 'at' => $at])
<li wire:key="task-comment-{{ $comment->id }}" class="space-y-1 rounded-md bg-zinc-50 p-3 dark:bg-zinc-800">
<p class="flex flex-wrap gap-x-2">
<span class="font-medium">{{ $this->authorName($comment) }}</span>
<span class="text-zinc-600 dark:text-zinc-300">
<time datetime="{{ str_replace(' ', 'T', $comment->createdAt) }}">{{ $at }}</time>
@if ($comment->editedAt !== null)
({{ __('jobs.tasks.comments.edited', ['at' => $this->formatTime($comment->editedAt)]) }})
@endif
</span>
</p>
@if ($editingCommentId === $comment->id)
<form wire:submit="saveEdit" class="space-y-2">
<x-textarea id="comment-edit-{{ $comment->id }}" wire:model="editingBody" :label="__('jobs.tasks.comments.body')" maxlength="5000" resize-auto />
<div class="flex flex-wrap gap-2">
<x-button submit sm icon="check" :text="__('jobs.tasks.comments.save')" />
<x-button wire:click="cancelEdit" subtle color="black" sm :text="__('jobs.tasks.comments.cancel')" />
</div>
</form>
@else
<p class="whitespace-pre-line break-words">{{ $comment->body }}</p>
@if ($canComment && ($this->isOwn($comment) || $this->mayRemove($comment)))
<div class="flex flex-wrap items-center gap-2">
@if ($this->isOwn($comment))
<x-button
id="comment-edit-button-{{ $comment->id }}"
wire:click="startEdit({{ $comment->id }})"
subtle
color="black"
sm
icon="pencil"
:text="__('jobs.edit')"
:aria-label="__('jobs.tasks.comments.edit_named', $named)"
/>
@endif
<x-button
wire:click="confirmRemoval({{ $comment->id }})"
subtle
color="black"
sm
icon="trash"
:text="__('jobs.tasks.comments.remove')"
:aria-label="__('jobs.tasks.comments.remove_named', $named)"
/>
</div>
@endif
@endif
</li>
@endforeach
</ol>
@endif
@if ($canComment)
<form wire:submit="add" class="space-y-2">
<x-textarea id="comment-new-{{ $taskId }}" wire:model="newComment" :label="__('jobs.tasks.comments.new')" maxlength="5000" resize-auto />
<x-button submit sm icon="chat-bubble-left" :text="__('jobs.tasks.comments.add')" :aria-label="__('jobs.tasks.comments.add_named', ['title' => $taskTitle])" />
</form>
<x-confirm-dialog id="remove-comment-dialog-{{ $taskId }}" :title="__('jobs.tasks.comments.remove_title')">
<p>{{ __('jobs.tasks.comments.remove_question') }}</p>
<x-slot:actions>
<x-button id="remove-comment-confirm-{{ $taskId }}" wire:click="remove" color="red" icon="trash" :text="__('jobs.tasks.comments.remove')" />
</x-slot:actions>
</x-confirm-dialog>
@endif
</section>
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Comments on tasks, oldest first. The author is kept as null if the
* user is ever deleted.
*/
public function up(): void
{
Schema::create('task_comments', function (Blueprint $table) {
$table->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');
}
};
+2 -2
View File
@@ -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.
+28
View File
@@ -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.',
+28
View File
@@ -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ä.',
+36
View File
@@ -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();
@@ -0,0 +1,34 @@
<?php
namespace Tests\Fakes;
use App\Modules\Jobs\Domain\Contracts\TaskCommentRepository;
use App\Modules\Jobs\Domain\Entities\TaskComment;
class InMemoryTaskCommentRepository implements TaskCommentRepository
{
/** @var array<int, TaskComment> */
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()]);
}
}
@@ -0,0 +1,148 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
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 Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->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);
});
@@ -0,0 +1,83 @@
<?php
use App\Modules\Jobs\Application\Services\TaskCommentFinder;
use App\Modules\Jobs\Application\UseCases\AddTaskComment;
use App\Modules\Jobs\Application\UseCases\EditTaskComment;
use App\Modules\Jobs\Application\UseCases\RemoveTaskComment;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskCommentBody;
use App\Modules\Jobs\Domain\Exceptions\NotTaskCommentAuthor;
use App\Modules\Jobs\Domain\Exceptions\TaskCommentNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Domain\ValueObjects\TaskCommentBody;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryTaskCommentRepository;
use Tests\Fakes\InMemoryTaskRepository;
beforeEach(function () {
$tasks = new InMemoryTaskRepository;
$this->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);
});