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:
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## Project
|
||||
|
||||
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks, task checklists, and the task calendar `jobs::calendar`: a Gantt of tasks per person where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings`, split over working days with the rest moved to the next working day past the daily maximum `jobs.daily_capacity_hours`) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
|
||||
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, split over working days with the rest moved to the next working day past the daily maximum `jobs.daily_capacity_hours`) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
|
||||
|
||||
- **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec.
|
||||
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
|
||||
|
||||
@@ -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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+49
-14
@@ -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
|
||||
|
||||
|
||||
@@ -32,12 +32,24 @@ class TaskFactory extends Factory
|
||||
}
|
||||
|
||||
/**
|
||||
* The first user is the assignee, the others members.
|
||||
*
|
||||
* @param list<int> $userIds
|
||||
*/
|
||||
public function assignedTo(array $userIds): static
|
||||
{
|
||||
$members = array_slice($userIds, 1);
|
||||
|
||||
return $this->state(['assignee_user_id' => $userIds[0] ?? null])->withMembers($members);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $userIds
|
||||
*/
|
||||
public function withMembers(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));
|
||||
DB::table('task_members')->insert(array_map(fn (int $userId): array => ['task_id' => $task->id, 'user_id' => $userId], $userIds));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* A task gets one assignee (tekijä), whose days its estimate books in the
|
||||
* task calendar, and members (jäsenet), who only see it among their own.
|
||||
* Of the earlier assignees, the one with most booked time becomes the
|
||||
* assignee (ties: the smallest user id) and the others members; bookings
|
||||
* of the others are removed.
|
||||
*
|
||||
* The rows are read before the tasks table changes, because SQLite
|
||||
* rebuilds the table and its cascades would remove them.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
$assignees = DB::table('task_assignees')->orderBy('task_id')->orderBy('user_id')->get()
|
||||
->map(fn ($row): array => ['task_id' => (int) $row->task_id, 'user_id' => (int) $row->user_id]);
|
||||
$bookings = DB::table('task_bookings')->get()
|
||||
->map(fn ($row): array => ['task_id' => (int) $row->task_id, 'user_id' => (int) $row->user_id, 'day' => $row->day, 'minutes' => (int) $row->minutes]);
|
||||
|
||||
Schema::table('tasks', function (Blueprint $table) {
|
||||
$table->foreignId('assignee_user_id')->nullable()->after('estimated_hours')->constrained('users')->restrictOnDelete();
|
||||
});
|
||||
|
||||
Schema::rename('task_assignees', 'task_members');
|
||||
|
||||
$booked = [];
|
||||
foreach ($bookings as $booking) {
|
||||
$key = $booking['task_id'].'-'.$booking['user_id'];
|
||||
$booked[$key] = ($booked[$key] ?? 0) + $booking['minutes'];
|
||||
}
|
||||
|
||||
$assigneeOf = [];
|
||||
foreach ($assignees->groupBy('task_id') as $taskId => $rows) {
|
||||
$assigneeOf[$taskId] = $rows
|
||||
->sort(fn (array $a, array $b): int => [$booked[$taskId.'-'.$b['user_id']] ?? 0, $a['user_id']] <=> [$booked[$taskId.'-'.$a['user_id']] ?? 0, $b['user_id']])
|
||||
->first()['user_id'];
|
||||
|
||||
DB::table('tasks')->where('id', $taskId)->update(['assignee_user_id' => $assigneeOf[$taskId]]);
|
||||
}
|
||||
|
||||
DB::table('task_members')->delete();
|
||||
DB::table('task_members')->insert($assignees->filter(fn (array $row): bool => $assigneeOf[$row['task_id']] !== $row['user_id'])->values()->all());
|
||||
|
||||
DB::table('task_bookings')->delete();
|
||||
DB::table('task_bookings')->insert($bookings->filter(fn (array $row): bool => ($assigneeOf[$row['task_id']] ?? null) === $row['user_id'])->values()->all());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations: the assignee becomes one of the assignees again.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
$assignees = DB::table('tasks')->whereNotNull('assignee_user_id')->get(['id', 'assignee_user_id'])
|
||||
->map(fn ($task): array => ['task_id' => (int) $task->id, 'user_id' => (int) $task->assignee_user_id])
|
||||
->merge(DB::table('task_members')->get()->map(fn ($row): array => ['task_id' => (int) $row->task_id, 'user_id' => (int) $row->user_id]));
|
||||
$bookings = DB::table('task_bookings')->get()->map(fn ($row): array => (array) $row);
|
||||
|
||||
Schema::rename('task_members', 'task_assignees');
|
||||
|
||||
Schema::table('tasks', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('assignee_user_id');
|
||||
});
|
||||
|
||||
DB::table('task_assignees')->delete();
|
||||
DB::table('task_assignees')->insert($assignees->all());
|
||||
DB::table('task_bookings')->delete();
|
||||
DB::table('task_bookings')->insert($bookings->all());
|
||||
}
|
||||
};
|
||||
+9
-9
@@ -200,7 +200,7 @@ Toistaiseksi jatkuvalle työlle, jonka maksuperuste on kiinteä kk-laskutus, syn
|
||||
| Laskutusyksikkö | `billing_unit_id` | Valitaan asiakkaan laskutusyksiköistä *(K17, K18)*. |
|
||||
| Muut jäsenet | `members` | Käyttäjät (myös alihankkijat), joille työn kortti näkyy omissa töissä *(K33)*. |
|
||||
|
||||
Käyttäjän "omat työt" ovat työt, joissa hän on vastuuhenkilö, kontaktihenkilö, laskuttaja, jäsen tai jonkin tehtävän tekijä.
|
||||
Käyttäjän "omat työt" ovat työt, joissa hän on vastuuhenkilö, kontaktihenkilö, laskuttaja, jäsen tai jonkin tehtävän tekijä tai jäsen.
|
||||
|
||||
### 5.7 Muutoshistoria *(K27)*
|
||||
|
||||
@@ -239,7 +239,7 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä
|
||||
|
||||
### 8.2 Tehtävät
|
||||
|
||||
- Tehtävät ovat asiakastyön alla. Kentät: nimi, kuvaus, tekijät (yksi tai useampi käyttäjä), määräpäivä, arvioitu aika, aikataulu (suunniteltu alku ja loppu), tila, tarkistuslista (todo) *(K26, K33, K35)*.
|
||||
- Tehtävät ovat asiakastyön alla. Kentät: nimi, kuvaus, tekijä (yksi käyttäjä tai ei ketään; tehtävä on hänen rivillään tehtäväkalenterissa ja varaa hänen aikaansa), jäsenet (käyttäjät, jotka näkevät tehtävän omissa töissään ja viikkonäkymässään, mutta joiden aikaa tehtävä ei varaa), määräpäivä, arvioitu aika, aikataulu (suunniteltu alku ja loppu), tila, tarkistuslista (todo) *(K26, K33, K35)*.
|
||||
- Tehtävän tilat oletuksena: odottaa (`Waiting`), työn alla (`InProgress`), tarkastettavana (`InReview`), valmis (`Done`). Määräaika ja myöhässä-ilmaisin.
|
||||
- ~~Tehtävien sarakkeet voivat olla palveluyksikkökohtaisia, ja ne määritellään asetuksista *(K34)*.~~ Päätös: tehtävien Kanbania ei tehdä. Tehtävän tilat ovat kiinteät, ja tehtäviä järjestetään henkilöittäin tehtäväkalenterissa (18.3).
|
||||
- Kommentit tehtävälle *(K27)*. Kuvatiedostojen lähetys tehtävälle (esim. puhelimen kameralla) *(K26)*.
|
||||
@@ -366,9 +366,9 @@ 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`, `created_by` *(olemassa)*; `planned_from`, `planned_to` *(V3, olemassa)*
|
||||
- `tasks`: `customer_job_id`, `work_type_id`, `title`, `description`, `status`, `due_on`, `estimated_hours`, `assignee_user_id`, `created_by` *(olemassa)*; `planned_from`, `planned_to` *(V3, olemassa)*
|
||||
- `task_bookings` *(V3, olemassa)*: `task_id`, `user_id`, `day`, `minutes` (tehtävän arvion varaus tekijän päivästä)
|
||||
- `task_assignees`: `task_id`, `user_id` *(olemassa)*
|
||||
- `task_members`: `task_id`, `user_id` (tehtävän jäsenet; tekijä on `tasks.assignee_user_id`) *(olemassa)*
|
||||
- `task_checklist_items` *(V3)*: `task_id`, `text`, `is_done`, `sort_order`
|
||||
- `task_comments` *(V3)*: `task_id`, `user_id`, `body`
|
||||
- `task_images` *(V3)*: `task_id`, `user_id`, `path`, `original_name`
|
||||
@@ -402,7 +402,7 @@ Tunnit kirjataan tehtäville, joten perustehtävät ja palveluyksiköiden työte
|
||||
4. Asiakastyö: kentät ilman rahakenttiä, numerointi, tagit, linkit, jäsenet, muutoshistoria, lista ja haku ("omat työt" oletuksena).
|
||||
5. Pikavastaanotto puhelimella.
|
||||
6. Asiakastöiden Kanban (tilat).
|
||||
7. Tehtävät (perus: nimi, kuvaus, tekijät, määräpäivä, arvioitu aika, tila odottaa/työn alla/tarkastettavana/valmis).
|
||||
7. Tehtävät (perus: nimi, kuvaus, tekijä ja jäsenet, määräpäivä, arvioitu aika, tila odottaa/työn alla/tarkastettavana/valmis).
|
||||
8. Tuntikirjaus tehtävälle ja viikkonäkymä.
|
||||
|
||||
**Vaihe 2 – raha ja laskutus**
|
||||
@@ -508,13 +508,13 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
|
||||
### 18.2 Työnkulkupohjat *(valmis)*
|
||||
- Pohjatiedot-sivulta linkki Työnkulkupohjat-sivulle (`/catalog/workflow-templates`, pääkäyttäjä ja johto): pohjat palveluyksiköittäin (nimi, työtehtävä, vaiheiden määrä), lisäys, muokkaus ja käytöstä poisto valintaruudulla.
|
||||
- Pohjan lomake: nimi, työtehtävä ja vaiheet (tehtävän nimi 1–255 merkkiä, työtehtävä, kuvaus). Vaiheen voi lisätä, siirtää Siirrä ylös / Siirrä alas -painikkeilla ja poistaa (vähintään yksi vaihe jää); muutokset ilmoitetaan ruudunlukijalle, ja fokus siirtyy uuden vaiheen nimeen tai pysyy käytetyssä painikkeessa. Kaikki tallennetaan kerralla.
|
||||
- Työn sivulla "Lisää tehtävät pohjasta" (`/jobs/{työ}/tasks/from-template`, muille kuin alihankkijoille, kun tehtäviä voi lisätä): valitaan käytössä oleva pohja, jonka työtehtävä kuuluu työn palveluyksiköihin tai kaikille yhteisiin; vaiheet näkyvät valinnan kuvauksessa. Kun pohja on valittu, sen tehtävät näytetään taulukossa, jossa jokaiselle voi antaa vapaaehtoisen määräpäivän ja arvioidun ajan (h); virheet näytetään solussa. Jokaisesta vaiheesta lisätään tehtävä järjestyksessä tilaan Odottaa, tekijänä lisääjä, ja ilmoitus kertoo lisättyjen määrän.
|
||||
- Työn sivulla "Lisää tehtävät pohjasta" (`/jobs/{työ}/tasks/from-template`, muille kuin alihankkijoille, kun tehtäviä voi lisätä): valitaan käytössä oleva pohja, jonka työtehtävä kuuluu työn palveluyksiköihin tai kaikille yhteisiin; vaiheet näkyvät valinnan kuvauksessa. Kun pohja on valittu, sen tehtävät näytetään taulukossa, jossa jokaiselle voi antaa vapaaehtoisen määräpäivän, arvioidun ajan (h) ja tekijän pudotusvalikosta (oletuksena lisääjä, tai Ei tekijää); virheet näytetään solussa. Jokaisesta vaiheesta lisätään tehtävä järjestyksessä tilaan Odottaa, ja ilmoitus kertoo lisättyjen määrän. Valinta "Aikatauluta tehtävät määräpäiville" on oletuksena päällä: tehtävä, jolla on määräpäivä, päättyy määräpäivänään, ja sen arvio varataan tekijän määräpäivän vapaasta ajasta ja sitä edeltävistä arkipäivistä taaksepäin (ei kuitenkin ennen tätä päivää); mitä ei mahdu, siirtyy määräpäivän jälkeisille arkipäiville, jolloin tehtävä on myöhässä ja ilmoitus kertoo sen. Ilman tekijää tehtävä alkaa niin monta arkipäivää ennen määräpäivää kuin arvio päiväkatolla vaatii, eikä varaa aikaa. Vaiheet aikataulutetaan järjestyksessä, joten saman tekijän myöhempi vaihe näkee aiempien varaukset.
|
||||
|
||||
### 18.3 Tehtäväkalenteri *(valmis)*
|
||||
- Valikon Kalenteri (`/jobs/calendar`, kaikki kirjautuneet): rullaava kaksi viikkoa tästä päivästä, painikkeet Edelliset 2 viikkoa / Tänään / Seuraavat 2 viikkoa. Rivi jokaiselle aktiiviselle käyttäjälle (oma rivi ensin) ja rivi Ei tekijää; suodattimet palveluyksikkö ja Vain oma rivi. Alihankkija näkee vain oman rivinsä ja liitettyjen töidensä tehtävät, ja hän voi vaihtaa vain tilaa.
|
||||
- Tehtävällä on aikataulu (suunniteltu alku ja loppu), joka näkyy palkkina jokaisen tekijän rivillä. Päällekkäiset tehtävät pinotaan omille kaistoilleen, joten samalle päivälle voi asettaa useita lyhyitä tehtäviä. Palkissa näkyvät nimi, työn numero, tila tekstinä ja tunnit; jos aikataulu päättyy määräpäivän jälkeen, palkissa on "Myöhässä" kuvakkeineen.
|
||||
- **Päiväkuorma:** tehtävän arvioitu aika varataan jokaiselta tekijältä (jokainen kantaa koko arvion) ja jaetaan tasan jakson arkipäiville; arkipäiviä eivät ole la, su eivätkä käytössä olevat arkipyhät. Jos jaksossa on vain viikonloppu- tai pyhäpäiviä, arvio jaetaan niille. Henkilön päivään varataan enintään päiväkatto (8 h, asetus `jobs.daily_capacity_hours`) miinus muiden avoimien tehtävien varaukset; ylittävä osa siirtyy seuraavalle arkipäivälle, ja tehtävän loppu siirtyy myöhemmäksi (ilmoitetaan). Muiden tehtävien varaukset eivät muutu. Valmiit tehtävät eivät vie kapasiteettia. Päivän solussa näkyy kuorma, esim. "6 / 8 h". Ilman arviota tehtävä ei kuormita.
|
||||
- **Muutokset hiirellä:** palkin rungosta vetämällä tehtävä siirtyy ajassa ja toisen henkilön riville (rivin henkilö korvataan tekijänä, muut tekijät säilyvät); reunoista vetämällä muuttuu alku tai loppu. Aikatauluttamattomat avoimet tehtävät listataan kalenterin alla, ja ne voi vetää päivälle; ilman loppua tehtävä saa niin monta arkipäivää kuin arvio päiväkatolla vaatii.
|
||||
- Tehtävällä on aikataulu (suunniteltu alku ja loppu), joka näkyy palkkina tekijän rivillä (jäsenten riveillä ei). Päällekkäiset tehtävät pinotaan omille kaistoilleen, joten samalle päivälle voi asettaa useita lyhyitä tehtäviä. Palkissa näkyvät nimi, työn numero, tila tekstinä ja tunnit; jos aikataulu päättyy määräpäivän jälkeen, palkissa on "Myöhässä" kuvakkeineen.
|
||||
- **Päiväkuorma:** tehtävän arvioitu aika varataan tekijältä (jäseniltä ei) ja jaetaan tasan jakson arkipäiville; arkipäiviä eivät ole la, su eivätkä käytössä olevat arkipyhät. Jos jaksossa on vain viikonloppu- tai pyhäpäiviä, arvio jaetaan niille. Henkilön päivään varataan enintään päiväkatto (8 h, asetus `jobs.daily_capacity_hours`) miinus muiden avoimien tehtävien varaukset; ylittävä osa siirtyy seuraavalle arkipäivälle, ja tehtävän loppu siirtyy myöhemmäksi (ilmoitetaan). Muiden tehtävien varaukset eivät muutu. Valmiit tehtävät eivät vie kapasiteettia. Päivän solussa näkyy kuorma, esim. "6 / 8 h". Ilman arviota tehtävä ei kuormita.
|
||||
- **Muutokset hiirellä:** palkin rungosta vetämällä tehtävä siirtyy ajassa ja toisen henkilön riville (uuden rivin henkilöstä tulee tekijä, jäsenet säilyvät); reunoista vetämällä muuttuu alku tai loppu. Aikatauluttamattomat avoimet tehtävät listataan kalenterin alla, ja ne voi vetää päivälle; ilman loppua tehtävä saa niin monta arkipäivää kuin arvio päiväkatolla vaatii.
|
||||
- **Näppäimistöllä:** jokainen palkki on painike, joka avaa dialogin: alkaa, päättyy, tekijä, tila, linkit työhön ja tehtävän muokkaukseen sekä Poista aikataulu. Muutos ilmoitetaan `aria-live`-alueella ja fokus palaa palkkiin. Puhelimella ja kapeassa ikkunassa ruudukon sijaan näytetään lista henkilöittäin samoin dialogein.
|
||||
- Tehtävän lomakkeella on kentät Aikataulu alkaa ja Aikataulu päättyy, ja työn sivun tehtäväkortissa näkyy aikataulu.
|
||||
|
||||
|
||||
+23
-5
@@ -37,34 +37,42 @@ return [
|
||||
'book_time_named' => 'Kirjaa tunnit tehtävälle :title',
|
||||
'from_template' => [
|
||||
'title' => 'Lisää tehtävät pohjasta',
|
||||
'intro' => 'Valitse työnkulkupohja. Jokaisesta vaiheesta lisätään tehtävä tilaan Odottaa, ja tekijäksi tulet sinä. Tehtäviä voi muokata lisäyksen jälkeen.',
|
||||
'intro' => 'Valitse työnkulkupohja. Jokaisesta vaiheesta lisätään tehtävä tilaan Odottaa. Tekijäksi tulet sinä, ellet valitse toista. Tehtäviä voi muokata lisäyksen jälkeen.',
|
||||
'template' => 'Työnkulkupohja',
|
||||
'option' => ':name (:work_type)',
|
||||
'steps' => 'Vaiheet: :steps',
|
||||
'table_caption' => 'Pohjan :name tehtävät',
|
||||
'schedule_help' => 'Määräpäivä ja arvioitu aika ovat vapaaehtoisia. Ne voi lisätä myös myöhemmin tehtävän lomakkeella.',
|
||||
'schedule_help' => 'Määräpäivä, arvioitu aika ja tekijä ovat vapaaehtoisia. Ne voi lisätä myös myöhemmin tehtävän lomakkeella.',
|
||||
'schedule_to_due' => 'Aikatauluta tehtävät määräpäiville',
|
||||
'schedule_to_due_hint' => 'Tehtävä päättyy määräpäivänään. Jos arvioitu aika ei mahdu tekijän määräpäivän vapaaseen aikaan, aikataulu alkaa aiemmin, mutta ei ennen tätä päivää.',
|
||||
'task' => 'Tehtävä',
|
||||
'due_on_of' => 'Määräpäivä: :title',
|
||||
'hours_of' => 'Arvioitu aika (h): :title',
|
||||
'assignee_of' => 'Tekijä: :title',
|
||||
'none' => 'Työn palveluyksiköille ei ole käytössä olevia työnkulkupohjia. Pohjia lisäävät pääkäyttäjä ja johto pohjatiedoissa.',
|
||||
'back' => 'Takaisin työhön',
|
||||
'submit' => 'Lisää tehtävät',
|
||||
'choose' => 'Valitse pohja.',
|
||||
'not_available' => 'Pohja ei ole enää käytettävissä tälle työlle. Valitse toinen.',
|
||||
'added' => '{1} Lisättiin 1 tehtävä pohjasta :name.|[2,*] Lisättiin :count tehtävää pohjasta :name.',
|
||||
'scheduled' => '{1} 1 tehtävä aikataulutettiin määräpäivälleen.|[2,*] :count tehtävää aikataulutettiin määräpäivilleen.',
|
||||
'late' => '{1} 1 tehtävä ei mahtunut tekijän päiviin ja päättyy määräpäivän jälkeen.|[2,*] :count tehtävää ei mahtunut tekijöiden päiviin ja päättyy määräpäivän jälkeen.',
|
||||
],
|
||||
'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',
|
||||
'assignee' => 'Tekijä',
|
||||
'assignee_hint' => 'Tehtävä näkyy tekijän rivillä tehtäväkalenterissa ja varaa hänen aikaansa.',
|
||||
'members' => 'Jäsenet',
|
||||
'members_hint' => 'Jäsenet näkevät tehtävän omissa töissään ja tunneissaan, mutta se ei varaa heidän aikaansa kalenterissa.',
|
||||
'status' => 'Tila',
|
||||
'due_on' => 'Määräpäivä',
|
||||
'estimated_hours' => 'Arvioitu aika (h)',
|
||||
'description' => 'Kuvaus',
|
||||
'planned_from' => 'Aikataulu alkaa',
|
||||
'planned_to' => 'Aikataulu päättyy',
|
||||
'planned_hint' => 'Tehtävä näkyy tekijöidensä riveillä tehtäväkalenterissa. Ilman loppua tehtävä kestää yhden päivän.',
|
||||
'planned_hint' => 'Tehtävä näkyy tekijän rivillä tehtäväkalenterissa. Ilman loppua tehtävä kestää yhden päivän.',
|
||||
],
|
||||
'schedule' => 'Aikataulu',
|
||||
'schedule_range' => ':from–:to',
|
||||
@@ -149,6 +157,16 @@ return [
|
||||
'bar_label' => ':title, :job, :status, :from–:to:hours',
|
||||
'bar_hours' => ', :hours h',
|
||||
'continues' => 'jatkuu',
|
||||
'info' => [
|
||||
'job' => 'Työ',
|
||||
'customer' => 'Asiakas',
|
||||
'job_status' => 'Työn tila',
|
||||
'job_due_on' => 'Työn määräpäivä',
|
||||
'responsible' => 'Vastuuhenkilö',
|
||||
'work_type' => 'Työtehtävä',
|
||||
'due_on' => 'Tehtävän määräpäivä',
|
||||
'schedule' => 'Aikataulu',
|
||||
],
|
||||
'unscheduled' => 'Aikatauluttamattomat tehtävät',
|
||||
'unscheduled_intro' => 'Avoimet tehtävät ilman aikataulua. Vedä tehtävä kalenteriin tai valitse Aikatauluta.',
|
||||
'unscheduled_none' => 'Kaikki avoimet tehtävät on aikataulutettu.',
|
||||
@@ -161,7 +179,7 @@ return [
|
||||
'to' => 'Päättyy',
|
||||
'to_hint' => 'Tyhjänä tehtävä saa niin monta arkipäivää kuin arvio vaatii.',
|
||||
'assignee' => 'Tekijä',
|
||||
'assignee_hint' => 'Korvaa tämän rivin tekijän. Muut tekijät säilyvät.',
|
||||
'assignee_hint' => 'Tehtävä siirtyy valitun henkilön riville. Jäsenet säilyvät.',
|
||||
'status' => 'Tila',
|
||||
],
|
||||
'save' => 'Tallenna',
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
* grid cell under the pointer (data-calendar-day / data-calendar-user).
|
||||
* Dragging is only a shortcut: every bar is a button whose dialog makes
|
||||
* the same changes with the keyboard. Escape cancels a drag.
|
||||
*
|
||||
* Hovering or focusing a bar shows its info popover (the job's basic
|
||||
* details); the pointer may move onto it, and Escape closes it.
|
||||
*/
|
||||
const DRAG_THRESHOLD_PX = 5;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
@@ -35,7 +38,82 @@ export function taskCalendar(canManage) {
|
||||
target: null,
|
||||
dragged: false,
|
||||
|
||||
info: null,
|
||||
infoTimer: null,
|
||||
|
||||
/**
|
||||
* Shows the info popover of a bar next to it. Not while dragging.
|
||||
*/
|
||||
showInfo(bar, id) {
|
||||
if (this.drag?.moved) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.keepInfo();
|
||||
|
||||
const popover = document.getElementById(id);
|
||||
|
||||
if (!popover) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.info && this.info !== popover) {
|
||||
this.closeInfo();
|
||||
}
|
||||
|
||||
if (!popover.matches(':popover-open')) {
|
||||
popover.showPopover();
|
||||
}
|
||||
|
||||
this.info = popover;
|
||||
|
||||
const anchor = bar.getBoundingClientRect();
|
||||
const box = popover.getBoundingClientRect();
|
||||
const gap = 4;
|
||||
const below = anchor.bottom + gap;
|
||||
const top = below + box.height <= window.innerHeight || anchor.top - gap - box.height < 0 ? below : anchor.top - gap - box.height;
|
||||
const left = Math.min(Math.max(gap, anchor.left), window.innerWidth - box.width - gap);
|
||||
|
||||
popover.style.top = `${Math.max(gap, top)}px`;
|
||||
popover.style.left = `${Math.max(gap, left)}px`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Hides the popover after a moment, so that the pointer can move onto it.
|
||||
*/
|
||||
hideInfo(id, delay = 150) {
|
||||
this.keepInfo();
|
||||
this.infoTimer = setTimeout(() => {
|
||||
const popover = document.getElementById(id);
|
||||
|
||||
if (popover?.matches(':popover-open')) {
|
||||
popover.hidePopover();
|
||||
}
|
||||
|
||||
if (this.info === popover) {
|
||||
this.info = null;
|
||||
}
|
||||
}, delay);
|
||||
},
|
||||
|
||||
keepInfo() {
|
||||
clearTimeout(this.infoTimer);
|
||||
this.infoTimer = null;
|
||||
},
|
||||
|
||||
closeInfo() {
|
||||
this.keepInfo();
|
||||
|
||||
if (this.info?.matches(':popover-open')) {
|
||||
this.info.hidePopover();
|
||||
}
|
||||
|
||||
this.info = null;
|
||||
},
|
||||
|
||||
begin(event, mode, bar) {
|
||||
this.closeInfo();
|
||||
|
||||
if (!canManage || event.button !== 0 || event.pointerType === 'touch') {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -250,6 +250,8 @@ it('adds tasks from a workflow template with the keyboard, without accessibility
|
||||
->keys('[value="'.$templateId.'"]', 'Space')
|
||||
->assertSee('Pohjan Lyhyt video tehtävät')
|
||||
->assertNoAccessibilityIssues(level: 2)
|
||||
->resize(320, 900)
|
||||
->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)
|
||||
->type('#row-1-hours', '2,5')
|
||||
->keys('main form button[type="submit"]', 'Enter')
|
||||
->assertSee('Lisättiin 2 tehtävää pohjasta Lyhyt video (videokuvaus).')
|
||||
|
||||
@@ -5,7 +5,6 @@ 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;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
@@ -61,6 +60,28 @@ it('reschedules a task with the keyboard and returns focus to its bar', function
|
||||
expect($this->task->refresh()->planned_from?->format('Y-m-d'))->toBe(now()->addDay()->toDateString());
|
||||
});
|
||||
|
||||
it('shows the job details of a bar on hover and focus, and closes them with Escape', function (string $colorScheme) {
|
||||
$key = $this->task->id.'-'.$this->user->id;
|
||||
$open = "document.getElementById('bar-info-{$key}').matches(':popover-open')";
|
||||
|
||||
$visit = visit(route('jobs.calendar'))->on()->desktop();
|
||||
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||
|
||||
$visit->hover('#bar-'.$key)
|
||||
->assertScript($open, true)
|
||||
->assertSee('Messuvideo')
|
||||
->assertSee('Johanna Johto')
|
||||
->assertNoAccessibilityIssues(level: 2)
|
||||
->hover('#bar-info-'.$key)
|
||||
->assertScript($open, true)
|
||||
->keys('#bar-'.$key, 'Escape')
|
||||
->assertScript($open, false)
|
||||
->keys('#bar-'.$key, 'Tab')
|
||||
->keys('#bar-'.$key, 'Shift')
|
||||
->assertScript($open, true)
|
||||
->assertNoJavaScriptErrors();
|
||||
})->with(['light', 'dark']);
|
||||
|
||||
it('moves a task to another person by dragging its bar', function () {
|
||||
// The bar (today – today + 2) is grabbed at its middle day, so dropping it
|
||||
// on today + 4 moves it three days later.
|
||||
@@ -72,7 +93,7 @@ it('moves a task to another person by dragging its bar', function () {
|
||||
->assertSee('Tehtävä Leikkaus: Aino Ahkera');
|
||||
|
||||
expect($this->task->refresh()->planned_from?->format('Y-m-d'))->toBe(now()->addDays(3)->toDateString())
|
||||
->and(DB::table('task_assignees')->where('task_id', $this->task->id)->pluck('user_id')->all())->toBe([$this->other->id]);
|
||||
->and($this->task->assignee_user_id)->toBe($this->other->id);
|
||||
});
|
||||
|
||||
it('has no accessibility issues on the holidays page', function (string $colorScheme) {
|
||||
|
||||
@@ -42,7 +42,8 @@ class InMemoryTaskRepository implements TaskRepository
|
||||
$task->status(),
|
||||
$task->dueOn(),
|
||||
$task->estimatedHours(),
|
||||
$task->assigneeUserIds(),
|
||||
$task->assigneeUserId(),
|
||||
$task->memberUserIds(),
|
||||
$task->createdBy(),
|
||||
$task->plannedFrom(),
|
||||
$task->plannedTo(),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('makes the earlier assignee with most booked time the assignee and the others members', function () {
|
||||
[$eero, $aino, $ville] = User::factory()->count(3)->create()->all();
|
||||
$booked = TaskModel::factory()->create();
|
||||
$unbooked = TaskModel::factory()->create();
|
||||
|
||||
$this->artisan('migrate:rollback', ['--step' => 1])->assertSuccessful();
|
||||
|
||||
DB::table('task_assignees')->insert([
|
||||
['task_id' => $booked->id, 'user_id' => $eero->id],
|
||||
['task_id' => $booked->id, 'user_id' => $aino->id],
|
||||
['task_id' => $unbooked->id, 'user_id' => $ville->id],
|
||||
['task_id' => $unbooked->id, 'user_id' => $aino->id],
|
||||
]);
|
||||
DB::table('task_bookings')->insert([
|
||||
['task_id' => $booked->id, 'user_id' => $eero->id, 'day' => '2026-12-07', 'minutes' => 60],
|
||||
['task_id' => $booked->id, 'user_id' => $aino->id, 'day' => '2026-12-07', 'minutes' => 240],
|
||||
]);
|
||||
|
||||
$this->artisan('migrate')->assertSuccessful();
|
||||
|
||||
expect($booked->refresh()->assignee_user_id)->toBe($aino->id)
|
||||
->and($unbooked->refresh()->assignee_user_id)->toBe(min($aino->id, $ville->id))
|
||||
->and(DB::table('task_members')->where('task_id', $booked->id)->pluck('user_id')->all())->toBe([$eero->id])
|
||||
->and(DB::table('task_members')->where('task_id', $unbooked->id)->pluck('user_id')->all())->toBe([max($aino->id, $ville->id)])
|
||||
->and(DB::table('task_bookings')->pluck('user_id')->all())->toBe([$aino->id]);
|
||||
});
|
||||
@@ -3,6 +3,7 @@
|
||||
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;
|
||||
@@ -53,7 +54,7 @@ it('moves a task to another person by dropping it and books their days', functio
|
||||
|
||||
expect($task->refresh()->planned_from?->format('Y-m-d'))->toBe('2026-12-28')
|
||||
->and($task->planned_to?->format('Y-m-d'))->toBe('2026-12-29')
|
||||
->and(DB::table('task_assignees')->where('task_id', $task->id)->pluck('user_id')->all())->toBe([$this->other->id])
|
||||
->and($task->assignee_user_id)->toBe($this->other->id)
|
||||
->and(DB::table('task_bookings')->where('task_id', $task->id)->orderBy('day')->pluck('minutes', 'day')->all())->toBe(['2026-12-28' => 360, '2026-12-29' => 360]);
|
||||
});
|
||||
|
||||
@@ -106,7 +107,7 @@ it('shows a subcontractor only their own row and lets them change only the statu
|
||||
->assertOk()
|
||||
->assertSee('Oma tehtävä')
|
||||
->assertDontSee('Toisen tehtävä')
|
||||
->assertDontSee('Eero Työntekijä')
|
||||
->assertDontSee('id="row-'.$this->employee->id.'-name"', escape: false)
|
||||
->assertDontSee('Ei tekijää');
|
||||
|
||||
Livewire::test('jobs::calendar')
|
||||
@@ -137,3 +138,43 @@ it('adds a schedule on the task form', function () {
|
||||
expect($task->planned_to?->format('Y-m-d'))->toBe('2026-12-28')
|
||||
->and(DB::table('task_bookings')->where('task_id', $task->id)->sum('minutes'))->toBe(240);
|
||||
});
|
||||
|
||||
it('shows a task only on its assignee row and books nothing for its members', function () {
|
||||
$task = TaskModel::factory()->assignedTo([$this->other->id, $this->employee->id])->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Mainoskuvat', 'estimated_hours' => 4]);
|
||||
|
||||
Livewire::test('jobs::calendar')->call('reschedule', $task->id, $this->job->id, $this->other->id, $this->other->id, '2026-12-22', '2026-12-22');
|
||||
|
||||
expect(DB::table('task_bookings')->where('task_id', $task->id)->pluck('user_id')->unique()->values()->all())->toBe([$this->other->id]);
|
||||
|
||||
Livewire::test('jobs::calendar')
|
||||
->set('mine', true)
|
||||
->assertDontSee('Mainoskuvat');
|
||||
});
|
||||
|
||||
it('leaves the tasks of quick sale jobs out of the unscheduled tasks', function () {
|
||||
$quickSales = CustomerJobModel::factory()->create(['name' => 'Pikamyynnit 2026', 'status' => 'in_production', 'quick_sale_year' => 2026]);
|
||||
calendarTaskModel(['customer_job_id' => $quickSales->id, 'work_type_id' => $this->graphic->id, 'title' => 'Passikuvat'], []);
|
||||
calendarTaskModel(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Mainoskuvat'], [$this->employee->id]);
|
||||
|
||||
Livewire::test('jobs::calendar')
|
||||
->assertSee('Mainoskuvat')
|
||||
->assertDontSee('Passikuvat');
|
||||
});
|
||||
|
||||
it('shows the job details in the info popover of a bar', function () {
|
||||
$this->job->update(['due_on' => '2026-12-31']);
|
||||
calendarTaskModel(['customer_job_id' => $this->job->id, 'work_type_id' => $this->graphic->id, 'title' => 'Mainoskuvat', 'description' => 'Kolme kuvaa somekanaviin', 'planned_from' => '2026-12-22', 'planned_to' => '2026-12-23'], [$this->other->id]);
|
||||
$task = TaskModel::query()->sole();
|
||||
|
||||
Livewire::test('jobs::calendar')
|
||||
->assertSee('aria-describedby="bar-info-'.$task->id.'-'.$this->other->id.'"', escape: false)
|
||||
->assertSeeInOrder([
|
||||
'Työ', $this->job->number, 'Kampanja',
|
||||
'Asiakas', CustomerModel::query()->findOrFail($this->job->customer_id)->name,
|
||||
'Työn tila', 'Tilaus',
|
||||
'Työn määräpäivä', '31.12.2026',
|
||||
'Vastuuhenkilö', 'Eero Työntekijä',
|
||||
'Työtehtävä', 'graafinen työ',
|
||||
'Kolme kuvaa somekanaviin',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -55,7 +55,7 @@ it('adds the steps of a template as tasks of the job', function () {
|
||||
['Kuvat', $this->graphic->id, 'waiting', null],
|
||||
['Julkaisu', $this->graphic->id, 'waiting', null],
|
||||
])
|
||||
->and(DB::table('task_assignees')->pluck('user_id')->unique()->values()->all())->toBe([$this->employee->id]);
|
||||
->and($tasks->pluck('assignee_user_id')->unique()->values()->all())->toBe([$this->employee->id]);
|
||||
|
||||
$this->get(route('jobs.show', $this->job->id))->assertSee('Lisättiin 3 tehtävää pohjasta Somekampanja (graafinen työ).');
|
||||
});
|
||||
@@ -103,13 +103,16 @@ it('shows a table of the chosen template tasks and saves their due dates and est
|
||||
Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id])
|
||||
->assertDontSee('Pohjan Somekampanja tehtävät')
|
||||
->set('templateId', (string) $this->campaign)
|
||||
->assertSet('rows', array_fill(0, 3, ['due_on' => '', 'estimated_hours' => '']))
|
||||
->assertSet('rows', array_fill(0, 3, ['due_on' => '', 'estimated_hours' => '', 'assignee_user_id' => (string) $this->employee->id]))
|
||||
->assertSet('scheduleToDueDates', true)
|
||||
->assertSee('Tekijä: Kuvat')
|
||||
->assertSee('Pohjan Somekampanja tehtävät')
|
||||
->assertSee('Määräpäivä: Kuvat')
|
||||
->assertSee('Arvioitu aika (h): Julkaisu')
|
||||
->set('rows.0.due_on', '2026-06-01')
|
||||
->set('rows.0.estimated_hours', '1,5')
|
||||
->set('rows.2.estimated_hours', '2')
|
||||
->set('scheduleToDueDates', false)
|
||||
->call('add')
|
||||
->assertHasNoErrors();
|
||||
|
||||
@@ -143,3 +146,31 @@ it('empties the rows when another template is chosen', function () {
|
||||
->set('templateId', (string) $this->campaign)
|
||||
->assertSet('rows.0.estimated_hours', '');
|
||||
});
|
||||
|
||||
it('schedules the tasks to their due dates for the chosen assignees, backwards from the due date', function () {
|
||||
$this->travelTo(new DateTimeImmutable('2026-06-01 09:00'));
|
||||
$colleague = User::factory()->create(['name' => 'Aino Ahkera']);
|
||||
|
||||
Livewire::test('jobs::tasks-from-template', ['job' => $this->job->id])
|
||||
->set('templateId', (string) $this->campaign)
|
||||
->set('rows.0.due_on', '2026-06-10')
|
||||
->set('rows.0.estimated_hours', '12')
|
||||
->set('rows.0.assignee_user_id', (string) $colleague->id)
|
||||
->set('rows.1.due_on', '2026-06-10')
|
||||
->set('rows.1.estimated_hours', '4')
|
||||
->set('rows.1.assignee_user_id', '')
|
||||
->call('add')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$tasks = TaskModel::query()->orderBy('id')->get();
|
||||
|
||||
expect($tasks->map(fn ($task) => [$task->assignee_user_id, $task->planned_from?->format('Y-m-d'), $task->planned_to?->format('Y-m-d')])->all())->toBe([
|
||||
[$colleague->id, '2026-06-09', '2026-06-10'],
|
||||
[null, '2026-06-10', '2026-06-10'],
|
||||
[$this->employee->id, null, null],
|
||||
])
|
||||
->and(DB::table('task_bookings')->where('task_id', $tasks[0]->id)->orderBy('day')->pluck('minutes', 'day')->all())->toBe(['2026-06-09' => 240, '2026-06-10' => 480])
|
||||
->and(DB::table('task_bookings')->where('task_id', '!=', $tasks[0]->id)->count())->toBe(0);
|
||||
|
||||
$this->get(route('jobs.show', $this->job->id))->assertSee('2 tehtävää aikataulutettiin määräpäivilleen.');
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use App\Models\User;
|
||||
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
|
||||
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
|
||||
use App\Modules\Jobs\Application\Contracts\TaskQueries;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
@@ -29,7 +30,8 @@ it('adds a task with work types of the job and the shared ones on offer', functi
|
||||
->assertDontSee('painotyö');
|
||||
|
||||
Livewire::test('jobs::task-form', ['job' => $this->job->id])
|
||||
->assertSet('form.assignee_user_ids', [(string) $this->employee->id])
|
||||
->assertSet('form.assignee_user_id', (string) $this->employee->id)
|
||||
->assertSet('form.member_user_ids', [])
|
||||
->set('form.title', 'Mainoskuvat')
|
||||
->set('form.work_type_id', (string) $this->graphic->id)
|
||||
->set('form.due_on', '2026-05-20')
|
||||
@@ -39,7 +41,8 @@ it('adds a task with work types of the job and the shared ones on offer', functi
|
||||
|
||||
$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]);
|
||||
->and($task->assignee_user_id)->toBe($this->employee->id)
|
||||
->and(DB::table('task_members')->where('task_id', $task->id)->count())->toBe(0);
|
||||
|
||||
$this->get(route('jobs.show', $this->job->id))
|
||||
->assertSee('Mainoskuvat')
|
||||
@@ -117,3 +120,34 @@ it('returns 404 for a task of another job', function () {
|
||||
|
||||
$this->get(route('jobs.tasks.edit', [$this->job->id, $other->id]))->assertNotFound();
|
||||
});
|
||||
|
||||
it('saves a task assignee and members apart, and the members find the job among their own', function () {
|
||||
$colleague = User::factory()->create(['name' => 'Aino Ahkera']);
|
||||
$intern = User::factory()->create(['name' => 'Ville Harjoittelija']);
|
||||
|
||||
Livewire::test('jobs::task-form', ['job' => $this->job->id])
|
||||
->set('form.title', 'Mainoskuvat')
|
||||
->set('form.work_type_id', (string) $this->graphic->id)
|
||||
->set('form.assignee_user_id', (string) $colleague->id)
|
||||
->set('form.member_user_ids', [(string) $intern->id, (string) $colleague->id])
|
||||
->call('save')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$task = TaskModel::query()->sole();
|
||||
|
||||
expect($task->assignee_user_id)->toBe($colleague->id)
|
||||
->and(DB::table('task_members')->where('task_id', $task->id)->pluck('user_id')->all())->toBe([$intern->id]);
|
||||
|
||||
$this->get(route('jobs.show', $this->job->id))
|
||||
->assertSeeInOrder(['Tekijä', 'Aino Ahkera', 'Jäsenet', 'Ville Harjoittelija']);
|
||||
|
||||
Livewire::test('jobs::task-form', ['job' => $this->job->id, 'task' => $task->id])
|
||||
->assertSet('form.assignee_user_id', (string) $colleague->id)
|
||||
->assertSet('form.member_user_ids', [(string) $intern->id])
|
||||
->set('form.assignee_user_id', '')
|
||||
->call('save')
|
||||
->assertHasNoErrors();
|
||||
|
||||
expect($task->refresh()->assignee_user_id)->toBeNull()
|
||||
->and(app(TaskQueries::class)->assignedOpenTaskIds($intern->id))->toBe([$task->id]);
|
||||
});
|
||||
|
||||
@@ -26,7 +26,7 @@ beforeEach(function () {
|
||||
$finder = new ChecklistItemFinder($tasks, $this->items);
|
||||
|
||||
$this->jobId = 5;
|
||||
$this->taskId = (int) $tasks->save(Task::reconstitute(1, $this->jobId, 11, new TaskTitle('Kuvaus'), null, TaskStatus::Waiting, null, null, [], 10))->id();
|
||||
$this->taskId = (int) $tasks->save(Task::reconstitute(1, $this->jobId, 11, new TaskTitle('Kuvaus'), null, TaskStatus::Waiting, null, null, null, [], 10))->id();
|
||||
|
||||
$this->add = new AddChecklistItem($finder, $this->items, $transactions);
|
||||
$this->rename = new RenameChecklistItem($finder, $this->items, $transactions);
|
||||
|
||||
@@ -5,21 +5,19 @@ use App\Modules\Jobs\Application\DTOs\CalendarTask;
|
||||
use App\Modules\Jobs\Application\Services\TaskCalendarLayout;
|
||||
use App\Modules\Jobs\Domain\Enums\TaskStatus;
|
||||
|
||||
/**
|
||||
* @param list<CalendarAssignment> $assignments
|
||||
*/
|
||||
function calendarTask(int $id, string $from, string $to, array $assignments, ?string $dueOn = null): CalendarTask
|
||||
function calendarTask(int $id, string $from, string $to, ?CalendarAssignment $assignment, ?string $dueOn = null): CalendarTask
|
||||
{
|
||||
return new CalendarTask($id, 1, '2026-001', 'Kampanja', 'Tehtävä '.$id, TaskStatus::Waiting, $dueOn, null, $from, $to, $assignments);
|
||||
return new CalendarTask($id, 1, '2026-001', 'Kampanja', 'Tehtävä '.$id, TaskStatus::Waiting, $dueOn, null, $from, $to, $assignment);
|
||||
}
|
||||
|
||||
it('puts each task on its assignees rows and overlapping tasks on their own lanes', function () {
|
||||
it('puts each task on its assignee row and overlapping tasks on their own lanes', function () {
|
||||
$days = ['2026-12-07', '2026-12-08', '2026-12-09', '2026-12-10'];
|
||||
$tasks = [
|
||||
calendarTask(1, '2026-12-07', '2026-12-08', [new CalendarAssignment(10, '2026-12-07', '2026-12-08', 480), new CalendarAssignment(11, '2026-12-07', '2026-12-09', 480)]),
|
||||
calendarTask(2, '2026-12-08', '2026-12-08', [new CalendarAssignment(10, '2026-12-08', '2026-12-08', 120)]),
|
||||
calendarTask(3, '2026-12-09', '2026-12-20', [new CalendarAssignment(10, null, null, 0)], dueOn: '2026-12-15'),
|
||||
calendarTask(4, '2026-12-01', '2026-12-07', []),
|
||||
calendarTask(1, '2026-12-07', '2026-12-08', new CalendarAssignment(10, '2026-12-07', '2026-12-08', 480)),
|
||||
calendarTask(2, '2026-12-08', '2026-12-08', new CalendarAssignment(10, '2026-12-08', '2026-12-08', 120)),
|
||||
calendarTask(3, '2026-12-09', '2026-12-20', new CalendarAssignment(10, null, null, 0), dueOn: '2026-12-15'),
|
||||
calendarTask(4, '2026-12-01', '2026-12-07', null),
|
||||
calendarTask(5, '2026-12-07', '2026-12-08', new CalendarAssignment(11, '2026-12-07', '2026-12-09', 480)),
|
||||
];
|
||||
$people = [['id' => 10, 'name' => 'Eero'], ['id' => 11, 'name' => 'Aino'], ['id' => null, 'name' => 'Ei tekijää']];
|
||||
|
||||
@@ -29,7 +27,7 @@ it('puts each task on its assignees rows and overlapping tasks on their own lane
|
||||
expect($bars(0))->toBe([[1, 0, 2, 0, false], [2, 1, 1, 1, false], [3, 2, 2, 0, true]])
|
||||
->and($rows[0]->lanes)->toBe(2)
|
||||
->and($rows[0]->minutesByDay)->toBe(['2026-12-07' => 0, '2026-12-08' => 360, '2026-12-09' => 0, '2026-12-10' => 0])
|
||||
->and($bars(1))->toBe([[1, 0, 3, 0, false]])
|
||||
->and($bars(1))->toBe([[5, 0, 3, 0, false]])
|
||||
->and($bars(2))->toBe([[4, 0, 1, 0, false]])
|
||||
->and(array_map(fn ($bar) => $bar->task->taskId, $rows[0]->barsOn(1)))->toBe([1, 2]);
|
||||
});
|
||||
|
||||
@@ -83,27 +83,28 @@ it('allows tasks from a quote request on, not before and not when archived', fun
|
||||
});
|
||||
|
||||
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);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting', dueOn: '2026-05-20', estimatedHours: '3,5', assigneeUserId: 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($task?->assigneeUserId())->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) {
|
||||
it('rejects a work type of another unit and an inactive assignee or member', function (int $workTypeId, ?int $assignee, array $members, string $field) {
|
||||
try {
|
||||
$this->addTask->execute($this->jobId, new TaskData('Työ', $workTypeId, 'waiting', assigneeUserIds: $assignees), 10);
|
||||
$this->addTask->execute($this->jobId, new TaskData('Työ', $workTypeId, 'waiting', assigneeUserId: $assignee, memberUserIds: $members), 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'],
|
||||
'work type of another unit' => [21, null, [], 'work_type'],
|
||||
'inactive assignee' => [11, 12, [], 'assignee'],
|
||||
'inactive member' => [11, 10, [12], 'members'],
|
||||
]);
|
||||
|
||||
it('changes, moves through statuses and removes a task', function () {
|
||||
@@ -150,8 +151,8 @@ it('does not remove a task with time entries', function () {
|
||||
});
|
||||
|
||||
it('books a scheduled task evenly from the working days of its period', function () {
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '12', assigneeUserIds: [10], plannedFrom: '2026-12-04', plannedTo: '2026-12-07'), 10);
|
||||
$oneDayId = $this->addTask->execute($this->jobId, new TaskData('Palaveri', 91, 'waiting', assigneeUserIds: [10], plannedFrom: '2026-12-08'), 10);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '12', assigneeUserId: 10, plannedFrom: '2026-12-04', plannedTo: '2026-12-07'), 10);
|
||||
$oneDayId = $this->addTask->execute($this->jobId, new TaskData('Palaveri', 91, 'waiting', assigneeUserId: 10, plannedFrom: '2026-12-08'), 10);
|
||||
|
||||
expect($this->bookings->of($taskId, 10))->toBe(['2026-12-04' => 360, '2026-12-07' => 360])
|
||||
->and($this->tasks->findForJob($this->jobId, $oneDayId)?->plannedTo()?->format('Y-m-d'))->toBe('2026-12-08')
|
||||
@@ -159,8 +160,8 @@ it('books a scheduled task evenly from the working days of its period', function
|
||||
});
|
||||
|
||||
it('moves what does not fit in a full day to the next working day', function () {
|
||||
$this->addTask->execute($this->jobId, new TaskData('Kuvaus', 11, 'waiting', estimatedHours: '6', assigneeUserIds: [10], plannedFrom: '2026-12-04'), 10);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserIds: [10]), 10);
|
||||
$this->addTask->execute($this->jobId, new TaskData('Kuvaus', 11, 'waiting', estimatedHours: '6', assigneeUserId: 10, plannedFrom: '2026-12-04'), 10);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserId: 10), 10);
|
||||
|
||||
$result = $this->scheduleTask->execute($this->jobId, $taskId, 10, 10, '2026-12-04', '2026-12-04');
|
||||
|
||||
@@ -170,20 +171,20 @@ it('moves what does not fit in a full day to the next working day', function ()
|
||||
});
|
||||
|
||||
it('does not count done tasks in the day load', function () {
|
||||
$doneId = $this->addTask->execute($this->jobId, new TaskData('Kuvaus', 11, 'waiting', estimatedHours: '8', assigneeUserIds: [10], plannedFrom: '2026-12-04'), 10);
|
||||
$doneId = $this->addTask->execute($this->jobId, new TaskData('Kuvaus', 11, 'waiting', estimatedHours: '8', assigneeUserId: 10, plannedFrom: '2026-12-04'), 10);
|
||||
$this->changeTaskStatus->execute($this->jobId, $doneId, TaskStatus::Done);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '8', assigneeUserIds: [10], plannedFrom: '2026-12-04'), 10);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '8', assigneeUserId: 10, plannedFrom: '2026-12-04'), 10);
|
||||
|
||||
expect($this->bookings->of($taskId, 10))->toBe(['2026-12-04' => 480]);
|
||||
});
|
||||
|
||||
it('moves a task to another person and gives it the days its estimate needs', function () {
|
||||
$this->users->addUser(11, 'Aino');
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '20', assigneeUserIds: [10], plannedFrom: '2026-12-01'), 10);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '20', assigneeUserId: 10, plannedFrom: '2026-12-01'), 10);
|
||||
|
||||
$result = $this->scheduleTask->execute($this->jobId, $taskId, 10, 11, '2026-12-11', null);
|
||||
|
||||
expect($this->tasks->findForJob($this->jobId, $taskId)?->assigneeUserIds())->toBe([11])
|
||||
expect($this->tasks->findForJob($this->jobId, $taskId)?->assigneeUserId())->toBe(11)
|
||||
->and($result->plannedFrom)->toBe('2026-12-11')
|
||||
->and($result->plannedTo)->toBe('2026-12-15')
|
||||
->and($result->extended)->toBeFalse()
|
||||
@@ -192,17 +193,48 @@ it('moves a task to another person and gives it the days its estimate needs', fu
|
||||
});
|
||||
|
||||
it('rejects moving a task to an inactive person or ending it before it starts', function () {
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', assigneeUserIds: [10]), 10);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', assigneeUserId: 10), 10);
|
||||
|
||||
expect(fn () => $this->scheduleTask->execute($this->jobId, $taskId, 10, 12, '2026-12-07', '2026-12-07'))->toThrow(InvalidTaskReference::class)
|
||||
->and(fn () => $this->scheduleTask->execute($this->jobId, $taskId, 10, 10, '2026-12-07', '2026-12-04'))->toThrow(PlanEndsBeforeStart::class);
|
||||
});
|
||||
|
||||
it('takes a task out of the calendar', function () {
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserIds: [10], plannedFrom: '2026-12-07'), 10);
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserId: 10, plannedFrom: '2026-12-07'), 10);
|
||||
|
||||
$this->clearSchedule->execute($this->jobId, $taskId);
|
||||
|
||||
expect($this->tasks->findForJob($this->jobId, $taskId)?->isScheduled())->toBeFalse()
|
||||
->and($this->bookings->of($taskId, 10))->toBe([]);
|
||||
});
|
||||
|
||||
it('books only the assignee, not the members, and keeps the assignee out of the members', function () {
|
||||
$this->users->addUser(11, 'Aino');
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserId: 10, memberUserIds: [11, 10], plannedFrom: '2026-12-07'), 10);
|
||||
$task = $this->tasks->findForJob($this->jobId, $taskId);
|
||||
|
||||
expect($task?->memberUserIds())->toBe([11])
|
||||
->and($this->bookings->of($taskId, 10))->toBe(['2026-12-07' => 240])
|
||||
->and($this->bookings->of($taskId, 11))->toBe([]);
|
||||
});
|
||||
|
||||
it('moves a task to a member, who then is the assignee and no longer a member', function () {
|
||||
$this->users->addUser(11, 'Aino');
|
||||
$this->users->addUser(13, 'Ville');
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserId: 10, memberUserIds: [11, 13], plannedFrom: '2026-12-07'), 10);
|
||||
|
||||
$this->scheduleTask->execute($this->jobId, $taskId, 10, 11, '2026-12-07', '2026-12-07');
|
||||
$task = $this->tasks->findForJob($this->jobId, $taskId);
|
||||
|
||||
expect($task?->assigneeUserId())->toBe(11)
|
||||
->and($task?->memberUserIds())->toBe([13])
|
||||
->and($this->bookings->of($taskId, 10))->toBe([])
|
||||
->and($this->bookings->of($taskId, 11))->toBe(['2026-12-07' => 240]);
|
||||
});
|
||||
|
||||
it('books nothing for a task without an assignee', function () {
|
||||
$taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', memberUserIds: [10], plannedFrom: '2026-12-07'), 10);
|
||||
|
||||
expect($this->bookings->of($taskId, 10))->toBe([])
|
||||
->and($this->tasks->findForJob($this->jobId, $taskId)?->plannedTo()?->format('Y-m-d'))->toBe('2026-12-07');
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use App\Modules\Jobs\Application\DTOs\CustomerJobData;
|
||||
use App\Modules\Jobs\Application\DTOs\TemplateTaskSchedule;
|
||||
use App\Modules\Jobs\Application\Services\JobDetailsFactory;
|
||||
use App\Modules\Jobs\Application\Services\TaskPlanner;
|
||||
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
|
||||
use App\Modules\Jobs\Application\UseCases\AddTasksFromWorkflowTemplate;
|
||||
use App\Modules\Jobs\Application\UseCases\CreateCustomerJob;
|
||||
@@ -12,13 +13,17 @@ 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\Shared\Application\UseCases\HolidayCalendar;
|
||||
use Tests\Fakes\FakeCatalogQueries;
|
||||
use Tests\Fakes\FakeClock;
|
||||
use Tests\Fakes\FakeCustomerQueries;
|
||||
use Tests\Fakes\FakeSettings;
|
||||
use Tests\Fakes\FakeTransactionManager;
|
||||
use Tests\Fakes\FakeUserAccountQueries;
|
||||
use Tests\Fakes\FakeWorkflowTemplateQueries;
|
||||
use Tests\Fakes\InMemoryCustomerJobRepository;
|
||||
use Tests\Fakes\InMemoryHolidayOverrides;
|
||||
use Tests\Fakes\InMemoryTaskBookingRepository;
|
||||
use Tests\Fakes\InMemoryTaskRepository;
|
||||
|
||||
beforeEach(function () {
|
||||
@@ -39,6 +44,8 @@ beforeEach(function () {
|
||||
$catalog->addWorkType(21, 2, 'painotyö');
|
||||
$catalog->addWorkType(91, 9, 'suunnittelu');
|
||||
$users->addUser(10, 'Eero');
|
||||
$users->addUser(11, 'Aino');
|
||||
$users->addUser(12, 'Pois', active: false);
|
||||
|
||||
$createJob = new CreateCustomerJob($this->jobs, $this->jobs, new JobDetailsFactory($customers, $catalog, $users), $transactions, new FakeClock(new DateTimeImmutable('2026-05-01')));
|
||||
$this->jobId = $createJob->execute(new CustomerJobData('Video', 1, [1], 10, 'one_off', 'quote_request', 'normal'), 10);
|
||||
@@ -49,18 +56,20 @@ beforeEach(function () {
|
||||
$this->templates->addTemplate(3, 'Vanha', 11, 1, [['Kuvaus']], active: false);
|
||||
$this->templates->addTemplate(4, 'Rikki', 11, 1, [['Painatus', 21]]);
|
||||
|
||||
$this->addTasks = new AddTasksFromWorkflowTemplate($this->jobs, $this->tasks, $this->templates, new TaskReferenceChecker($catalog, $users), $transactions);
|
||||
$this->bookings = new InMemoryTaskBookingRepository($this->tasks);
|
||||
$planner = new TaskPlanner($this->bookings, new HolidayCalendar(new InMemoryHolidayOverrides), new FakeSettings);
|
||||
$this->addTasks = new AddTasksFromWorkflowTemplate($this->jobs, $this->tasks, $this->templates, new TaskReferenceChecker($catalog, $users), $planner, new FakeClock(new DateTimeImmutable('2026-05-01')), $transactions);
|
||||
});
|
||||
|
||||
it('adds a waiting task per step in order, with the step work type and the adder as assignee', function () {
|
||||
expect($this->addTasks->execute($this->jobId, 1, 10))->toBe(3);
|
||||
expect($this->addTasks->execute($this->jobId, 1, 10)->added)->toBe(3);
|
||||
|
||||
$tasks = array_values($this->tasks->tasks);
|
||||
|
||||
expect(array_map(fn (Task $task): array => [$task->title()->value, $task->workTypeId(), $task->status(), $task->assigneeUserIds()], $tasks))->toBe([
|
||||
['Suunnittelu', 91, TaskStatus::Waiting, [10]],
|
||||
['Kuvaus', 11, TaskStatus::Waiting, [10]],
|
||||
['Editointi', 12, TaskStatus::Waiting, [10]],
|
||||
expect(array_map(fn (Task $task): array => [$task->title()->value, $task->workTypeId(), $task->status(), $task->assigneeUserId(), $task->isScheduled()], $tasks))->toBe([
|
||||
['Suunnittelu', 91, TaskStatus::Waiting, 10, false],
|
||||
['Kuvaus', 11, TaskStatus::Waiting, 10, false],
|
||||
['Editointi', 12, TaskStatus::Waiting, 10, false],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -94,3 +103,71 @@ it('gives each task the due date and estimate entered for its step', function ()
|
||||
it('rejects an estimate that is not a number', function () {
|
||||
$this->addTasks->execute($this->jobId, 1, 10, [new TemplateTaskSchedule(null, 'paljon')]);
|
||||
})->throws(InvalidEstimatedHours::class);
|
||||
|
||||
/**
|
||||
* @param array<int, Task> $tasks
|
||||
* @return list<array{0: ?string, 1: ?string}>
|
||||
*/
|
||||
function plannedPeriods(array $tasks): array
|
||||
{
|
||||
return array_map(fn (Task $task): array => [$task->plannedFrom()?->format('Y-m-d'), $task->plannedTo()?->format('Y-m-d')], array_values($tasks));
|
||||
}
|
||||
|
||||
it('gives each task the assignee chosen for its step', function () {
|
||||
$this->addTasks->execute($this->jobId, 1, 10, [
|
||||
new TemplateTaskSchedule(null, null, 11),
|
||||
new TemplateTaskSchedule(null, null, null),
|
||||
new TemplateTaskSchedule(null, null, 10),
|
||||
]);
|
||||
|
||||
expect(array_map(fn (Task $task): ?int => $task->assigneeUserId(), array_values($this->tasks->tasks)))->toBe([11, null, 10]);
|
||||
});
|
||||
|
||||
it('rejects an inactive assignee', function () {
|
||||
try {
|
||||
$this->addTasks->execute($this->jobId, 1, 10, [new TemplateTaskSchedule(null, null, 12)]);
|
||||
$this->fail('No exception');
|
||||
} catch (InvalidTaskReference $exception) {
|
||||
expect($exception->field)->toBe('assignee');
|
||||
}
|
||||
});
|
||||
|
||||
it('schedules tasks to end on their due dates, booking backwards from the due date past full days', function () {
|
||||
$result = $this->addTasks->execute($this->jobId, 1, 10, [
|
||||
new TemplateTaskSchedule('2026-05-12', '12', 10),
|
||||
new TemplateTaskSchedule('2026-05-12', '6', 10),
|
||||
new TemplateTaskSchedule(null, '2', 10),
|
||||
], scheduleToDueDates: true);
|
||||
|
||||
[$first, $second] = array_keys($this->tasks->tasks);
|
||||
|
||||
expect([$result->added, $result->scheduled, $result->late])->toBe([3, 2, 0])
|
||||
->and(plannedPeriods($this->tasks->tasks))->toBe([['2026-05-11', '2026-05-12'], ['2026-05-08', '2026-05-12'], [null, null]])
|
||||
->and($this->bookings->of($first, 10))->toBe(['2026-05-11' => 240, '2026-05-12' => 480])
|
||||
->and($this->bookings->of($second, 10))->toBe(['2026-05-08' => 120, '2026-05-11' => 240]);
|
||||
});
|
||||
|
||||
it('does not schedule before today and lets the rest run past the due date', function () {
|
||||
$result = $this->addTasks->execute($this->jobId, 1, 10, [new TemplateTaskSchedule('2026-05-04', '20', 10)], scheduleToDueDates: true);
|
||||
$taskId = array_key_first($this->tasks->tasks);
|
||||
|
||||
// Today, 1.5., is May Day, so only Monday 4.5. is free before the due date.
|
||||
expect([$result->scheduled, $result->late])->toBe([1, 1])
|
||||
->and(plannedPeriods([$this->tasks->tasks[$taskId]]))->toBe([['2026-05-04', '2026-05-06']])
|
||||
->and($this->bookings->of($taskId, 10))->toBe(['2026-05-04' => 480, '2026-05-05' => 480, '2026-05-06' => 240]);
|
||||
});
|
||||
|
||||
it('gives a task without an assignee the working days its estimate needs before the due date, without bookings', function () {
|
||||
$this->addTasks->execute($this->jobId, 1, 10, [new TemplateTaskSchedule('2026-05-12', '12', null)], scheduleToDueDates: true);
|
||||
$taskId = array_key_first($this->tasks->tasks);
|
||||
|
||||
expect(plannedPeriods([$this->tasks->tasks[$taskId]]))->toBe([['2026-05-11', '2026-05-12']])
|
||||
->and($this->bookings->bookings[$taskId] ?? [])->toBe([]);
|
||||
});
|
||||
|
||||
it('leaves the tasks unscheduled when scheduling to due dates is off', function () {
|
||||
$result = $this->addTasks->execute($this->jobId, 1, 10, [new TemplateTaskSchedule('2026-05-12', '12', 10)]);
|
||||
|
||||
expect($result->scheduled)->toBe(0)
|
||||
->and(plannedPeriods($this->tasks->tasks)[0])->toBe([null, null]);
|
||||
});
|
||||
|
||||
@@ -45,3 +45,18 @@ it('gives a placed task the working days its estimate needs', function () {
|
||||
->and(TaskScheduler::defaultEnd(scheduleDay('2026-12-23'), 960, 480, ['2026-12-24', '2026-12-25'])->format('Y-m-d'))->toBe('2026-12-28')
|
||||
->and(TaskScheduler::defaultEnd(scheduleDay('2026-12-05'), 0, 480, [])->format('Y-m-d'))->toBe('2026-12-05');
|
||||
});
|
||||
|
||||
it('books backwards from a due date on a weekend, past holidays and other bookings', function () {
|
||||
// Due Sat 26.12.2026; 24.–25.12. are holidays and Wed 23.12. is half booked.
|
||||
$schedule = TaskScheduler::scheduleBackwards(scheduleDay('2026-12-26'), 720, ['2026-12-23' => 240], 480, ['2026-12-24', '2026-12-25'], scheduleDay('2026-12-01'));
|
||||
|
||||
expect($schedule->minutesByDay)->toBe(['2026-12-22' => 480, '2026-12-23' => 240])
|
||||
->and($schedule->end->format('Y-m-d'))->toBe('2026-12-26')
|
||||
->and($schedule->extended)->toBeFalse();
|
||||
});
|
||||
|
||||
it('starts a task without an assignee as many working days before its end as the estimate needs, not before the earliest day', function () {
|
||||
expect(TaskScheduler::defaultStart(scheduleDay('2026-12-08'), 1200, 480, [], scheduleDay('2026-12-01'))->format('Y-m-d'))->toBe('2026-12-04')
|
||||
->and(TaskScheduler::defaultStart(scheduleDay('2026-12-08'), 1200, 480, [], scheduleDay('2026-12-07'))->format('Y-m-d'))->toBe('2026-12-07')
|
||||
->and(TaskScheduler::defaultStart(scheduleDay('2026-12-08'), 0, 480, [], scheduleDay('2026-12-01'))->format('Y-m-d'))->toBe('2026-12-08');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user