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
@@ -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>