Add tasks to customer jobs

Phase 1, item 7, in the Jobs module (tasks are part of a job, and my jobs
needs their assignees):
- Tasks with name, work type, assignees, status (waiting, in progress,
  in review, done), due date, estimated hours and description.
- Tasks can be added once the job is a quote request or later, not to
  an archived job. The work type must belong to the job's service units
  or the shared ones and be in use; assignees must be active. What a
  task already has stays allowed after being taken out of use.
- Job page: a Tehtävät section with a status select per task (announced,
  focus kept), edit links and delete with a confirmation dialog. Task
  form with work types grouped by unit and service.
- Access: adding, changing and removing for everyone but subcontractors;
  subcontractors may change task statuses on jobs they are attached to.
- Task assignees now count in my jobs (list, Kanban, job access).
- Spec and CLAUDE.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-23 19:26:31 +02:00
co-authored by Claude Opus 5.5
parent 7f3b6dff78
commit 02a62eb16e
37 changed files with 1895 additions and 8 deletions
+1 -1
View File
@@ -22,7 +22,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<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`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`).
- `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`.
- Generate module files with Artisan, then edit them: `php artisan make:class Modules/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files.
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
use App\Modules\Jobs\Application\DTOs\TaskSummary;
interface TaskQueries
{
/**
* The job's tasks: open ones by due date (none last), then done ones.
*
* @return list<TaskSummary>
*/
public function tasksOf(int $jobId): array;
/**
* Null when the task does not exist or belongs to another job.
*/
public function findTask(int $jobId, int $taskId): ?TaskSummary;
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* Input for adding or changing a task. The due date is Y-m-d.
*/
final readonly class TaskData
{
/**
* @param list<int> $assigneeUserIds
*/
public function __construct(
public string $title,
public int $workTypeId,
public string $status,
public ?string $description = null,
public ?string $dueOn = null,
public ?string $estimatedHours = null,
public array $assigneeUserIds = [],
) {}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* A task with names resolved, for the job page and the task form.
*/
final readonly class TaskSummary
{
/**
* @param list<NamedId> $assignees
*/
public function __construct(
public int $id,
public int $jobId,
public string $title,
public ?string $description,
public TaskStatus $status,
public ?string $dueOn,
public ?string $estimatedHours,
public NamedId $workType,
public array $assignees,
) {}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Services;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Jobs\Domain\Entities\CustomerJob;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
/**
* Checks that a task's work type belongs to the job's service units (or
* the shared work types) and is in use, and that assignees are active.
* What the task already has stays allowed after being taken out of use.
*/
final class TaskReferenceChecker
{
public function __construct(
private CatalogQueries $catalog,
private UserAccountQueries $users,
) {}
/**
* @param list<int> $assigneeUserIds
*
* @throws InvalidTaskReference
*/
public function check(CustomerJob $job, int $workTypeId, array $assigneeUserIds, ?Task $current = null): void
{
if ($workTypeId !== $current?->workTypeId() && ! in_array($workTypeId, $this->workTypeIdsFor($job), true)) {
throw new InvalidTaskReference('work_type');
}
$activeIds = array_map(fn ($option): int => $option->id, $this->users->activeUserOptions());
foreach ($assigneeUserIds as $userId) {
if (! in_array($userId, $activeIds, true) && ! in_array($userId, $current?->assigneeUserIds() ?? [], true)) {
throw new InvalidTaskReference('assignees');
}
}
}
/**
* @return list<int>
*/
private function workTypeIdsFor(CustomerJob $job): array
{
$ids = [];
foreach ($this->catalog->activeWorkTypesFor($job->details()->serviceUnitIds) as $unit) {
foreach ($unit->workTypes as $workType) {
$ids[] = $workType->id;
}
foreach ($unit->services as $service) {
foreach ($service->workTypes as $workType) {
$ids[] = $workType->id;
}
}
}
return $ids;
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\DTOs\TaskData;
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class AddTask
{
public function __construct(
private CustomerJobRepository $jobs,
private TaskRepository $tasks,
private TaskReferenceChecker $references,
private TransactionManager $transactions,
) {}
/**
* @return int The new task's id.
*
* @throws CustomerJobNotFound
* @throws TasksNotAllowedYet
* @throws InvalidTaskReference
*/
public function execute(int $jobId, TaskData $data, int $actorUserId): int
{
$title = new TaskTitle($data->title);
return $this->transactions->run(function () use ($jobId, $data, $title, $actorUserId): int {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$this->references->check($job, $data->workTypeId, $data->assigneeUserIds);
$task = Task::create(
$jobId,
$job->details()->status,
$data->workTypeId,
$title,
$data->description,
TaskStatus::from($data->status),
TaskInput::date($data->dueOn),
TaskInput::hours($data->estimatedHours),
$data->assigneeUserIds,
$actorUserId,
);
return (int) $this->tasks->save($task)->id();
});
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class ChangeTaskStatus
{
public function __construct(
private TaskRepository $tasks,
private TransactionManager $transactions,
) {}
/**
* @throws TaskNotFound
*/
public function execute(int $jobId, int $taskId, TaskStatus $status): void
{
$this->transactions->run(function () use ($jobId, $taskId, $status): void {
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
$task->changeStatus($status);
$this->tasks->save($task);
});
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Deletes a task. Once time is recorded on tasks, a task with time entries
* cannot be removed.
*/
final class RemoveTask
{
public function __construct(
private TaskRepository $tasks,
private TransactionManager $transactions,
) {}
/**
* @throws TaskNotFound
*/
public function execute(int $jobId, int $taskId): void
{
$this->transactions->run(function () use ($jobId, $taskId): void {
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
$this->tasks->delete($task);
});
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use DateTimeImmutable;
use InvalidArgumentException;
/**
* Parses the optional date and hours of task input.
*
* @internal
*/
final class TaskInput
{
public static function date(?string $value): ?DateTimeImmutable
{
$value = $value === null ? '' : trim($value);
if ($value === '') {
return null;
}
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if ($date === false || $date->format('Y-m-d') !== $value) {
throw new InvalidArgumentException("Not a Y-m-d date: {$value}");
}
return $date;
}
public static function hours(?string $value): ?EstimatedHours
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : EstimatedHours::fromString($value);
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\DTOs\TaskData;
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use App\Modules\Shared\Application\Contracts\TransactionManager;
final class UpdateTask
{
public function __construct(
private CustomerJobRepository $jobs,
private TaskRepository $tasks,
private TaskReferenceChecker $references,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerJobNotFound
* @throws TaskNotFound
* @throws InvalidTaskReference
*/
public function execute(int $jobId, int $taskId, TaskData $data): void
{
$title = new TaskTitle($data->title);
$this->transactions->run(function () use ($jobId, $taskId, $data, $title): void {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
$this->references->check($job, $data->workTypeId, $data->assigneeUserIds, $task);
$task->changeDetails(
$data->workTypeId,
$title,
$data->description,
TaskStatus::from($data->status),
TaskInput::date($data->dueOn),
TaskInput::hours($data->estimatedHours),
$data->assigneeUserIds,
);
$this->tasks->save($task);
});
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Contracts;
use App\Modules\Jobs\Domain\Entities\Task;
interface TaskRepository
{
/**
* Null when the task does not exist or belongs to another job.
*/
public function findForJob(int $jobId, int $taskId): ?Task;
public function save(Task $task): Task;
public function delete(Task $task): void;
}
+177
View File
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Entities;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use DateTimeImmutable;
/**
* A task (tehtävä) of a customer job: one step of the work, done by its
* assignees under one work type. Time entries are recorded on tasks.
*/
final class Task
{
/**
* @param list<int> $assigneeUserIds
*/
private function __construct(
private ?int $id,
private int $jobId,
private int $workTypeId,
private TaskTitle $title,
private ?string $description,
private TaskStatus $status,
private ?DateTimeImmutable $dueOn,
private ?EstimatedHours $estimatedHours,
private array $assigneeUserIds,
private int $createdBy,
) {
$this->assigneeUserIds = self::normaliseIds($assigneeUserIds);
}
/**
* @param list<int> $assigneeUserIds
*
* @throws TasksNotAllowedYet
*/
public static function create(
int $jobId,
JobStatus $jobStatus,
int $workTypeId,
TaskTitle $title,
?string $description,
TaskStatus $status,
?DateTimeImmutable $dueOn,
?EstimatedHours $estimatedHours,
array $assigneeUserIds,
int $createdBy,
): self {
if (! $jobStatus->allowsTasks()) {
throw new TasksNotAllowedYet;
}
return new self(null, $jobId, $workTypeId, $title, self::text($description), $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy);
}
/**
* @param list<int> $assigneeUserIds
*/
public static function reconstitute(
int $id,
int $jobId,
int $workTypeId,
TaskTitle $title,
?string $description,
TaskStatus $status,
?DateTimeImmutable $dueOn,
?EstimatedHours $estimatedHours,
array $assigneeUserIds,
int $createdBy,
): self {
return new self($id, $jobId, $workTypeId, $title, $description, $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy);
}
/**
* @param list<int> $assigneeUserIds
*/
public function changeDetails(
int $workTypeId,
TaskTitle $title,
?string $description,
TaskStatus $status,
?DateTimeImmutable $dueOn,
?EstimatedHours $estimatedHours,
array $assigneeUserIds,
): void {
$this->workTypeId = $workTypeId;
$this->title = $title;
$this->description = self::text($description);
$this->status = $status;
$this->dueOn = $dueOn;
$this->estimatedHours = $estimatedHours;
$this->assigneeUserIds = self::normaliseIds($assigneeUserIds);
}
public function changeStatus(TaskStatus $status): void
{
$this->status = $status;
}
public function id(): ?int
{
return $this->id;
}
public function jobId(): int
{
return $this->jobId;
}
public function workTypeId(): int
{
return $this->workTypeId;
}
public function title(): TaskTitle
{
return $this->title;
}
public function description(): ?string
{
return $this->description;
}
public function status(): TaskStatus
{
return $this->status;
}
public function dueOn(): ?DateTimeImmutable
{
return $this->dueOn;
}
public function estimatedHours(): ?EstimatedHours
{
return $this->estimatedHours;
}
/**
* @return list<int>
*/
public function assigneeUserIds(): array
{
return $this->assigneeUserIds;
}
public function createdBy(): int
{
return $this->createdBy;
}
/**
* @param list<int> $ids
* @return list<int>
*/
private static function normaliseIds(array $ids): array
{
$ids = array_values(array_unique($ids));
sort($ids);
return $ids;
}
private static function text(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : $value;
}
}
@@ -30,6 +30,14 @@ enum JobStatus: string
return $this === self::Invoiced || $this === self::Billed;
}
/**
* Tasks can be added from a quote request on (K36), not to an archived job.
*/
public function allowsTasks(): bool
{
return ! in_array($this, [self::Prospect, self::Tentative, self::Archived], true);
}
/**
* The Kanban columns: every status except archived.
*
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Status of a task (spec 8.2). Per-service-unit columns come in phase 3.
*/
enum TaskStatus: string
{
case Waiting = 'waiting';
case InProgress = 'in_progress';
case InReview = 'in_review';
case Done = 'done';
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The chosen work type or assignee does not fit the task's job.
*/
final class InvalidTaskReference extends DomainException
{
public function __construct(public readonly string $field)
{
parent::__construct("The task's {$field} is not a valid choice.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidTaskTitle extends DomainException
{
public function __construct()
{
parent::__construct('The task name must be 1–255 characters.');
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The task does not exist or belongs to another job.
*/
final class TaskNotFound extends DomainException
{
public function __construct(public readonly int $jobId, public readonly int $taskId)
{
parent::__construct("Task {$taskId} of job {$jobId} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class TasksNotAllowedYet extends DomainException
{
public function __construct()
{
parent::__construct('Tasks can be added once the job is a quote request or later, and not to an archived job.');
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskTitle;
final readonly class TaskTitle
{
public const int MAX_LENGTH = 255;
public string $value;
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidTaskTitle;
}
$this->value = $value;
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Eloquent;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use Carbon\CarbonImmutable;
use Database\Factories\TaskFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model of a task, used only inside the Jobs Infrastructure
* layer. Assignees are in task_assignees.
*
* @property int $id
* @property int $customer_job_id
* @property int $work_type_id
* @property string $title
* @property string|null $description
* @property TaskStatus $status
* @property CarbonImmutable|null $due_on
* @property string|null $estimated_hours
* @property int $created_by
*/
#[Table('tasks')]
#[Fillable(['customer_job_id', 'work_type_id', 'title', 'description', 'status', 'due_on', 'estimated_hours', 'created_by'])]
#[UseFactory(TaskFactory::class)]
class TaskModel extends Model
{
/** @use HasFactory<TaskFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'customer_job_id' => 'integer',
'work_type_id' => 'integer',
'status' => TaskStatus::class,
'due_on' => 'immutable_date',
'created_by' => 'integer',
];
}
}
@@ -236,7 +236,8 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
}
/**
* Restricts to jobs where the user is responsible, contact, biller or member.
* Restricts to jobs where the user is responsible, contact, biller,
* member or an assignee of one of the job's tasks.
*
* @param Builder<CustomerJobModel> $query
* @return Builder<CustomerJobModel>
@@ -247,6 +248,10 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
->where('responsible_user_id', $userId)
->orWhere('contact_user_id', $userId)
->orWhere('biller_user_id', $userId)
->orWhereIn('id', DB::table('customer_job_members')->select('customer_job_id')->where('user_id', $userId)));
->orWhereIn('id', DB::table('customer_job_members')->select('customer_job_id')->where('user_id', $userId))
->orWhereIn('id', DB::table('tasks')
->join('task_assignees', 'task_assignees.task_id', '=', 'tasks.id')
->select('tasks.customer_job_id')
->where('task_assignees.user_id', $userId)));
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Application\DTOs\TaskSummary;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class EloquentTaskQueries implements TaskQueries
{
public function __construct(
private CatalogQueries $catalog,
private UserAccountQueries $users,
) {}
public function tasksOf(int $jobId): array
{
$models = TaskModel::query()
->where('customer_job_id', $jobId)
->orderByRaw('status = ?', [TaskStatus::Done->value])
->orderByRaw('due_on IS NULL')
->orderBy('due_on')
->orderBy('id')
->get();
return $this->summaries($models);
}
public function findTask(int $jobId, int $taskId): ?TaskSummary
{
$model = TaskModel::query()->where('customer_job_id', $jobId)->find($taskId);
return $model === null ? null : $this->summaries(collect([$model]))[0];
}
/**
* @param Collection<int, TaskModel> $models
* @return list<TaskSummary>
*/
private function summaries(Collection $models): array
{
$assignees = DB::table('task_assignees')
->whereIn('task_id', $models->pluck('id')->all())
->get()
->groupBy('task_id');
$userNames = $this->users->namesByIds($assignees->flatten()->pluck('user_id')->map(fn ($id): int => (int) $id)->unique()->values()->all());
$workTypeNames = [];
foreach ($models->pluck('work_type_id')->unique() as $workTypeId) {
$workTypeNames[$workTypeId] = $this->catalog->findWorkType((int) $workTypeId)->name ?? '';
}
return $models->map(fn (TaskModel $model): TaskSummary => new TaskSummary(
id: $model->id,
jobId: $model->customer_job_id,
title: $model->title,
description: $model->description,
status: $model->status,
dueOn: $model->due_on?->format('Y-m-d'),
estimatedHours: $model->estimated_hours === null ? null : rtrim(rtrim($model->estimated_hours, '0'), '.'),
workType: new NamedId($model->work_type_id, $workTypeNames[$model->work_type_id] ?? ''),
assignees: ($assignees->get($model->id) ?? collect())
->map(fn ($row): NamedId => new NamedId((int) $row->user_id, $userNames[(int) $row->user_id] ?? ''))
->sortBy('name')
->values()
->all(),
))->values()->all();
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
class EloquentTaskRepository implements TaskRepository
{
public function findForJob(int $jobId, int $taskId): ?Task
{
$model = TaskModel::query()->where('customer_job_id', $jobId)->find($taskId);
return $model === null ? null : $this->toEntity($model);
}
public function save(Task $task): Task
{
$model = $task->id() === null ? new TaskModel : TaskModel::query()->findOrFail($task->id());
$model->fill([
'customer_job_id' => $task->jobId(),
'work_type_id' => $task->workTypeId(),
'title' => $task->title()->value,
'description' => $task->description(),
'status' => $task->status(),
'due_on' => $task->dueOn()?->format('Y-m-d'),
'estimated_hours' => $task->estimatedHours()?->value,
'created_by' => $task->createdBy(),
])->save();
DB::table('task_assignees')->where('task_id', $model->id)->whereNotIn('user_id', $task->assigneeUserIds())->delete();
DB::table('task_assignees')->insertOrIgnore(array_map(
fn (int $userId): array => ['task_id' => $model->id, 'user_id' => $userId],
$task->assigneeUserIds(),
));
return $this->toEntity($model->refresh());
}
public function delete(Task $task): void
{
TaskModel::query()->whereKey($task->id())->delete();
}
private function toEntity(TaskModel $model): Task
{
return Task::reconstitute(
$model->id,
$model->customer_job_id,
$model->work_type_id,
new TaskTitle($model->title),
$model->description,
$model->status,
$model->due_on === null ? null : (DateTimeImmutable::createFromFormat('!Y-m-d', $model->due_on->format('Y-m-d')) ?: null),
$model->estimated_hours === null ? null : new EstimatedHours((float) $model->estimated_hours),
DB::table('task_assignees')->where('task_id', $model->id)->pluck('user_id')->map(fn ($id): int => (int) $id)->all(),
$model->created_by,
);
}
}
@@ -5,12 +5,16 @@ namespace App\Modules\Jobs\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs;
use App\Modules\Jobs\Infrastructure\Persistence\DatabaseJobNumberSequence;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskRepository;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
@@ -30,6 +34,8 @@ class JobsServiceProvider extends ServiceProvider
CustomerJobQueries::class => EloquentCustomerJobQueries::class,
JobNumberSequence::class => DatabaseJobNumberSequence::class,
CustomerRowUsage::class => CustomerRowUsageFromJobs::class,
TaskRepository::class => EloquentTaskRepository::class,
TaskQueries::class => EloquentTaskQueries::class,
];
public function boot(): void
@@ -55,6 +61,13 @@ class JobsServiceProvider extends ServiceProvider
Gate::define('jobs.archive', $isManager);
// Adding, changing and removing tasks: everyone but subcontractors.
Gate::define('jobs.manage-tasks', fn (User $user, int $jobId): bool => $user->role !== Role::Subcontractor);
// A subcontractor may change the status of tasks on the jobs they are attached to (spec 2.4).
Gate::define('jobs.update-task-status', fn (User $user, int $jobId): bool => $user->role !== Role::Subcontractor
|| app(CustomerJobQueries::class)->isMember($jobId, $user->id));
// "Lasku luotu" and "Laskutettu" are set when invoicing: management or the job's biller.
// The argument is the job's biller (user id), when known.
Gate::define('jobs.set-billing-status', fn (User $user, ?int $billerUserId = null): bool => $isManager($user)
@@ -0,0 +1,109 @@
<?php
namespace App\Modules\Jobs\Presentation\Livewire\Forms;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Application\DTOs\TaskData;
use App\Modules\Jobs\Application\DTOs\TaskSummary;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskTitle;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Illuminate\Validation\Rule;
use Livewire\Form;
/**
* Task form shared by the add and edit pages.
*/
class TaskForm extends Form
{
public string $title = '';
public string $work_type_id = '';
public string $status = TaskStatus::Waiting->value;
public string $due_on = '';
public string $estimated_hours = '';
public string $description = '';
/** @var list<string> */
public array $assignee_user_ids = [];
public function fillFromSummary(TaskSummary $task): void
{
$this->title = $task->title;
$this->work_type_id = (string) $task->workType->id;
$this->status = $task->status->value;
$this->due_on = $task->dueOn ?? '';
$this->estimated_hours = $task->estimatedHours ?? '';
$this->description = $task->description ?? '';
$this->assignee_user_ids = array_map(fn (NamedId $user): string => (string) $user->id, $task->assignees);
}
public function toData(): TaskData
{
$this->validate();
return new TaskData(
title: $this->title,
workTypeId: (int) $this->work_type_id,
status: $this->status,
description: trim($this->description) === '' ? null : $this->description,
dueOn: $this->due_on === '' ? null : $this->due_on,
estimatedHours: trim($this->estimated_hours) === '' ? null : $this->estimated_hours,
assigneeUserIds: array_map('intval', $this->assignee_user_ids),
);
}
public function showDomainError(DomainException $exception): void
{
[$field, $key] = match (true) {
$exception instanceof InvalidTaskTitle => ['title', 'jobs.tasks.errors.invalid_title'],
$exception instanceof InvalidEstimatedHours => ['estimated_hours', 'jobs.errors.invalid_hours'],
$exception instanceof TasksNotAllowedYet => ['title', 'jobs.tasks.not_allowed_yet'],
$exception instanceof InvalidTaskReference => [$exception->field === 'work_type' ? 'work_type_id' : 'assignee_user_ids', 'jobs.errors.invalid_reference'],
default => throw $exception,
};
$this->addError($field, __($key));
}
/**
* @return array<string, array<int, mixed>>
*/
protected function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'work_type_id' => ['required', 'integer'],
'status' => ['required', Rule::enum(TaskStatus::class)],
'due_on' => ['nullable', 'date_format:Y-m-d'],
'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'],
'description' => ['nullable', 'string', 'max:10000'],
'assignee_user_ids' => ['array'],
'assignee_user_ids.*' => ['integer'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'title.required' => __('jobs.tasks.errors.title_required'),
'title.max' => __('jobs.tasks.errors.invalid_title'),
'work_type_id.required' => __('jobs.tasks.errors.work_type_required'),
'due_on.date_format' => __('jobs.errors.invalid_date'),
'estimated_hours.numeric' => __('jobs.errors.invalid_hours'),
'estimated_hours.min' => __('jobs.errors.invalid_hours'),
'estimated_hours.max' => __('jobs.errors.invalid_hours'),
'description.max' => __('jobs.errors.too_long', ['max' => 10000]),
];
}
}
@@ -4,9 +4,16 @@ use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\TaskSummary;
use App\Modules\Jobs\Application\UseCases\ChangeTaskStatus;
use App\Modules\Jobs\Application\UseCases\RemoveTask;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
@@ -19,6 +26,17 @@ new class extends Component
#[Locked]
public int $jobId;
/**
* The task the remove dialog asks about.
*/
#[Locked]
public ?int $removalTaskId = null;
#[Locked]
public string $removalTaskTitle = '';
public string $taskStatusMessage = '';
public function mount(CustomerJobQueries $jobQueries, int $job): void
{
$this->authorize('jobs.view');
@@ -45,6 +63,82 @@ new class extends Component
return app(CustomerJobQueries::class)->changes($this->jobId);
}
/**
* @return list<TaskSummary>
*/
#[Computed]
public function tasks(): array
{
return app(TaskQueries::class)->tasksOf($this->jobId);
}
public function changeTaskStatus(int $taskId, string $status, ChangeTaskStatus $changeStatus): void
{
$this->authorize('jobs.update-task-status', $this->jobId);
$newStatus = TaskStatus::tryFrom($status);
$task = app(TaskQueries::class)->findTask($this->jobId, $taskId);
if ($newStatus === null || $task === null) {
$this->taskStatusMessage = __('jobs.tasks.not_found');
return;
}
try {
$changeStatus->execute($this->jobId, $taskId, $newStatus);
} catch (TaskNotFound) {
$this->taskStatusMessage = __('jobs.tasks.not_found');
return;
}
unset($this->tasks);
$this->taskStatusMessage = __('jobs.tasks.status_changed', ['title' => $task->title, 'status' => __('jobs.tasks.statuses.'.$newStatus->value)]);
// The list is re-ordered (done tasks last): keep focus on the same select.
$this->js("document.getElementById('task-status-{$taskId}')?.focus()");
}
public function confirmTaskRemoval(int $taskId): void
{
$this->authorize('jobs.manage-tasks', $this->jobId);
$task = app(TaskQueries::class)->findTask($this->jobId, $taskId);
if ($task === null) {
$this->taskStatusMessage = __('jobs.tasks.not_found');
return;
}
$this->removalTaskId = $task->id;
$this->removalTaskTitle = $task->title;
$this->js("document.getElementById('remove-task-dialog').showModal()");
}
public function removeTask(RemoveTask $removeTask): void
{
$this->authorize('jobs.manage-tasks', $this->jobId);
if ($this->removalTaskId === null) {
return;
}
try {
$removeTask->execute($this->jobId, $this->removalTaskId);
$this->taskStatusMessage = __('jobs.tasks.removed', ['title' => $this->removalTaskTitle]);
} catch (TaskNotFound) {
$this->taskStatusMessage = __('jobs.tasks.not_found');
}
unset($this->tasks);
$this->reset('removalTaskId', 'removalTaskTitle');
$this->js("document.getElementById('remove-task-dialog').close(); document.getElementById('tasks-heading').focus()");
}
public function formatDate(?string $date): string
{
return $date === null ? __('jobs.not_set') : CarbonImmutable::parse($date)->format('j.n.Y');
@@ -188,6 +282,113 @@ new class extends Component
</dl>
</section>
<section id="tasks" aria-labelledby="tasks-heading" class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="tasks-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">{{ __('jobs.tasks.title') }}</h2>
@can('jobs.manage-tasks', $job->id)
@if ($job->status->allowsTasks())
<x-button :href="route('jobs.tasks.create', $job->id)" wire:navigate icon="plus" :text="__('jobs.tasks.new')" />
@endif
@endcan
</div>
@can('jobs.manage-tasks', $job->id)
@unless ($job->status->allowsTasks())
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.not_allowed_yet') }}</p>
@endunless
@endcan
<p role="status" aria-live="polite" class="text-sm">{{ $taskStatusMessage }}</p>
@if ($this->tasks === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.empty') }}</p>
@else
@php($canChangeStatus = Gate::allows('jobs.update-task-status', $job->id))
@php($canManageTasks = Gate::allows('jobs.manage-tasks', $job->id))
<ul class="space-y-3">
@foreach ($this->tasks as $task)
<li wire:key="task-{{ $task->id }}">
<article aria-labelledby="task-{{ $task->id }}-title" class="space-y-3 rounded-lg border border-zinc-200 p-4 text-sm dark:border-zinc-700">
<div class="flex flex-wrap items-start justify-between gap-3">
<h3 id="task-{{ $task->id }}-title" class="text-base font-medium break-words">{{ $task->title }}</h3>
<span>{{ __('jobs.tasks.statuses.'.$task->status->value) }}</span>
</div>
<dl class="grid gap-x-6 gap-y-1 sm:grid-cols-[max-content_1fr]">
<dt class="font-medium">{{ __('jobs.tasks.fields.work_type') }}</dt>
<dd>{{ $task->workType->name }}</dd>
<dt class="font-medium">{{ __('jobs.tasks.fields.assignees') }}</dt>
<dd>{{ $task->assignees === [] ? __('jobs.not_set') : collect($task->assignees)->pluck('name')->join(', ') }}</dd>
<dt class="font-medium">{{ __('jobs.tasks.fields.due_on') }}</dt>
<dd><x-jobs.due-date :date="$task->dueOn" :status="$task->status" /></dd>
<dt class="font-medium">{{ __('jobs.tasks.fields.estimated_hours') }}</dt>
<dd>{{ $task->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $task->estimatedHours).' h' }}</dd>
</dl>
@if ($task->description !== null)
<p class="whitespace-pre-line">{{ $task->description }}</p>
@endif
<div class="flex flex-wrap items-end gap-3">
@if ($canChangeStatus)
<div class="w-full sm:w-56">
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native
id="task-status-{{ $task->id }}"
wire:change="changeTaskStatus({{ $task->id }}, $event.target.value)"
:label="__('jobs.tasks.fields.status')"
:aria-label="__('jobs.tasks.status_of', ['title' => $task->title])"
>
@foreach (TaskStatus::cases() as $status)
<option value="{{ $status->value }}" @selected($status === $task->status)>{{ __('jobs.tasks.statuses.'.$status->value) }}</option>
@endforeach
</x-select.native>
</div>
@endif
@if ($canManageTasks)
<x-button
:href="route('jobs.tasks.edit', [$job->id, $task->id])"
wire:navigate
subtle
color="black"
sm
icon="pencil"
:text="__('jobs.edit')"
:aria-label="__('jobs.tasks.edit_named', ['title' => $task->title])"
/>
<x-button
wire:click="confirmTaskRemoval({{ $task->id }})"
subtle
color="black"
sm
icon="trash"
:text="__('customers.remove')"
:aria-label="__('jobs.tasks.remove_named', ['title' => $task->title])"
/>
@endif
</div>
</article>
</li>
@endforeach
</ul>
@endif
<x-confirm-dialog id="remove-task-dialog" :title="__('customers.removal.title')">
<p>
@if ($removalTaskId !== null)
{{ __('jobs.tasks.remove_question', ['title' => $removalTaskTitle]) }}
@endif
</p>
<x-slot:actions>
<x-button wire:click="removeTask" color="red" icon="trash" :text="__('customers.remove')" />
</x-slot:actions>
</x-confirm-dialog>
</section>
<section aria-labelledby="links-heading" class="space-y-3">
<h2 id="links-heading" class="text-xl font-semibold">{{ __('jobs.sections.links') }}</h2>
@@ -0,0 +1,218 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Application\UseCases\AddTask;
use App\Modules\Jobs\Application\UseCases\UpdateTask;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Presentation\Livewire\Forms\TaskForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (no {task}) and edit page (with {task}) of a job's task.
*/
new class extends Component
{
#[Locked]
public int $jobId;
#[Locked]
public ?int $taskId = null;
#[Locked]
public string $jobTitle = '';
/** @var list<int> */
#[Locked]
public array $serviceUnitIds = [];
/**
* The task's work type when editing, offered even if taken out of use.
*/
#[Locked]
public ?int $storedWorkTypeId = null;
public TaskForm $form;
public function mount(CustomerJobQueries $jobQueries, TaskQueries $taskQueries, int $job, ?int $task = null): void
{
$details = $jobQueries->findDetails($job);
abort_if($details === null, 404);
$this->authorize('jobs.manage-tasks', $details->id);
$this->jobId = $details->id;
$this->jobTitle = $details->number.' '.$details->name;
$this->serviceUnitIds = array_map(fn (NamedId $unit): int => $unit->id, $details->serviceUnits);
if ($task === null) {
abort_unless($details->status->allowsTasks(), 404);
$this->form->assignee_user_ids = [(string) auth()->id()];
return;
}
$summary = $taskQueries->findTask($details->id, $task);
abort_if($summary === null, 404);
$this->taskId = $summary->id;
$this->storedWorkTypeId = $summary->workType->id;
$this->form->fillFromSummary($summary);
}
/**
* Work types of the job's service units and the shared ones, grouped
* as "Unit – Service" for <optgroup>.
*
* @return array<string, list<array{id: int, name: string}>>
*/
#[Computed]
public function workTypeGroups(): array
{
$catalog = app(CatalogQueries::class);
$groups = [];
$seen = [];
foreach ($catalog->activeWorkTypesFor($this->serviceUnitIds) as $node) {
if ($node->workTypes !== []) {
$groups[$node->serviceUnit->name] = array_map(fn ($workType): array => ['id' => $workType->id, 'name' => $workType->name], $node->workTypes);
}
foreach ($node->services as $serviceNode) {
if ($serviceNode->workTypes !== []) {
$groups[$node->serviceUnit->name.' – '.$serviceNode->service->name] = array_map(fn ($workType): array => ['id' => $workType->id, 'name' => $workType->name], $serviceNode->workTypes);
}
}
}
foreach ($groups as $group) {
foreach ($group as $workType) {
$seen[$workType['id']] = true;
}
}
if ($this->storedWorkTypeId !== null && ! isset($seen[$this->storedWorkTypeId]) && ($stored = $catalog->findWorkType($this->storedWorkTypeId)) !== null) {
$groups[__('catalog.inactive')] = [['id' => $stored->id, 'name' => $stored->name]];
}
return $groups;
}
/**
* @return list<array{value: int, label: string, note: ?string}>
*/
#[Computed]
public function userOptions(): array
{
return array_map(fn ($user): array => [
'value' => $user->id,
'label' => $user->name,
'note' => $user->role === Role::Subcontractor ? __('users.roles.subcontractor') : null,
], app(UserAccountQueries::class)->activeUserOptions());
}
public function save(AddTask $addTask, UpdateTask $updateTask): void
{
$this->authorize('jobs.manage-tasks', $this->jobId);
$data = $this->form->toData();
try {
if ($this->taskId === null) {
$addTask->execute($this->jobId, $data, (int) auth()->id());
session()->flash('status', __('jobs.tasks.created', ['title' => trim($data->title)]));
} else {
$updateTask->execute($this->jobId, $this->taskId, $data);
session()->flash('status', __('jobs.tasks.updated', ['title' => trim($data->title)]));
}
} catch (CustomerJobNotFound|TaskNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirect(route('jobs.show', $this->jobId).'#tasks', navigate: true);
}
public function heading(): string
{
return __($this->taskId === null ? 'jobs.tasks.create_title' : 'jobs.tasks.edit_title');
}
public function render(): mixed
{
return $this->view()->title($this->heading().' – '.$this->jobTitle);
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
{{ __('jobs.tasks.job_label') }}:
<x-link :href="route('jobs.show', $jobId)" navigate>{{ $jobTitle }}</x-link>
</p>
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.title" :label="__('jobs.tasks.fields.title')" autocomplete="off" required />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model="form.work_type_id" :label="__('jobs.tasks.fields.work_type')" :aria-label="__('jobs.tasks.fields.work_type')" :hint="__('jobs.tasks.fields.work_type_description')" required>
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($this->workTypeGroups as $group => $workTypes)
<optgroup label="{{ $group }}">
@foreach ($workTypes as $workType)
<option value="{{ $workType['id'] }}">{{ $workType['name'] }}</option>
@endforeach
</optgroup>
@endforeach
</x-select.native>
<x-checkbox-group
:legend="__('jobs.tasks.fields.assignees')"
model="form.assignee_user_ids"
:options="$this->userOptions"
/>
<div class="grid gap-6 sm:grid-cols-3">
<x-select.native wire:model="form.status" :label="__('jobs.tasks.fields.status')" :aria-label="__('jobs.tasks.fields.status')">
@foreach (TaskStatus::cases() as $status)
<option value="{{ $status->value }}">{{ __('jobs.tasks.statuses.'.$status->value) }}</option>
@endforeach
</x-select.native>
<x-input wire:model="form.due_on" type="date" :label="__('jobs.tasks.fields.due_on')" />
<x-input
wire:model="form.estimated_hours"
type="number"
step="0.25"
min="0"
inputmode="decimal"
:label="__('jobs.tasks.fields.estimated_hours')"
/>
</div>
<x-textarea wire:model="form.description" :label="__('jobs.tasks.fields.description')" resize-auto />
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('jobs.save')" />
<x-button :href="route('jobs.show', $jobId).'#tasks'" wire:navigate subtle color="black" :text="__('jobs.cancel')" />
</div>
</form>
</div>
@@ -12,4 +12,6 @@ Route::middleware(['web', 'auth', 'can:jobs.view'])
Route::livewire('/board', 'jobs::board')->name('board');
Route::livewire('/{job}', 'jobs::show')->whereNumber('job')->name('show');
Route::livewire('/{job}/edit', 'jobs::form')->whereNumber('job')->middleware('can:jobs.manage')->name('edit');
Route::livewire('/{job}/tasks/create', 'jobs::task-form')->whereNumber('job')->name('tasks.create');
Route::livewire('/{job}/tasks/{task}/edit', 'jobs::task-form')->whereNumber(['job', 'task'])->name('tasks.edit');
});
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace Database\Factories;
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\DB;
/**
* @extends Factory<TaskModel>
*/
class TaskFactory extends Factory
{
protected $model = TaskModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'customer_job_id' => CustomerJobModel::factory()->state(['status' => 'order']),
'work_type_id' => fn () => WorkTypeModel::query()->value('id') ?? WorkTypeModel::factory()->create()->id,
'title' => fake()->sentence(3),
'status' => TaskStatus::Waiting,
'created_by' => User::factory(),
];
}
/**
* @param list<int> $userIds
*/
public function assignedTo(array $userIds): static
{
return $this->afterCreating(function (TaskModel $task) use ($userIds): void {
DB::table('task_assignees')->insert(array_map(fn (int $userId): array => ['task_id' => $task->id, 'user_id' => $userId], $userIds));
});
}
}
@@ -0,0 +1,45 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Tasks of customer jobs and their assignees. Checklists, comments and
* images come in phase 3.
*/
public function up(): void
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_job_id')->constrained()->cascadeOnDelete();
$table->foreignId('work_type_id')->constrained()->restrictOnDelete();
$table->string('title');
$table->text('description')->nullable();
$table->string('status', 20);
$table->date('due_on')->nullable();
$table->decimal('estimated_hours', 7, 2)->nullable();
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
$table->timestamps();
$table->index(['customer_job_id', 'status']);
});
Schema::create('task_assignees', function (Blueprint $table) {
$table->foreignId('task_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->restrictOnDelete();
$table->primary(['task_id', 'user_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('task_assignees');
Schema::dropIfExists('tasks');
}
};
+5 -4
View File
@@ -337,8 +337,8 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
- `customer_job_changes`: `customer_job_id`, `user_id`, `field`, `old_value`, `new_value`, `created_at`
**Tasks**
- `tasks`: `customer_job_id`, `work_type_id`, `title`, `description`, `status`, `due_on`, `estimated_hours`, `sort_order`, `created_by`
- `task_assignees`: `task_id`, `user_id`
- `tasks`: `customer_job_id`, `work_type_id`, `title`, `description`, `status`, `due_on`, `estimated_hours`, `created_by` *(olemassa)*
- `task_assignees`: `task_id`, `user_id` *(olemassa)*
- `task_checklist_items` *(V3)*: `task_id`, `text`, `is_done`, `sort_order`
- `task_comments` *(V3)*: `task_id`, `user_id`, `body`
- `task_images` *(V3)*: `task_id`, `user_id`, `path`, `original_name`
@@ -421,8 +421,9 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
- Sarakkeet tiloittain, arkistoitu pois. Kortin tila vaihdetaan vetämällä tai kortin valikosta (näppäimistö). Muutos ilmoitetaan `aria-live`-alueella.
- Puhelimella sarakkeet allekkain tai yksi sarake kerrallaan, ei vaakavieritystä sivulla.
### 16.7 Tehtävät
- Tehtäviä voi lisätä työlle tarjouspyyntö-tilasta alkaen. Tehtävälle valitaan työtehtävä työn palveluyksiköistä.
### 16.7 Tehtävät *(valmis)*
- Tehtäviä voi lisätä työlle tarjouspyyntö-tilasta alkaen (ei arkistoidulle työlle). Tehtävälle valitaan työtehtävä työn palveluyksiköistä tai kaikille yhteisistä; tekijöiksi oletuksena lisääjä.
- Tehtävät näkyvät työn sivulla: avoimet määräpäivän mukaan, valmiit viimeisenä. Tilan voi vaihtaa suoraan listalta (myös alihankkija liitettyjen töidensä tehtävissä); lisäys, muokkaus ja poisto ovat muille kuin alihankkijoille. Poisto vahvistetaan dialogissa, ja se estetään tuntikirjauksen osassa, jos tehtävällä on kirjauksia.
- Tehtävän tila: odottaa, työn alla, tarkastettavana, valmis. Myöhässä oleva tehtävä näytetään tekstillä ja kuvakkeella.
### 16.8 Tuntikirjaus
+40
View File
@@ -14,6 +14,46 @@ return [
'late' => 'Myöhässä',
'opens_in_new_tab' => 'avautuu uuteen välilehteen',
'tasks' => [
'title' => 'Tehtävät',
'new' => 'Lisää tehtävä',
'create_title' => 'Uusi tehtävä',
'edit_title' => 'Muokkaa tehtävää',
'job_label' => 'Asiakastyö',
'empty' => 'Ei tehtäviä.',
'not_allowed_yet' => 'Tehtäviä voi lisätä, kun työ on tarjouspyyntö-tilassa tai myöhemmässä tilassa.',
'created' => 'Tehtävä :title lisätty.',
'updated' => 'Tehtävä :title tallennettu.',
'removed' => 'Tehtävä :title poistettu.',
'not_found' => 'Tehtävää ei löytynyt. Päivitä sivu.',
'status_of' => 'Tila: :title',
'status_changed' => 'Tehtävän :title tila on nyt :status.',
'edit_named' => 'Muokkaa tehtävää :title',
'remove_named' => 'Poista tehtävä :title',
'remove_question' => 'Poistetaanko tehtävä :title? Poistoa ei voi perua.',
'fields' => [
'title' => 'Nimi',
'work_type' => 'Työtehtävä',
'work_type_description' => 'Työn palveluyksiköiden ja kaikille yhteiset työtehtävät.',
'assignees' => 'Tekijät',
'status' => 'Tila',
'due_on' => 'Määräpäivä',
'estimated_hours' => 'Arvioitu aika (h)',
'description' => 'Kuvaus',
],
'statuses' => [
'waiting' => 'Odottaa',
'in_progress' => 'Työn alla',
'in_review' => 'Tarkastettavana',
'done' => 'Valmis',
],
'errors' => [
'title_required' => 'Anna tehtävän nimi.',
'invalid_title' => 'Nimen pituus voi olla enintään 255 merkkiä.',
'work_type_required' => 'Valitse työtehtävä.',
],
],
'board' => [
'title' => 'Kanban',
'link' => 'Näytä Kanban-näkymänä',
+46
View File
@@ -2,8 +2,10 @@
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
@@ -145,3 +147,47 @@ it('moves a card by dragging it to another column', function () {
expect($this->job->fresh()->status->value)->toBe('order');
});
it('has no accessibility issues on a job with tasks and on the task form', function (string $page, string $device, string $colorScheme) {
$this->job->update(['status' => 'order']);
$workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole();
$task = TaskModel::factory()
->assignedTo([$this->user->id])
->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Kuvauspäivä', 'due_on' => now()->subDay()->toDateString(), 'estimated_hours' => 6]);
$url = match ($page) {
'job page' => route('jobs.show', $this->job->id),
'new task' => route('jobs.tasks.create', $this->job->id),
'edit task' => route('jobs.tasks.edit', [$this->job->id, $task->id]),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['job page', 'new task', 'edit task'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('changes a task status and removes a task with the keyboard', function () {
$this->job->update(['status' => 'order']);
$workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole();
$task = TaskModel::factory()
->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Kuvauspäivä']);
visit(route('jobs.show', $this->job->id))
->select('#task-status-'.$task->id, 'in_progress')
->assertSee('Tehtävän Kuvauspäivä tila on nyt Työn alla.')
->assertScript('document.activeElement.id', 'task-status-'.$task->id)
->keys('[aria-label="Poista tehtävä Kuvauspäivä"]', 'Enter')
->assertScript('document.getElementById("remove-task-dialog").open', true)
->assertScript('document.getElementById("remove-task-dialog").contains(document.activeElement)', true)
->click('#remove-task-dialog [wire\\:click="removeTask"]')
->assertSee('Tehtävä Kuvauspäivä poistettu.')
->assertScript('document.activeElement.id', 'tasks-heading');
});
+18 -1
View File
@@ -4,6 +4,7 @@ namespace Tests\Fakes;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\DTOs\ServiceSummary;
use App\Modules\Catalog\Application\DTOs\ServiceUnitNode;
use App\Modules\Catalog\Application\DTOs\ServiceUnitSummary;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
@@ -15,6 +16,14 @@ class FakeCatalogQueries implements CatalogQueries
/** @var array<int, ServiceUnitSummary> */
public array $serviceUnits = [];
/** @var array<int, list<WorkTypeSummary>> active work types directly under each unit */
public array $workTypes = [];
public function addWorkType(int $id, int $serviceUnitId, string $name): void
{
$this->workTypes[$serviceUnitId][] = new WorkTypeSummary($id, $serviceUnitId, null, $name, true);
}
public function addServiceUnit(int $id, string $name, bool $active = true, bool $shared = false): void
{
$this->serviceUnits[$id] = new ServiceUnitSummary($id, $name, $shared, $active);
@@ -32,7 +41,15 @@ class FakeCatalogQueries implements CatalogQueries
public function activeWorkTypesFor(array $serviceUnitIds): array
{
return [];
$nodes = [];
foreach ($this->serviceUnits as $id => $unit) {
if ($unit->isActive && (in_array($id, $serviceUnitIds, true) || $unit->isShared)) {
$nodes[] = new ServiceUnitNode($unit, [], $this->workTypes[$id] ?? []);
}
}
return $nodes;
}
public function findServiceUnit(int $id): ?ServiceUnitSummary
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace Tests\Fakes;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Entities\Task;
class InMemoryTaskRepository implements TaskRepository
{
/** @var array<int, Task> */
public array $tasks = [];
private int $nextId = 1;
public function findForJob(int $jobId, int $taskId): ?Task
{
$task = $this->tasks[$taskId] ?? null;
return $task !== null && $task->jobId() === $jobId ? clone $task : null;
}
public function save(Task $task): Task
{
$id = $task->id() ?? $this->nextId++;
$this->tasks[$id] = Task::reconstitute(
$id,
$task->jobId(),
$task->workTypeId(),
$task->title(),
$task->description(),
$task->status(),
$task->dueOn(),
$task->estimatedHours(),
$task->assigneeUserIds(),
$task->createdBy(),
);
return clone $this->tasks[$id];
}
public function delete(Task $task): void
{
unset($this->tasks[$task->id()]);
}
}
+119
View File
@@ -0,0 +1,119 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->employee = User::factory()->create(['name' => 'Eero Työntekijä']);
$this->actingAs($this->employee);
$this->marketing = ServiceUnitModel::query()->where('name', 'Markkinointi')->sole();
$this->job = CustomerJobModel::factory()->create(['name' => 'Kampanja', 'status' => 'order', 'responsible_user_id' => $this->employee->id]);
DB::table('customer_job_service_unit')->where('customer_job_id', $this->job->id)->update(['service_unit_id' => $this->marketing->id]);
$this->graphic = WorkTypeModel::query()->where('name', 'graafinen työ')->sole();
$this->planning = WorkTypeModel::query()->where('name', 'suunnittelu')->sole();
});
it('adds a task with work types of the job and the shared ones on offer', function () {
$this->get(route('jobs.tasks.create', $this->job->id))
->assertOk()
->assertSee('graafinen työ')
->assertSee('suunnittelu')
->assertDontSee('painotyö');
Livewire::test('jobs::task-form', ['job' => $this->job->id])
->assertSet('form.assignee_user_ids', [(string) $this->employee->id])
->set('form.title', 'Mainoskuvat')
->set('form.work_type_id', (string) $this->graphic->id)
->set('form.due_on', '2026-05-20')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('jobs.show', $this->job->id).'#tasks');
$task = TaskModel::query()->sole();
expect($task->work_type_id)->toBe($this->graphic->id)
->and(DB::table('task_assignees')->where('task_id', $task->id)->pluck('user_id')->all())->toBe([$this->employee->id]);
$this->get(route('jobs.show', $this->job->id))
->assertSee('Mainoskuvat')
->assertSee('graafinen työ')
->assertSee('Eero Työntekijä');
});
it('shows Finnish errors on the task form', function () {
Livewire::test('jobs::task-form', ['job' => $this->job->id])
->call('save')
->assertHasErrors(['form.title', 'form.work_type_id'])
->assertSee('Anna tehtävän nimi.')
->assertSee('Valitse työtehtävä.');
});
it('does not add tasks before the job is a quote request', function () {
$this->job->update(['status' => 'tentative']);
$this->get(route('jobs.tasks.create', $this->job->id))->assertNotFound();
$this->get(route('jobs.show', $this->job->id))
->assertSee('Tehtäviä voi lisätä, kun työ on tarjouspyyntö-tilassa')
->assertDontSee('Lisää tehtävä');
});
it('edits, changes the status of and removes a task on the job page', function () {
$task = TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Mainoskuvat']);
Livewire::test('jobs::task-form', ['job' => $this->job->id, 'task' => $task->id])
->assertSet('form.title', 'Mainoskuvat')
->set('form.work_type_id', (string) $this->planning->id)
->call('save')
->assertHasNoErrors();
Livewire::test('jobs::show', ['job' => $this->job->id])
->call('changeTaskStatus', $task->id, 'in_review')
->assertSee('Tehtävän Mainoskuvat tila on nyt Tarkastettavana.')
->call('confirmTaskRemoval', $task->id)
->assertSee('Poistetaanko tehtävä Mainoskuvat?')
->call('removeTask')
->assertSee('Tehtävä Mainoskuvat poistettu.');
expect(TaskModel::query()->count())->toBe(0);
});
it('counts task assignees as members in my jobs', function () {
$colleague = User::factory()->create();
TaskModel::factory()->assignedTo([$colleague->id])->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id]);
$this->actingAs($colleague);
Livewire::test('jobs::index')->assertSee('Kampanja');
});
it('lets a subcontractor change task statuses on their jobs, but not add or change tasks', function () {
$subcontractor = User::factory()->subcontractor()->create();
$task = TaskModel::factory()->assignedTo([$subcontractor->id])->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id]);
$this->actingAs($subcontractor);
$this->get(route('jobs.show', $this->job->id))->assertOk()->assertDontSee('Lisää tehtävä');
$this->get(route('jobs.tasks.create', $this->job->id))->assertForbidden();
$this->get(route('jobs.tasks.edit', [$this->job->id, $task->id]))->assertForbidden();
Livewire::test('jobs::show', ['job' => $this->job->id])
->call('changeTaskStatus', $task->id, 'done')
->assertHasNoErrors()
->call('confirmTaskRemoval', $task->id)
->assertForbidden();
expect($task->fresh()->status->value)->toBe('done');
});
it('returns 404 for a task of another job', function () {
$other = TaskModel::factory()->create();
$this->get(route('jobs.tasks.edit', [$this->job->id, $other->id]))->assertNotFound();
});
@@ -0,0 +1,125 @@
<?php
use App\Modules\Jobs\Application\DTOs\CustomerJobData;
use App\Modules\Jobs\Application\DTOs\TaskData;
use App\Modules\Jobs\Application\Services\JobDetailsFactory;
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
use App\Modules\Jobs\Application\UseCases\AddTask;
use App\Modules\Jobs\Application\UseCases\ChangeJobStatus;
use App\Modules\Jobs\Application\UseCases\ChangeTaskStatus;
use App\Modules\Jobs\Application\UseCases\CreateCustomerJob;
use App\Modules\Jobs\Application\UseCases\RemoveTask;
use App\Modules\Jobs\Application\UseCases\UpdateTask;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskTitle;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use Tests\Fakes\FakeCatalogQueries;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeCustomerQueries;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\FakeUserAccountQueries;
use Tests\Fakes\InMemoryCustomerJobRepository;
use Tests\Fakes\InMemoryTaskRepository;
beforeEach(function () {
$this->jobs = new InMemoryCustomerJobRepository;
$this->tasks = new InMemoryTaskRepository;
$customers = new FakeCustomerQueries;
$this->catalog = new FakeCatalogQueries;
$this->users = new FakeUserAccountQueries;
$transactions = new FakeTransactionManager;
$customers->customers = [1 => 'Mainos Oy'];
$this->catalog->addServiceUnit(1, 'Markkinointi');
$this->catalog->addServiceUnit(2, 'Painotuotanto');
$this->catalog->addServiceUnit(9, 'Kaikille yhteiset', shared: true);
$this->catalog->addWorkType(11, 1, 'graafinen työ');
$this->catalog->addWorkType(21, 2, 'painotyö');
$this->catalog->addWorkType(91, 9, 'suunnittelu');
$this->users->addUser(10, 'Eero');
$this->users->addUser(12, 'Pois', active: false);
$createJob = new CreateCustomerJob($this->jobs, $this->jobs, new JobDetailsFactory($customers, $this->catalog, $this->users), $transactions, new FakeClock(new DateTimeImmutable('2026-05-01')));
$this->jobId = $createJob->execute(new CustomerJobData('Kampanja', 1, [1], 10, 'one_off', 'quote_request', 'normal'), 10);
$this->tentativeJobId = $createJob->execute(new CustomerJobData('Alustava', 1, [1], 10, 'one_off', 'tentative', 'normal'), 10);
$checker = new TaskReferenceChecker($this->catalog, $this->users);
$this->addTask = new AddTask($this->jobs, $this->tasks, $checker, $transactions);
$this->updateTask = new UpdateTask($this->jobs, $this->tasks, $checker, $transactions);
$this->changeTaskStatus = new ChangeTaskStatus($this->tasks, $transactions);
$this->removeTask = new RemoveTask($this->tasks, $transactions);
$this->changeJobStatus = new ChangeJobStatus($this->jobs, $transactions);
});
it('allows tasks from a quote request on, not before and not when archived', function () {
expect(JobStatus::Tentative->allowsTasks())->toBeFalse()
->and(JobStatus::Prospect->allowsTasks())->toBeFalse()
->and(JobStatus::Archived->allowsTasks())->toBeFalse()
->and(JobStatus::QuoteRequest->allowsTasks())->toBeTrue()
->and(JobStatus::Billed->allowsTasks())->toBeTrue()
->and(fn () => new TaskTitle(' '))->toThrow(InvalidTaskTitle::class);
expect(fn () => $this->addTask->execute($this->tentativeJobId, new TaskData('Luonnos', 11, 'waiting'), 10))
->toThrow(TasksNotAllowedYet::class);
});
it('adds a task with a work type of the job or a shared one', function () {
$taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting', dueOn: '2026-05-20', estimatedHours: '3,5', assigneeUserIds: [10]), 10);
$this->addTask->execute($this->jobId, new TaskData('Suunnittelupalaveri', 91, 'waiting'), 10);
$task = $this->tasks->findForJob($this->jobId, $taskId);
expect($task?->dueOn()?->format('Y-m-d'))->toBe('2026-05-20')
->and($task?->estimatedHours()?->format())->toBe('3.5')
->and($task?->assigneeUserIds())->toBe([10])
->and($this->tasks->tasks)->toHaveCount(2);
});
it('rejects a work type of another unit and an inactive assignee', function (int $workTypeId, array $assignees, string $field) {
try {
$this->addTask->execute($this->jobId, new TaskData('Työ', $workTypeId, 'waiting', assigneeUserIds: $assignees), 10);
$this->fail('No exception');
} catch (InvalidTaskReference $exception) {
expect($exception->field)->toBe($field);
}
})->with([
'work type of another unit' => [21, [], 'work_type'],
'inactive assignee' => [11, [12], 'assignees'],
]);
it('changes, moves through statuses and removes a task', function () {
$taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10);
$this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat ja banneri', 11, 'in_progress'));
$this->changeTaskStatus->execute($this->jobId, $taskId, TaskStatus::Done);
$task = $this->tasks->findForJob($this->jobId, $taskId);
expect($task?->title()->value)->toBe('Mainoskuvat ja banneri')
->and($task?->status())->toBe(TaskStatus::Done);
$this->removeTask->execute($this->jobId, $taskId);
expect($this->tasks->tasks)->toBeEmpty();
});
it('can still change a task after the job moved back to an earlier status', function () {
$taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10);
$this->changeJobStatus->execute($this->jobId, JobStatus::Tentative, 10);
$this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat', 11, 'in_review'));
expect($this->tasks->findForJob($this->jobId, $taskId)?->status())->toBe(TaskStatus::InReview);
});
it('does not touch a task of another job', function (string $action) {
$taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10);
match ($action) {
'update' => $this->updateTask->execute($this->tentativeJobId, $taskId, new TaskData('X', 11, 'done')),
'status' => $this->changeTaskStatus->execute($this->tentativeJobId, $taskId, TaskStatus::Done),
'remove' => $this->removeTask->execute($this->tentativeJobId, $taskId),
};
})->throws(TaskNotFound::class)->with(['update', 'status', 'remove']);