Give tasks one assignee and members, and schedule template tasks to due dates

- A task now has one optional assignee (tasks.assignee_user_id), whose
  calendar row it is on and whose days its estimate books, and members
  (task_members) who see it among their own jobs and in the weekly sheet
  but get no bookings. A migration moves existing assignees over: the one
  with most booked time becomes the assignee, the others members.
- Adding tasks from a workflow template asks for each step's assignee and,
  by default, schedules tasks with a due date to end on it, booking the
  estimate backwards from the due date (not before today); what does not
  fit runs past the due date and is reported as late.
- The task calendar leaves quick sale tasks out of the unscheduled list,
  shows a bar's job details in a popover on hover and focus, and shows the
  day load on its own grid line.
- The template table stacks its cells on narrow screens to reflow at 320 px.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 19:01:11 +02:00
co-authored by Claude Opus 5.5
parent b4f2f1cfaa
commit 18598cc08e
45 changed files with 1133 additions and 248 deletions
@@ -22,7 +22,8 @@ interface TaskCalendarQueries
/**
* Tasks that are not done and have no planned period, on jobs that are
* not archived, by due date.
* not archived, by due date. Tasks of the quick sale jobs are left out:
* they hold quick sale hours and are not scheduled.
*
* @return list<CalendarTask>
*/
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* One assignee's part of a scheduled task: the first and last booked day
* The assignee's part of a scheduled task: the first and last booked day
* (null when the task books no time, e.g. without an estimate) and the
* booked minutes.
*/
@@ -4,15 +4,17 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* A task as the task calendar shows it. Dates are Y-m-d.
* A task as the task calendar shows it, with the basic details of its job
* for the bar's info popover. Dates are Y-m-d.
*/
final readonly class CalendarTask
{
/**
* @param list<CalendarAssignment> $assignments One per assignee.
* @param ?CalendarAssignment $assignment The assignee's part; null without an assignee.
*/
public function __construct(
public int $taskId,
@@ -25,17 +27,17 @@ final readonly class CalendarTask
public ?string $estimatedHours,
public ?string $plannedFrom,
public ?string $plannedTo,
public array $assignments,
public ?CalendarAssignment $assignment,
public ?string $customerName = null,
public ?JobStatus $jobStatus = null,
public ?string $jobDueOn = null,
public ?string $responsibleName = null,
public ?string $workTypeName = null,
public ?string $description = null,
) {}
public function assignmentOf(int $userId): ?CalendarAssignment
{
foreach ($this->assignments as $assignment) {
if ($assignment->userId === $userId) {
return $assignment;
}
}
return null;
return $this->assignment?->userId === $userId ? $this->assignment : null;
}
}
@@ -11,7 +11,7 @@ namespace App\Modules\Jobs\Application\DTOs;
final readonly class TaskData
{
/**
* @param list<int> $assigneeUserIds
* @param list<int> $memberUserIds Members see the task among their own; only the assignee gets calendar bookings.
*/
public function __construct(
public string $title,
@@ -20,7 +20,8 @@ final readonly class TaskData
public ?string $description = null,
public ?string $dueOn = null,
public ?string $estimatedHours = null,
public array $assigneeUserIds = [],
public ?int $assigneeUserId = null,
public array $memberUserIds = [],
public ?string $plannedFrom = null,
public ?string $plannedTo = null,
) {}
@@ -12,7 +12,7 @@ use App\Modules\Jobs\Domain\Enums\TaskStatus;
final readonly class TaskSummary
{
/**
* @param list<NamedId> $assignees
* @param list<NamedId> $members
*/
public function __construct(
public int $id,
@@ -23,7 +23,8 @@ final readonly class TaskSummary
public ?string $dueOn,
public ?string $estimatedHours,
public NamedId $workType,
public array $assignees,
public ?NamedId $assignee,
public array $members,
public ?string $plannedFrom = null,
public ?string $plannedTo = null,
) {}
@@ -5,13 +5,14 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* Due date (Y-m-d) and estimated hours ("1,5") entered for the task of one
* workflow template step. Both are optional.
* Due date (Y-m-d), estimated hours ("1,5") and assignee entered for the
* task of one workflow template step. All are optional.
*/
final readonly class TemplateTaskSchedule
{
public function __construct(
public ?string $dueOn = null,
public ?string $estimatedHours = null,
public ?int $assigneeUserId = null,
) {}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* What adding tasks from a workflow template did: how many tasks were
* added, how many of them were scheduled to their due dates, and how many
* of those end after the due date because their assignee's days were full.
*/
final readonly class TemplateTasksResult
{
public function __construct(
public int $added,
public int $scheduled = 0,
public int $late = 0,
) {}
}
@@ -11,8 +11,8 @@ use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* Lays scheduled tasks out on the task calendar's rows: one row per
* person (a task with several assignees is on each of their rows) and a
* row for tasks without an assignee. Overlapping bars get their own lanes.
* person (a task is on its assignee's row; members do not see it there)
* and a row for tasks without an assignee. Overlapping bars get their own lanes.
*/
final class TaskCalendarLayout
{
@@ -61,7 +61,7 @@ final class TaskCalendarLayout
}
if ($userId === null) {
if ($task->assignments !== []) {
if ($task->assignment !== null) {
return null;
}
@@ -13,7 +13,7 @@ use DateInterval;
use DateTimeImmutable;
/**
* Books a saved task's estimate from each assignee's days with the
* Books a saved task's estimate from its assignee's days with the
* TaskScheduler, using the holidays in use and the daily maximum
* (setting `jobs.daily_capacity_hours`, 8 h by default). When the days
* are full, the task's planned end moves later.
@@ -41,8 +41,8 @@ final class TaskPlanner
}
/**
* Rebooks the task's assignees and, if their days were full, moves the
* task's planned end later. The task must be saved (have an id);
* Rebooks the task's assignee (members get no bookings) and, if their
* days were full, moves the task's planned end later. The task must be saved (have an id);
* save it again afterwards.
*
* @return bool Whether the planned end moved later.
@@ -59,33 +59,27 @@ final class TaskPlanner
return false;
}
$this->bookings->deleteForTask($taskId, $task->assigneeUserIds());
$userId = $task->assigneeUserId();
$this->bookings->deleteForTask($taskId, $userId === null ? [] : [$userId]);
$minutes = (int) round(($task->estimatedHours()->value ?? 0) * 60);
$lookahead = $to->add(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d');
$holidays = $this->holidays->activeDatesBetween($from->format('Y-m-d'), $lookahead);
$capacity = $this->capacityMinutes();
$end = $to;
foreach ($task->assigneeUserIds() as $userId) {
$schedule = TaskScheduler::schedule(
$from,
$to,
$minutes,
$this->bookings->otherOpenMinutes($userId, $from->format('Y-m-d'), $lookahead, $taskId),
$capacity,
$holidays,
);
$this->bookings->replaceFor($taskId, $userId, $schedule->minutesByDay);
if ($schedule->end > $end) {
$end = $schedule->end;
}
if ($userId === null) {
return false;
}
if ($end > $to) {
$task->schedule($from, $end);
$lookahead = $to->add(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d');
$schedule = TaskScheduler::schedule(
$from,
$to,
self::minutesOf($task),
$this->bookings->otherOpenMinutes($userId, $from->format('Y-m-d'), $lookahead, $taskId),
$this->capacityMinutes(),
$this->holidays->activeDatesBetween($from->format('Y-m-d'), $lookahead),
);
$this->bookings->replaceFor($taskId, $userId, $schedule->minutesByDay);
if ($schedule->end > $to) {
$task->schedule($from, $schedule->end);
return true;
}
@@ -93,14 +87,69 @@ final class TaskPlanner
return false;
}
/**
* Schedules a saved task to end on its due date: the estimate is booked
* from the assignee's free time on the due date and the working days
* before it, not before the earliest day (today); what does not fit
* goes after the due date. Without an assignee nothing is booked and the
* task starts as many working days before as the estimate needs. Save
* the task afterwards.
*
* @return bool Whether the task ends after its due date.
*/
public function planBackwards(Task $task, DateTimeImmutable $earliest): bool
{
$taskId = (int) $task->id();
$due = $task->dueOn();
if ($due === null) {
return false;
}
$userId = $task->assigneeUserId();
$minutes = self::minutesOf($task);
$start = min($due, $earliest)->sub(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d');
$lookahead = max($due, $earliest)->add(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d');
$holidays = $this->holidays->activeDatesBetween($start, $lookahead);
$this->bookings->deleteForTask($taskId);
if ($userId === null) {
$task->schedule(TaskScheduler::defaultStart($due, $minutes, $this->capacityMinutes(), $holidays, $earliest), $due);
return false;
}
$schedule = TaskScheduler::scheduleBackwards(
$due,
$minutes,
$this->bookings->otherOpenMinutes($userId, $start, $lookahead, $taskId),
$this->capacityMinutes(),
$holidays,
$earliest,
);
$this->bookings->replaceFor($taskId, $userId, $schedule->minutesByDay);
$firstDay = array_key_first($schedule->minutesByDay);
$task->schedule($firstDay === null ? $due : new DateTimeImmutable($firstDay), $schedule->end);
return $schedule->extended;
}
/**
* The end of a task placed on a day without an end (TaskScheduler::defaultEnd).
*/
public function defaultEnd(DateTimeImmutable $from, Task $task): DateTimeImmutable
{
$minutes = (int) round(($task->estimatedHours()->value ?? 0) * 60);
$minutes = self::minutesOf($task);
$lookahead = $from->add(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d');
return TaskScheduler::defaultEnd($from, $minutes, $this->capacityMinutes(), $this->holidays->activeDatesBetween($from->format('Y-m-d'), $lookahead));
}
private static function minutesOf(Task $task): int
{
return (int) round(($task->estimatedHours()->value ?? 0) * 60);
}
}
@@ -12,7 +12,8 @@ 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.
* the shared work types) and is in use, and that its assignee and members
* are active.
* What the task already has stays allowed after being taken out of use.
*/
final class TaskReferenceChecker
@@ -23,11 +24,11 @@ final class TaskReferenceChecker
) {}
/**
* @param list<int> $assigneeUserIds
* @param list<int> $memberUserIds
*
* @throws InvalidTaskReference
*/
public function check(CustomerJob $job, int $workTypeId, array $assigneeUserIds, ?Task $current = null): void
public function check(CustomerJob $job, int $workTypeId, ?int $assigneeUserId, array $memberUserIds = [], ?Task $current = null): void
{
if ($workTypeId !== $current?->workTypeId() && ! in_array($workTypeId, $this->workTypeIdsFor($job), true)) {
throw new InvalidTaskReference('work_type');
@@ -35,9 +36,16 @@ final class TaskReferenceChecker
$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');
$currentIds = $current === null ? [] : [$current->assigneeUserId(), ...$current->memberUserIds()];
$allowed = fn (int $userId): bool => in_array($userId, $activeIds, true) || in_array($userId, $currentIds, true);
if ($assigneeUserId !== null && ! $allowed($assigneeUserId)) {
throw new InvalidTaskReference('assignee');
}
foreach ($memberUserIds as $userId) {
if (! $allowed($userId)) {
throw new InvalidTaskReference('members');
}
}
}
@@ -42,7 +42,7 @@ final class AddTask
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);
$this->references->check($job, $data->workTypeId, $data->assigneeUserId, $data->memberUserIds);
$task = Task::create(
$jobId,
@@ -53,7 +53,8 @@ final class AddTask
TaskStatus::from($data->status),
TaskInput::date($data->dueOn),
TaskInput::hours($data->estimatedHours),
$data->assigneeUserIds,
$data->assigneeUserId,
$data->memberUserIds,
$actorUserId,
TaskInput::date($data->plannedFrom),
TaskInput::date($data->plannedTo),
@@ -7,6 +7,8 @@ namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails;
use App\Modules\Jobs\Application\DTOs\TemplateTaskSchedule;
use App\Modules\Jobs\Application\DTOs\TemplateTasksResult;
use App\Modules\Jobs\Application\Services\TaskPlanner;
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
@@ -19,11 +21,14 @@ use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\Exceptions\WorkflowTemplateNotAvailable;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Makes a task of every step of a workflow template, in the template's
* order: waiting, with the step's work type and the due date and estimate
* entered for it, assigned to the user who adds them. The tasks are
* order: waiting, with the step's work type and the due date, estimate and
* assignee entered for it (without an entry, the adder is the assignee).
* When asked, a task with a due date is scheduled to end on it, booked
* backwards from the due date (TaskPlanner::planBackwards). The tasks are
* copies, so later changes to the template do not touch them.
*/
final class AddTasksFromWorkflowTemplate
@@ -33,32 +38,39 @@ final class AddTasksFromWorkflowTemplate
private TaskRepository $tasks,
private WorkflowTemplateQueries $templates,
private TaskReferenceChecker $references,
private TaskPlanner $planner,
private Clock $clock,
private TransactionManager $transactions,
) {}
/**
* @param list<TemplateTaskSchedule> $schedules In step order; a missing one leaves the task without a due date and estimate.
* @return int How many tasks were added.
* @param list<TemplateTaskSchedule> $schedules In step order; a missing one leaves the task without a due date and estimate, assigned to the adder.
* @param bool $scheduleToDueDates Whether tasks with a due date are scheduled to end on it.
*
* @throws CustomerJobNotFound
* @throws InvalidEstimatedHours
* @throws TasksNotAllowedYet
* @throws WorkflowTemplateNotAvailable
* @throws InvalidTaskReference when a step's work type is not available for the job
* @throws InvalidTaskReference when a step's work type is not available for the job, or the assignee is not active
*/
public function execute(int $jobId, int $templateId, int $actorUserId, array $schedules = []): int
public function execute(int $jobId, int $templateId, int $actorUserId, array $schedules = [], bool $scheduleToDueDates = false): TemplateTasksResult
{
$dueDates = array_map(fn (TemplateTaskSchedule $schedule) => TaskInput::date($schedule->dueOn), $schedules);
$estimates = array_map(fn (TemplateTaskSchedule $schedule) => TaskInput::hours($schedule->estimatedHours), $schedules);
$assignees = array_map(fn (TemplateTaskSchedule $schedule): ?int => $schedule->assigneeUserId, $schedules);
return $this->transactions->run(function () use ($jobId, $templateId, $actorUserId, $dueDates, $estimates): int {
return $this->transactions->run(function () use ($jobId, $templateId, $actorUserId, $dueDates, $estimates, $assignees, $scheduleToDueDates): TemplateTasksResult {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$template = $this->availableTemplate($templateId, $job->details()->serviceUnitIds);
$today = $this->clock->today();
$scheduled = 0;
$late = 0;
foreach ($template->steps as $index => $step) {
$this->references->check($job, $step->effectiveWorkTypeId, [$actorUserId]);
$assigneeUserId = array_key_exists($index, $assignees) ? $assignees[$index] : $actorUserId;
$this->references->check($job, $step->effectiveWorkTypeId, $assigneeUserId);
$this->tasks->save(Task::create(
$task = $this->tasks->save(Task::create(
$jobId,
$job->details()->status,
$step->effectiveWorkTypeId,
@@ -67,12 +79,19 @@ final class AddTasksFromWorkflowTemplate
TaskStatus::Waiting,
$dueDates[$index] ?? null,
$estimates[$index] ?? null,
[$actorUserId],
$assigneeUserId,
[],
$actorUserId,
));
if ($scheduleToDueDates && $task->dueOn() !== null) {
$late += $this->planner->planBackwards($task, $today) ? 1 : 0;
$scheduled++;
$this->tasks->save($task);
}
}
return count($template->steps);
return new TemplateTasksResult(count($template->steps), $scheduled, $late);
});
}
@@ -72,6 +72,7 @@ final class ProvideQuickSaleTask
TaskStatus::InProgress,
null,
null,
null,
[],
$actorUserId,
));
@@ -17,8 +17,8 @@ use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Moves a task in the task calendar: a new planned period, and possibly
* from one person's row to another's (the person on the row it left is
* replaced as an assignee; null is the "no assignee" row). Without an
* from one person's row to another's (the person on the new row becomes
* the assignee; null is the "no assignee" row; members stay). Without an
* end, the task lasts as many working days as its estimate needs.
*/
final class ScheduleTask
@@ -46,19 +46,11 @@ final class ScheduleTask
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
$assignees = $task->assigneeUserIds();
if ($fromUserId !== $toUserId) {
$assignees = array_values(array_filter($assignees, fn (int $userId): bool => $userId !== $fromUserId));
if ($toUserId !== null) {
$assignees[] = $toUserId;
}
$this->references->check($job, $task->workTypeId(), $toUserId, [], $task);
$task->assignTo($toUserId);
}
$this->references->check($job, $task->workTypeId(), $assignees, $task);
$task->changeAssignees($assignees);
$task->schedule($from, $to ?? $this->planner->defaultEnd($from, $task));
$task = $this->tasks->save($task);
@@ -42,7 +42,7 @@ final class UpdateTask
$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);
$this->references->check($job, $data->workTypeId, $data->assigneeUserId, $data->memberUserIds, $task);
$before = self::planningInput($task);
@@ -53,7 +53,8 @@ final class UpdateTask
TaskStatus::from($data->status),
TaskInput::date($data->dueOn),
TaskInput::hours($data->estimatedHours),
$data->assigneeUserIds,
$data->assigneeUserId,
$data->memberUserIds,
);
$task->schedule(TaskInput::date($data->plannedFrom), TaskInput::date($data->plannedTo));
@@ -68,7 +69,7 @@ final class UpdateTask
}
/**
* @return array{0: ?string, 1: ?string, 2: ?float, 3: list<int>}
* @return array{0: ?string, 1: ?string, 2: ?float, 3: ?int}
*/
private static function planningInput(Task $task): array
{
@@ -76,7 +77,7 @@ final class UpdateTask
$task->plannedFrom()?->format('Y-m-d'),
$task->plannedTo()?->format('Y-m-d'),
$task->estimatedHours()?->value,
$task->assigneeUserIds(),
$task->assigneeUserId(),
];
}
}
+38 -22
View File
@@ -13,14 +13,16 @@ 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.
* Its planned schedule (planned from–to) places it in the task calendar.
* A task (tehtävä) of a customer job: one step of the work under one work
* type. Its assignee (tekijä) does it: the planned schedule (planned
* from–to) places it on the assignee's row of the task calendar and books
* the estimate from their days. Members (jäsenet) see the task among their
* own but get no bookings. Time entries are recorded on tasks.
*/
final class Task
{
/**
* @param list<int> $assigneeUserIds
* @param list<int> $memberUserIds
*/
private function __construct(
private ?int $id,
@@ -31,17 +33,18 @@ final class Task
private TaskStatus $status,
private ?DateTimeImmutable $dueOn,
private ?EstimatedHours $estimatedHours,
private array $assigneeUserIds,
private ?int $assigneeUserId,
private array $memberUserIds,
private int $createdBy,
private ?DateTimeImmutable $plannedFrom = null,
private ?DateTimeImmutable $plannedTo = null,
) {
$this->assigneeUserIds = self::normaliseIds($assigneeUserIds);
$this->memberUserIds = self::members($memberUserIds, $assigneeUserId);
self::checkPlan($plannedFrom, $plannedTo);
}
/**
* @param list<int> $assigneeUserIds
* @param list<int> $memberUserIds
*
* @throws TasksNotAllowedYet
* @throws PlanEndsBeforeStart
@@ -55,7 +58,8 @@ final class Task
TaskStatus $status,
?DateTimeImmutable $dueOn,
?EstimatedHours $estimatedHours,
array $assigneeUserIds,
?int $assigneeUserId,
array $memberUserIds,
int $createdBy,
?DateTimeImmutable $plannedFrom = null,
?DateTimeImmutable $plannedTo = null,
@@ -64,11 +68,11 @@ final class Task
throw new TasksNotAllowedYet;
}
return new self(null, $jobId, $workTypeId, $title, self::text($description), $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy, ...self::plan($plannedFrom, $plannedTo));
return new self(null, $jobId, $workTypeId, $title, self::text($description), $status, $dueOn, $estimatedHours, $assigneeUserId, $memberUserIds, $createdBy, ...self::plan($plannedFrom, $plannedTo));
}
/**
* @param list<int> $assigneeUserIds
* @param list<int> $memberUserIds
*/
public static function reconstitute(
int $id,
@@ -79,16 +83,17 @@ final class Task
TaskStatus $status,
?DateTimeImmutable $dueOn,
?EstimatedHours $estimatedHours,
array $assigneeUserIds,
?int $assigneeUserId,
array $memberUserIds,
int $createdBy,
?DateTimeImmutable $plannedFrom = null,
?DateTimeImmutable $plannedTo = null,
): self {
return new self($id, $jobId, $workTypeId, $title, $description, $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy, $plannedFrom, $plannedTo);
return new self($id, $jobId, $workTypeId, $title, $description, $status, $dueOn, $estimatedHours, $assigneeUserId, $memberUserIds, $createdBy, $plannedFrom, $plannedTo);
}
/**
* @param list<int> $assigneeUserIds
* @param list<int> $memberUserIds
*/
public function changeDetails(
int $workTypeId,
@@ -97,7 +102,8 @@ final class Task
TaskStatus $status,
?DateTimeImmutable $dueOn,
?EstimatedHours $estimatedHours,
array $assigneeUserIds,
?int $assigneeUserId,
array $memberUserIds,
): void {
$this->workTypeId = $workTypeId;
$this->title = $title;
@@ -105,7 +111,8 @@ final class Task
$this->status = $status;
$this->dueOn = $dueOn;
$this->estimatedHours = $estimatedHours;
$this->assigneeUserIds = self::normaliseIds($assigneeUserIds);
$this->assigneeUserId = $assigneeUserId;
$this->memberUserIds = self::members($memberUserIds, $assigneeUserId);
}
public function changeStatus(TaskStatus $status): void
@@ -125,11 +132,13 @@ final class Task
}
/**
* @param list<int> $assigneeUserIds
* Makes the user the assignee (null: no assignee). A member who becomes
* the assignee is no longer a member; the earlier assignee is dropped.
*/
public function changeAssignees(array $assigneeUserIds): void
public function assignTo(?int $userId): void
{
$this->assigneeUserIds = self::normaliseIds($assigneeUserIds);
$this->assigneeUserId = $userId;
$this->memberUserIds = self::members($this->memberUserIds, $userId);
}
public function id(): ?int
@@ -187,12 +196,17 @@ final class Task
return $this->plannedFrom !== null;
}
public function assigneeUserId(): ?int
{
return $this->assigneeUserId;
}
/**
* @return list<int>
*/
public function assigneeUserIds(): array
public function memberUserIds(): array
{
return $this->assigneeUserIds;
return $this->memberUserIds;
}
public function createdBy(): int
@@ -201,12 +215,14 @@ final class Task
}
/**
* The members sorted, without duplicates and without the assignee.
*
* @param list<int> $ids
* @return list<int>
*/
private static function normaliseIds(array $ids): array
private static function members(array $ids, ?int $assigneeUserId): array
{
$ids = array_values(array_unique($ids));
$ids = array_values(array_unique(array_filter($ids, fn (int $id): bool => $id !== $assigneeUserId)));
sort($ids);
return $ids;
@@ -9,7 +9,7 @@ use DateInterval;
use DateTimeImmutable;
/**
* Books a task's estimated time from an assignee's days (spec 18.3).
* Books a task's estimated time from its assignee's days (spec 18.3).
*
* The estimate is split evenly over the working days of the planned
* period (not Saturdays, Sundays or holidays); a period of only such days
@@ -65,10 +65,36 @@ final class TaskScheduler
}
}
$day = $to;
return self::finish($booked, self::bookAfter($to, $carry, $otherMinutes, $capacityMinutes, $holidaySet), $to);
}
for ($extra = 0; $carry > 0 && $extra < self::MAX_EXTRA_DAYS; $extra++) {
$day = $day->add(new DateInterval('P1D'));
/**
* Books a task's estimated time backwards from its due date: first the
* assignee's free time on the due date, then on the working days before
* it, but not before the earliest day (today). What does not fit goes to
* the working days after the due date, which makes the task end late.
*
* @param array<string, int> $otherMinutes Y-m-d => minutes booked by the assignee's other open tasks.
* @param list<string> $holidays Y-m-d dates of the holidays in use.
*/
public static function scheduleBackwards(
DateTimeImmutable $due,
int $minutes,
array $otherMinutes,
int $capacityMinutes,
array $holidays,
DateTimeImmutable $earliest,
): TaskSchedule {
if ($minutes <= 0) {
return new TaskSchedule([], $due, false);
}
$holidaySet = array_flip($holidays);
$booked = [];
$carry = $minutes;
$first = $earliest->format('Y-m-d');
for ($day = $due, $back = 0; $carry > 0 && $day->format('Y-m-d') >= $first && $back < self::MAX_EXTRA_DAYS; $day = $day->sub(new DateInterval('P1D')), $back++) {
$date = $day->format('Y-m-d');
if (! self::isWorkingDay($date, $holidaySet)) {
@@ -83,16 +109,41 @@ final class TaskScheduler
}
}
if ($carry > 0) {
$date = $day->format('Y-m-d');
$booked[$date] = ($booked[$date] ?? 0) + $carry;
// A due date before the earliest day: the rest starts on the earliest day.
$after = $due->format('Y-m-d') >= $first ? $due : $earliest->sub(new DateInterval('P1D'));
return self::finish($booked, self::bookAfter($after, $carry, $otherMinutes, $capacityMinutes, $holidaySet), $due);
}
/**
* The start of a task that ends on a day: as many working days before
* it as the estimate needs at the daily maximum, but not before the
* earliest day unless the end is; without an estimate, the day itself.
*
* @param list<string> $holidays
*/
public static function defaultStart(DateTimeImmutable $to, int $minutes, int $capacityMinutes, array $holidays, DateTimeImmutable $earliest): DateTimeImmutable
{
$first = $earliest->format('Y-m-d');
if ($minutes <= 0 || $capacityMinutes <= 0 || $to->format('Y-m-d') <= $first) {
return $to;
}
ksort($booked);
$lastDay = array_key_last($booked);
$end = $lastDay !== null && $lastDay > $to->format('Y-m-d') ? new DateTimeImmutable($lastDay) : $to;
$needed = (int) ceil($minutes / $capacityMinutes);
$holidaySet = array_flip($holidays);
$day = $to;
$counted = self::isWorkingDay($to->format('Y-m-d'), $holidaySet) ? 1 : 0;
return new TaskSchedule($booked, $end, $end > $to);
while ($counted < $needed && $day->format('Y-m-d') > $first) {
$day = $day->sub(new DateInterval('P1D'));
if (self::isWorkingDay($day->format('Y-m-d'), $holidaySet)) {
$counted++;
}
}
return $day;
}
/**
@@ -168,6 +219,59 @@ final class TaskScheduler
return $shares;
}
/**
* Books the carried minutes on the working days after the day; what
* finds no free time within MAX_EXTRA_DAYS goes on the last day tried.
*
* @param array<string, int> $otherMinutes
* @param array<string, int> $holidaySet
* @return array<string, int> Y-m-d => minutes.
*/
private static function bookAfter(DateTimeImmutable $day, int $carry, array $otherMinutes, int $capacityMinutes, array $holidaySet): array
{
$booked = [];
for ($extra = 0; $carry > 0 && $extra < self::MAX_EXTRA_DAYS; $extra++) {
$day = $day->add(new DateInterval('P1D'));
$date = $day->format('Y-m-d');
if (! self::isWorkingDay($date, $holidaySet)) {
continue;
}
$booking = min($carry, self::free($date, $otherMinutes, $capacityMinutes));
$carry -= $booking;
if ($booking > 0) {
$booked[$date] = $booking;
}
}
if ($carry > 0) {
$date = $day->format('Y-m-d');
$booked[$date] = ($booked[$date] ?? 0) + $carry;
}
return $booked;
}
/**
* @param array<string, int> $booked
* @param array<string, int> $overflow Bookings after the planned end.
*/
private static function finish(array $booked, array $overflow, DateTimeImmutable $to): TaskSchedule
{
foreach ($overflow as $date => $minutes) {
$booked[$date] = ($booked[$date] ?? 0) + $minutes;
}
ksort($booked);
$lastDay = array_key_last($booked);
$end = $lastDay !== null && $lastDay > $to->format('Y-m-d') ? new DateTimeImmutable($lastDay) : $to;
return new TaskSchedule($booked, $end, $end > $to);
}
/**
* @param array<string, int> $otherMinutes
*/
@@ -13,7 +13,8 @@ use Illuminate\Database\Eloquent\Model;
/**
* Persistence model of a task, used only inside the Jobs Infrastructure
* layer. Assignees are in task_assignees, day bookings in task_bookings.
* layer. Members are in task_members, the assignee's day bookings in
* task_bookings.
*
* @property int $id
* @property int $customer_job_id
@@ -25,10 +26,11 @@ use Illuminate\Database\Eloquent\Model;
* @property CarbonImmutable|null $planned_from
* @property CarbonImmutable|null $planned_to
* @property string|null $estimated_hours
* @property int|null $assignee_user_id
* @property int $created_by
*/
#[Table('tasks')]
#[Fillable(['customer_job_id', 'work_type_id', 'title', 'description', 'status', 'due_on', 'planned_from', 'planned_to', 'estimated_hours', 'created_by'])]
#[Fillable(['customer_job_id', 'work_type_id', 'title', 'description', 'status', 'due_on', 'planned_from', 'planned_to', 'estimated_hours', 'assignee_user_id', 'created_by'])]
#[UseFactory(TaskFactory::class)]
class TaskModel extends Model
{
@@ -47,6 +49,7 @@ class TaskModel extends Model
'due_on' => 'immutable_date',
'planned_from' => 'immutable_date',
'planned_to' => 'immutable_date',
'assignee_user_id' => 'integer',
'created_by' => 'integer',
];
}
@@ -7,7 +7,7 @@ use Illuminate\Support\Facades\DB;
/**
* The jobs a user is involved in: responsible, contact person, biller,
* member, or assignee of one of the job's tasks. Used for "my jobs" and
* member, or assignee or member of one of the job's tasks. Used for "my jobs" and
* for what a subcontractor may see.
*/
final class JobInvolvement
@@ -27,10 +27,11 @@ final class JobInvolvement
->orWhere($table.'.contact_user_id', $userId)
->orWhere($table.'.biller_user_id', $userId)
->orWhereIn($table.'.id', DB::table('customer_job_members')->select('customer_job_id')->where('user_id', $userId))
->orWhereIn($table.'.id', DB::table('tasks')->select('customer_job_id')->where('assignee_user_id', $userId))
->orWhereIn($table.'.id', DB::table('tasks')
->join('task_assignees', 'task_assignees.task_id', '=', 'tasks.id')
->join('task_members', 'task_members.task_id', '=', 'tasks.id')
->select('tasks.customer_job_id')
->where('task_assignees.user_id', $userId)));
->where('task_members.user_id', $userId)));
return $query;
}
@@ -2,17 +2,26 @@
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries;
use App\Modules\Jobs\Application\DTOs\CalendarAssignment;
use App\Modules\Jobs\Application\DTOs\CalendarTask;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
class EloquentTaskCalendarQueries implements TaskCalendarQueries
{
public function __construct(
private CatalogQueries $catalog,
private CustomerQueries $customers,
private UserAccountQueries $users,
) {}
public function scheduledTasks(string $from, string $to, ?int $serviceUnitId = null, ?int $onlyAssigneeUserId = null): array
{
$query = $this->tasks($serviceUnitId, $onlyAssigneeUserId)
@@ -29,6 +38,7 @@ class EloquentTaskCalendarQueries implements TaskCalendarQueries
{
$query = $this->tasks($serviceUnitId, $onlyAssigneeUserId)
->whereNull('tasks.planned_from')
->whereNull('customer_jobs.quick_sale_year')
->where('tasks.status', '!=', TaskStatus::Done->value)
->where('customer_jobs.status', '!=', JobStatus::Archived->value)
->orderByRaw('tasks.due_on IS NULL')
@@ -72,7 +82,7 @@ class EloquentTaskCalendarQueries implements TaskCalendarQueries
if ($onlyAssigneeUserId !== null) {
JobInvolvement::restrict($query, $onlyAssigneeUserId);
$query->whereIn('tasks.id', DB::table('task_assignees')->select('task_id')->where('user_id', $onlyAssigneeUserId));
$query->where('tasks.assignee_user_id', $onlyAssigneeUserId);
}
return $query;
@@ -84,8 +94,10 @@ class EloquentTaskCalendarQueries implements TaskCalendarQueries
private function calendarTasks(Builder $query): array
{
$rows = $query->get([
'tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.status', 'tasks.due_on', 'tasks.estimated_hours',
'tasks.planned_from', 'tasks.planned_to', 'customer_jobs.number', 'customer_jobs.name',
'tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.description', 'tasks.status', 'tasks.due_on', 'tasks.estimated_hours',
'tasks.planned_from', 'tasks.planned_to', 'tasks.assignee_user_id', 'tasks.work_type_id',
'customer_jobs.number', 'customer_jobs.name', 'customer_jobs.customer_id', 'customer_jobs.status as job_status',
'customer_jobs.due_on as job_due_on', 'customer_jobs.responsible_user_id',
]);
$taskIds = $rows->pluck('id')->map(fn ($id): int => (int) $id)->all();
@@ -93,7 +105,6 @@ class EloquentTaskCalendarQueries implements TaskCalendarQueries
return [];
}
$assignees = DB::table('task_assignees')->whereIn('task_id', $taskIds)->orderBy('user_id')->get()->groupBy('task_id');
$bookings = DB::table('task_bookings')
->whereIn('task_id', $taskIds)
->groupBy('task_id', 'user_id')
@@ -101,6 +112,14 @@ class EloquentTaskCalendarQueries implements TaskCalendarQueries
->get()
->keyBy(fn ($row): string => $row->task_id.'-'.$row->user_id);
$customerNames = $this->customers->namesByIds(self::ids($rows->pluck('customer_id')->all()));
$userNames = $this->users->namesByIds(self::ids($rows->pluck('responsible_user_id')->all()));
$workTypeNames = [];
foreach (self::ids($rows->pluck('work_type_id')->all()) as $workTypeId) {
$workTypeNames[$workTypeId] = $this->catalog->findWorkType($workTypeId)->name ?? null;
}
return $rows->map(fn ($row): CalendarTask => new CalendarTask(
(int) $row->id,
(int) $row->customer_job_id,
@@ -112,19 +131,35 @@ class EloquentTaskCalendarQueries implements TaskCalendarQueries
$row->estimated_hours === null ? null : (string) (float) $row->estimated_hours,
self::date($row->planned_from),
self::date($row->planned_to),
($assignees->get($row->id) ?? collect())->map(function ($assignee) use ($bookings, $row): CalendarAssignment {
$booking = $bookings->get($row->id.'-'.$assignee->user_id);
return new CalendarAssignment(
(int) $assignee->user_id,
self::date($booking?->first_day),
self::date($booking?->last_day),
(int) ($booking->minutes ?? 0),
);
})->values()->all(),
$row->assignee_user_id === null ? null : self::assignment((int) $row->assignee_user_id, $bookings->get($row->id.'-'.$row->assignee_user_id)),
customerName: $customerNames[(int) $row->customer_id] ?? null,
jobStatus: JobStatus::tryFrom((string) $row->job_status),
jobDueOn: self::date($row->job_due_on),
responsibleName: $row->responsible_user_id === null ? null : ($userNames[(int) $row->responsible_user_id] ?? null),
workTypeName: $workTypeNames[(int) $row->work_type_id] ?? null,
description: $row->description === null ? null : (string) $row->description,
))->values()->all();
}
/**
* @param array<int, mixed> $values
* @return list<int>
*/
private static function ids(array $values): array
{
return array_values(array_unique(array_map('intval', array_filter($values, fn ($value): bool => $value !== null))));
}
private static function assignment(int $userId, mixed $booking): CalendarAssignment
{
return new CalendarAssignment(
$userId,
self::date($booking?->first_day),
self::date($booking?->last_day),
(int) ($booking->minutes ?? 0),
);
}
private static function date(mixed $value): ?string
{
return $value === null ? null : substr((string) $value, 0, 10);
@@ -60,9 +60,10 @@ class EloquentTaskQueries implements TaskQueries
public function assignedOpenTaskIds(int $userId): array
{
return DB::table('tasks')
->join('task_assignees', 'task_assignees.task_id', '=', 'tasks.id')
->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id')
->where('task_assignees.user_id', $userId)
->where(fn ($query) => $query
->where('tasks.assignee_user_id', $userId)
->orWhereIn('tasks.id', DB::table('task_members')->select('task_id')->where('user_id', $userId)))
->where('tasks.status', '!=', TaskStatus::Done->value)
->whereNotIn('customer_jobs.status', self::lockedStatuses())
->orderBy('tasks.id')
@@ -139,11 +140,13 @@ class EloquentTaskQueries implements TaskQueries
*/
private function summaries(Collection $models): array
{
$assignees = DB::table('task_assignees')
$members = DB::table('task_members')
->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());
$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());
$workTypeNames = [];
foreach ($models->pluck('work_type_id')->unique() as $workTypeId) {
@@ -159,7 +162,8 @@ class EloquentTaskQueries implements TaskQueries
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())
assignee: $model->assignee_user_id === null ? null : new NamedId($model->assignee_user_id, $userNames[$model->assignee_user_id] ?? ''),
members: ($members->get($model->id) ?? collect())
->map(fn ($row): NamedId => new NamedId((int) $row->user_id, $userNames[(int) $row->user_id] ?? ''))
->sortBy('name')
->values()
@@ -41,13 +41,14 @@ class EloquentTaskRepository implements TaskRepository
'planned_from' => $task->plannedFrom()?->format('Y-m-d'),
'planned_to' => $task->plannedTo()?->format('Y-m-d'),
'estimated_hours' => $task->estimatedHours()?->value,
'assignee_user_id' => $task->assigneeUserId(),
'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(
DB::table('task_members')->where('task_id', $model->id)->whereNotIn('user_id', $task->memberUserIds())->delete();
DB::table('task_members')->insertOrIgnore(array_map(
fn (int $userId): array => ['task_id' => $model->id, 'user_id' => $userId],
$task->assigneeUserIds(),
$task->memberUserIds(),
));
return $this->toEntity($model->refresh());
@@ -69,7 +70,8 @@ class EloquentTaskRepository implements TaskRepository
$model->status,
self::date($model->due_on),
$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->assignee_user_id,
DB::table('task_members')->where('task_id', $model->id)->pluck('user_id')->map(fn ($id): int => (int) $id)->all(),
$model->created_by,
self::date($model->planned_from),
self::date($model->planned_to),
@@ -36,8 +36,10 @@ class TaskForm extends Form
public string $description = '';
public string $assignee_user_id = '';
/** @var list<string> */
public array $assignee_user_ids = [];
public array $member_user_ids = [];
public function fillFromSummary(TaskSummary $task): void
{
@@ -49,7 +51,8 @@ class TaskForm extends Form
$this->planned_from = $task->plannedFrom ?? '';
$this->planned_to = $task->plannedTo ?? '';
$this->description = $task->description ?? '';
$this->assignee_user_ids = array_map(fn (NamedId $user): string => (string) $user->id, $task->assignees);
$this->assignee_user_id = $task->assignee === null ? '' : (string) $task->assignee->id;
$this->member_user_ids = array_map(fn (NamedId $user): string => (string) $user->id, $task->members);
}
public function toData(): TaskData
@@ -63,7 +66,8 @@ class TaskForm extends Form
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),
assigneeUserId: $this->assignee_user_id === '' ? null : (int) $this->assignee_user_id,
memberUserIds: array_map('intval', $this->member_user_ids),
plannedFrom: $this->planned_from === '' ? null : $this->planned_from,
plannedTo: $this->planned_from === '' || $this->planned_to === '' ? null : $this->planned_to,
);
@@ -76,7 +80,11 @@ class TaskForm extends Form
$exception instanceof InvalidEstimatedHours => ['estimated_hours', 'jobs.errors.invalid_hours'],
$exception instanceof TasksNotAllowedYet => ['title', 'jobs.tasks.not_allowed_yet'],
$exception instanceof PlanEndsBeforeStart => ['planned_to', 'jobs.calendar.errors.to'],
$exception instanceof InvalidTaskReference => [$exception->field === 'work_type' ? 'work_type_id' : 'assignee_user_ids', 'jobs.errors.invalid_reference'],
$exception instanceof InvalidTaskReference => [match ($exception->field) {
'work_type' => 'work_type_id',
'assignee' => 'assignee_user_id',
default => 'member_user_ids',
}, 'jobs.errors.invalid_reference'],
default => throw $exception,
};
@@ -97,8 +105,9 @@ class TaskForm extends Form
'planned_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:planned_from'],
'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'],
'description' => ['nullable', 'string', 'max:10000'],
'assignee_user_ids' => ['array'],
'assignee_user_ids.*' => ['integer'],
'assignee_user_id' => ['nullable', 'integer'],
'member_user_ids' => ['array'],
'member_user_ids.*' => ['integer'],
];
}
@@ -365,6 +365,10 @@ new class extends Component
public function hours(int $minutes): string
{
if ($minutes === 0) {
return '0';
}
return rtrim(rtrim(number_format($minutes / 60, 2, ',', ''), '0'), ',');
}
@@ -389,12 +393,11 @@ new class extends Component
/**
* The person an unscheduled task is moved from when it is dropped on a
* row: its only assignee, so that the task moves rather than gets a
* second assignee.
* row: its assignee, who the person on the row replaces.
*/
public function onlyAssignee(CalendarTask $task): ?int
{
return count($task->assignments) === 1 ? $task->assignments[0]->userId : null;
return $task->assignment?->userId;
}
public function render(): mixed
@@ -543,7 +546,7 @@ new class extends Component
x-data="taskCalendar(@js($canManage))"
x-on:pointermove.window="track($event)"
x-on:pointerup.window="drop($event)"
x-on:keydown.escape.window="cancel()"
x-on:keydown.escape.window="cancel(); closeInfo()"
x-on:task-calendar-place.window="begin($event.detail.event, 'place', $event.detail.bar)"
>
<div class="grid border-b border-zinc-300 text-sm dark:border-zinc-600" style="{{ $columns }}" aria-hidden="true">
@@ -598,22 +601,31 @@ new class extends Component
data-calendar-user="{{ $row->userId ?? '' }}"
x-bind:class="isTarget('{{ $day }}', '{{ $row->userId ?? '' }}') && 'outline-2 -outline-offset-2 outline-blue-700 dark:outline-blue-300'"
@class([
'min-h-12 border-l border-zinc-200 px-1 pt-1 pb-2 text-right text-xs dark:border-zinc-700',
'min-h-12 border-l border-zinc-200 dark:border-zinc-700',
'bg-zinc-200 dark:bg-zinc-800' => $this->isDayOff($day),
])
style="grid-column: {{ $index + 2 }}; grid-row: 1 / span {{ $row->lanes + 1 }};"
>
@if ($booked > 0)
></div>
{{-- The day's booked time on its own grid line, above the task bars. --}}
@if ($row->userId !== null && ($booked > 0 || ! $this->isDayOff($day)))
<div
wire:key="load-{{ $rowKey }}-{{ $day }}"
@class([
'pointer-events-none px-1 pt-1 text-right text-xs whitespace-nowrap',
'font-semibold' => $booked > $this->capacityMinutes,
'text-zinc-600 dark:text-zinc-300' => $booked === 0,
])
style="grid-column: {{ $index + 2 }}; grid-row: 1;"
>
<span class="sr-only">{{ $this->dayLabel($day) }}:</span>
<span @class(['font-semibold' => $booked > $this->capacityMinutes])>
{{ __('jobs.calendar.load', ['booked' => $this->hours($booked), 'capacity' => $capacity]) }}
@if ($booked > $this->capacityMinutes)
<x-icon name="exclamation-triangle" class="inline size-3" aria-hidden="true" />
{{ __('jobs.calendar.over_capacity') }}
@endif
</span>
@endif
</div>
{{ __('jobs.calendar.load', ['booked' => $this->hours($booked), 'capacity' => $capacity]) }}
@if ($booked > $this->capacityMinutes)
<x-icon name="exclamation-triangle" class="inline size-3" aria-hidden="true" />
{{ __('jobs.calendar.over_capacity') }}
@endif
</div>
@endif
@endforeach
@foreach ($row->bars as $bar)
@@ -622,6 +634,11 @@ new class extends Component
id="bar-{{ $bar->key() }}"
wire:key="bar-{{ $bar->key() }}"
aria-label="{{ $this->barLabel($bar) }}"
aria-describedby="bar-info-{{ $bar->key() }}"
x-on:mouseenter="showInfo($el, 'bar-info-{{ $bar->key() }}')"
x-on:mouseleave="hideInfo('bar-info-{{ $bar->key() }}')"
x-on:focus="showInfo($el, 'bar-info-{{ $bar->key() }}')"
x-on:blur="hideInfo('bar-info-{{ $bar->key() }}', 0)"
x-on:pointerdown="begin($event, 'move', @js(['task' => $bar->task->taskId, 'job' => $bar->task->jobId, 'user' => $bar->userId, 'from' => $bar->from, 'to' => $bar->to]))"
x-on:click="if (! consumeDrag()) $wire.openDialog({{ $bar->task->taskId }}, {{ $bar->userId ?? 'null' }})"
@class([
@@ -656,6 +673,48 @@ new class extends Component
></span>
@endif
</button>
{{-- The job's basic details on hover and focus (WCAG 1.4.13: hoverable, Escape closes it). --}}
<div
id="bar-info-{{ $bar->key() }}"
wire:key="bar-info-{{ $bar->key() }}"
popover="manual"
role="tooltip"
x-on:mouseenter="keepInfo()"
x-on:mouseleave="hideInfo('bar-info-{{ $bar->key() }}')"
class="m-0 w-80 max-w-[calc(100vw-1rem)] rounded-lg border border-zinc-300 bg-white p-3 text-left text-sm text-zinc-900 shadow-lg dark:border-zinc-600 dark:bg-zinc-800 dark:text-white"
style="inset: auto;"
>
<p class="font-semibold break-words">{{ $bar->task->title }}</p>
<dl class="mt-2 grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1">
<dt class="font-medium">{{ __('jobs.calendar.info.job') }}</dt>
<dd class="break-words">{{ $bar->task->jobNumber }} {{ $bar->task->jobName }}</dd>
<dt class="font-medium">{{ __('jobs.calendar.info.customer') }}</dt>
<dd class="break-words">{{ $bar->task->customerName ?? __('jobs.not_set') }}</dd>
<dt class="font-medium">{{ __('jobs.calendar.info.job_status') }}</dt>
<dd>{{ $bar->task->jobStatus === null ? __('jobs.not_set') : __('jobs.statuses.'.$bar->task->jobStatus->value) }}</dd>
<dt class="font-medium">{{ __('jobs.calendar.info.job_due_on') }}</dt>
<dd>{{ $bar->task->jobDueOn === null ? __('jobs.not_set') : $this->shortDate($bar->task->jobDueOn) }}</dd>
<dt class="font-medium">{{ __('jobs.calendar.info.responsible') }}</dt>
<dd class="break-words">{{ $bar->task->responsibleName ?? __('jobs.not_set') }}</dd>
<dt class="font-medium">{{ __('jobs.calendar.info.work_type') }}</dt>
<dd class="break-words">{{ $bar->task->workTypeName ?? __('jobs.not_set') }}</dd>
<dt class="font-medium">{{ __('jobs.calendar.info.due_on') }}</dt>
<dd>{{ $bar->task->dueOn === null ? __('jobs.not_set') : $this->shortDate($bar->task->dueOn) }}</dd>
<dt class="font-medium">{{ __('jobs.calendar.info.schedule') }}</dt>
<dd>
{{ $this->shortDate($bar->from) }}–{{ $this->shortDate($bar->to) }}@if ($bar->minutes > 0), {{ $this->hours($bar->minutes) }} h @endif
@if ($bar->late)
<span class="inline-flex items-center gap-1 font-semibold">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
</span>
@endif
</dd>
</dl>
@if ($bar->task->description !== null)
<p class="mt-2 line-clamp-3 break-words whitespace-pre-line text-zinc-700 dark:text-zinc-200">{{ $bar->task->description }}</p>
@endif
</div>
@endforeach
</section>
@endforeach
@@ -683,6 +742,9 @@ new class extends Component
<span class="font-semibold break-words">{{ $bar->task->title }}</span>
<span>{{ $this->shortDate($bar->from) }}–{{ $this->shortDate($bar->to) }}@if ($bar->minutes > 0), {{ $this->hours($bar->minutes) }} h @endif</span>
<span class="break-words">{{ $bar->task->jobNumber }} {{ $bar->task->jobName }} · {{ __('jobs.tasks.statuses.'.$bar->task->status->value) }}</span>
@if ($bar->task->customerName !== null)
<span class="break-words">{{ __('jobs.calendar.info.customer') }}: {{ $bar->task->customerName }}</span>
@endif
@if ($bar->late)
<span class="inline-flex items-center gap-1 font-semibold">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
@@ -721,7 +783,7 @@ new class extends Component
<span class="font-semibold break-words">{{ $task->title }}</span>
<span class="break-words">{{ $task->jobNumber }} {{ $task->jobName }}</span>
<span class="break-words">
{{ $task->assignments === [] ? __('jobs.calendar.no_assignee') : implode(', ', array_map(fn ($assignment) => $this->userNames[$assignment->userId] ?? '', $task->assignments)) }}
{{ $task->assignment === null ? __('jobs.calendar.no_assignee') : ($this->userNames[$task->assignment->userId] ?? '') }}
@if ($task->estimatedHours !== null) · {{ str_replace('.', ',', $task->estimatedHours) }} h @endif
</span>
@if ($task->dueOn !== null)
@@ -347,8 +347,12 @@ new class extends Component
<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.assignee') }}</dt>
<dd>{{ $task->assignee?->name ?? __('jobs.calendar.no_assignee') }}</dd>
@if ($task->members !== [])
<dt class="font-medium">{{ __('jobs.tasks.fields.members') }}</dt>
<dd>{{ collect($task->members)->pluck('name')->join(', ') }}</dd>
@endif
<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.schedule') }}</dt>
@@ -58,7 +58,7 @@ new class extends Component
if ($task === null) {
abort_unless($details->status->allowsTasks(), 404);
$this->form->assignee_user_ids = [(string) auth()->id()];
$this->form->assignee_user_id = (string) auth()->id();
return;
}
@@ -193,10 +193,18 @@ new class extends Component
@endforeach
</x-select.native>
<x-select.native wire:model="form.assignee_user_id" :label="__('jobs.tasks.fields.assignee')" :aria-label="__('jobs.tasks.fields.assignee')" :hint="__('jobs.tasks.fields.assignee_hint')">
<option value="">{{ __('jobs.calendar.no_assignee') }}</option>
@foreach ($this->userOptions as $user)
<option value="{{ $user['value'] }}">{{ $user['note'] === null ? $user['label'] : $user['label'].' ('.$user['note'].')' }}</option>
@endforeach
</x-select.native>
<x-checkbox-group
:legend="__('jobs.tasks.fields.assignees')"
model="form.assignee_user_ids"
:legend="__('jobs.tasks.fields.members')"
model="form.member_user_ids"
:options="$this->userOptions"
:hint="__('jobs.tasks.fields.members_hint')"
/>
<div class="grid gap-6 sm:grid-cols-3">
@@ -12,6 +12,8 @@ use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\Exceptions\WorkflowTemplateNotAvailable;
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;
@@ -19,7 +21,8 @@ use Livewire\Component;
/**
* Adds a job's tasks from a workflow template (työnkulkupohja): one task per
* step. Once a template is chosen, a table of its tasks takes an optional
* due date and estimate for each.
* due date, estimate and assignee (the adder by default) for each; tasks
* with a due date are scheduled to end on it unless that is turned off.
*/
new class extends Component
{
@@ -38,10 +41,12 @@ new class extends Component
/**
* One row per step of the chosen template, in step order.
*
* @var list<array{due_on: string, estimated_hours: string}>
* @var list<array{due_on: string, estimated_hours: string, assignee_user_id: string}>
*/
public array $rows = [];
public bool $scheduleToDueDates = true;
public function mount(CustomerJobQueries $jobQueries, int $job): void
{
$details = $jobQueries->findDetails($job);
@@ -85,6 +90,18 @@ new class extends Component
], $this->templates);
}
/**
* @return list<array{value: int, label: string}>
*/
#[Computed]
public function userOptions(): array
{
return array_map(fn ($user): array => [
'value' => $user->id,
'label' => $user->role === Role::Subcontractor ? $user->name.' ('.__('users.roles.subcontractor').')' : $user->name,
], app(UserAccountQueries::class)->activeUserOptions());
}
#[Computed]
public function selectedTemplate(): ?WorkflowTemplateDetails
{
@@ -103,7 +120,7 @@ new class extends Component
public function updatedTemplateId(): void
{
$this->resetErrorBag();
$this->rows = array_map(fn (): array => ['due_on' => '', 'estimated_hours' => ''], $this->selectedTemplate?->steps ?? []);
$this->rows = array_map(fn (): array => ['due_on' => '', 'estimated_hours' => '', 'assignee_user_id' => (string) auth()->id()], $this->selectedTemplate?->steps ?? []);
}
public function add(AddTasksFromWorkflowTemplate $addTasks): void
@@ -116,6 +133,8 @@ new class extends Component
'rows' => ['array'],
'rows.*.due_on' => ['nullable', 'date_format:Y-m-d'],
'rows.*.estimated_hours' => ['nullable', 'regex:/^\s*\d{1,5}([.,]\d{1,2})?\s*$/'],
'rows.*.assignee_user_id' => ['nullable', 'integer'],
'scheduleToDueDates' => ['boolean'],
],
[
'templateId.required' => __('jobs.tasks.from_template.choose'),
@@ -129,10 +148,11 @@ new class extends Component
$schedules = array_map(fn (array $row): TemplateTaskSchedule => new TemplateTaskSchedule(
$row['due_on'] === '' ? null : $row['due_on'],
trim($row['estimated_hours']) === '' ? null : $row['estimated_hours'],
$row['assignee_user_id'] === '' ? null : (int) $row['assignee_user_id'],
), $this->rows);
try {
$count = $addTasks->execute($this->jobId, (int) $this->templateId, (int) auth()->id(), $schedules);
$result = $addTasks->execute($this->jobId, (int) $this->templateId, (int) auth()->id(), $schedules, $this->scheduleToDueDates);
} catch (CustomerJobNotFound) {
abort(404);
} catch (TasksNotAllowedYet) {
@@ -143,17 +163,39 @@ new class extends Component
$this->addError('templateId', __('jobs.errors.invalid_hours'));
return;
} catch (WorkflowTemplateNotAvailable|InvalidTaskReference) {
} catch (InvalidTaskReference $exception) {
if ($exception->field === 'assignee') {
unset($this->userOptions);
$this->addError('templateId', __('jobs.errors.invalid_reference'));
return;
}
unset($this->templates, $this->options, $this->selectedTemplate);
$this->addError('templateId', __('jobs.tasks.from_template.not_available'));
return;
} catch (WorkflowTemplateNotAvailable) {
unset($this->templates, $this->options, $this->selectedTemplate);
$this->addError('templateId', __('jobs.tasks.from_template.not_available'));
return;
}
session()->flash('status', trans_choice('jobs.tasks.from_template.added', $count, [
'count' => $count,
$message = trans_choice('jobs.tasks.from_template.added', $result->added, [
'count' => $result->added,
'name' => $template === null ? '' : $this->labelOf($template),
]));
]);
if ($result->scheduled > 0) {
$message .= ' '.trans_choice('jobs.tasks.from_template.scheduled', $result->scheduled, ['count' => $result->scheduled]);
}
if ($result->late > 0) {
$message .= ' '.trans_choice('jobs.tasks.from_template.late', $result->late, ['count' => $result->late]);
}
session()->flash('status', $message);
$this->redirect(route('jobs.show', $this->jobId).'#tasks', navigate: true);
}
@@ -201,23 +243,26 @@ new class extends Component
<div class="space-y-2">
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.from_template.schedule_help') }}</p>
{{-- Below sm the rows stack (each cell on its own line, with its own visible label) so that the page reflows at 320 px. --}}
<table class="w-full border-collapse text-sm">
<caption class="mb-2 text-left font-medium">{{ __('jobs.tasks.from_template.table_caption', ['name' => $template->name]) }}</caption>
<thead>
<thead class="max-sm:hidden">
<tr class="border-b border-zinc-200 dark:border-zinc-700">
<th scope="col" class="py-2 pr-2 text-left font-semibold">{{ __('jobs.tasks.from_template.task') }}</th>
<th scope="col" class="px-1 py-2 text-left font-semibold">{{ __('jobs.tasks.fields.due_on') }}</th>
<th scope="col" class="py-2 pl-1 text-left font-semibold">{{ __('jobs.tasks.fields.estimated_hours') }}</th>
<th scope="col" class="px-1 py-2 text-left font-semibold">{{ __('jobs.tasks.fields.estimated_hours') }}</th>
<th scope="col" class="py-2 pl-1 text-left font-semibold">{{ __('jobs.tasks.fields.assignee') }}</th>
</tr>
</thead>
<tbody>
<tbody class="max-sm:block">
@foreach ($template->steps as $index => $step)
<tr wire:key="row-{{ $template->id }}-{{ $index }}" class="border-b border-zinc-200 align-top dark:border-zinc-700">
<th scope="row" class="py-2 pr-2 text-left font-normal break-words">
<tr wire:key="row-{{ $template->id }}-{{ $index }}" class="border-b border-zinc-200 align-top max-sm:block max-sm:py-2 dark:border-zinc-700">
<th scope="row" class="py-2 pr-2 text-left font-normal break-words max-sm:block max-sm:py-0">
<span class="font-medium">{{ $step->title }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $step->workTypeName }}</span>
</th>
<td class="px-1 py-2">
<td class="px-1 py-2 max-sm:block max-sm:px-0 max-sm:py-1">
<span class="block text-xs font-medium sm:hidden" aria-hidden="true">{{ __('jobs.tasks.fields.due_on') }}</span>
<input
type="date"
id="row-{{ $index }}-due-on"
@@ -230,7 +275,8 @@ new class extends Component
<p id="row-{{ $index }}-due-on-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</td>
<td class="py-2 pl-1">
<td class="px-1 py-2 max-sm:block max-sm:px-0 max-sm:py-1">
<span class="block text-xs font-medium sm:hidden" aria-hidden="true">{{ __('jobs.tasks.fields.estimated_hours') }}</span>
<input
type="text"
inputmode="decimal"
@@ -239,16 +285,40 @@ new class extends Component
wire:model="rows.{{ $index }}.estimated_hours"
aria-label="{{ __('jobs.tasks.from_template.hours_of', ['title' => $step->title]) }}"
@error('rows.'.$index.'.estimated_hours') aria-invalid="true" aria-describedby="row-{{ $index }}-hours-error" @enderror
class="w-16 rounded-md border border-zinc-500 bg-white px-2 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800"
class="w-16 rounded-md border max-sm:w-full border-zinc-500 bg-white px-2 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800"
/>
@error('rows.'.$index.'.estimated_hours')
<p id="row-{{ $index }}-hours-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</td>
<td class="py-2 pl-1 max-sm:block max-sm:py-1 max-sm:pl-0">
<span class="block text-xs font-medium sm:hidden" aria-hidden="true">{{ __('jobs.tasks.fields.assignee') }}</span>
<select
id="row-{{ $index }}-assignee"
wire:model="rows.{{ $index }}.assignee_user_id"
aria-label="{{ __('jobs.tasks.from_template.assignee_of', ['title' => $step->title]) }}"
class="w-full min-w-0 rounded-md border border-zinc-500 bg-white px-1 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800"
>
<option value="">{{ __('jobs.calendar.no_assignee') }}</option>
@foreach ($this->userOptions as $user)
<option value="{{ $user['value'] }}">{{ $user['label'] }}</option>
@endforeach
</select>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="space-y-1 pt-2">
<x-checkbox
id="schedule-to-due-dates"
wire:model="scheduleToDueDates"
aria-describedby="schedule-to-due-dates-hint"
:label="__('jobs.tasks.from_template.schedule_to_due')"
/>
<p id="schedule-to-due-dates-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.from_template.schedule_to_due_hint') }}</p>
</div>
</div>
@endif