diff --git a/CLAUDE.md b/CLAUDE.md index a0ee723..7313320 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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: ``, ``), 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: ``, ``), 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. diff --git a/app/Modules/Jobs/Application/Contracts/TaskCalendarQueries.php b/app/Modules/Jobs/Application/Contracts/TaskCalendarQueries.php index a9b46ae..b15b80c 100644 --- a/app/Modules/Jobs/Application/Contracts/TaskCalendarQueries.php +++ b/app/Modules/Jobs/Application/Contracts/TaskCalendarQueries.php @@ -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 */ diff --git a/app/Modules/Jobs/Application/DTOs/CalendarAssignment.php b/app/Modules/Jobs/Application/DTOs/CalendarAssignment.php index 99355b8..d1d6988 100644 --- a/app/Modules/Jobs/Application/DTOs/CalendarAssignment.php +++ b/app/Modules/Jobs/Application/DTOs/CalendarAssignment.php @@ -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. */ diff --git a/app/Modules/Jobs/Application/DTOs/CalendarTask.php b/app/Modules/Jobs/Application/DTOs/CalendarTask.php index db42222..bc6e738 100644 --- a/app/Modules/Jobs/Application/DTOs/CalendarTask.php +++ b/app/Modules/Jobs/Application/DTOs/CalendarTask.php @@ -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 $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; } } diff --git a/app/Modules/Jobs/Application/DTOs/TaskData.php b/app/Modules/Jobs/Application/DTOs/TaskData.php index 7f160d6..da6e314 100644 --- a/app/Modules/Jobs/Application/DTOs/TaskData.php +++ b/app/Modules/Jobs/Application/DTOs/TaskData.php @@ -11,7 +11,7 @@ namespace App\Modules\Jobs\Application\DTOs; final readonly class TaskData { /** - * @param list $assigneeUserIds + * @param list $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, ) {} diff --git a/app/Modules/Jobs/Application/DTOs/TaskSummary.php b/app/Modules/Jobs/Application/DTOs/TaskSummary.php index 5ed7a1e..8fe16e9 100644 --- a/app/Modules/Jobs/Application/DTOs/TaskSummary.php +++ b/app/Modules/Jobs/Application/DTOs/TaskSummary.php @@ -12,7 +12,7 @@ use App\Modules\Jobs\Domain\Enums\TaskStatus; final readonly class TaskSummary { /** - * @param list $assignees + * @param list $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, ) {} diff --git a/app/Modules/Jobs/Application/DTOs/TemplateTaskSchedule.php b/app/Modules/Jobs/Application/DTOs/TemplateTaskSchedule.php index f0296c0..33cbf86 100644 --- a/app/Modules/Jobs/Application/DTOs/TemplateTaskSchedule.php +++ b/app/Modules/Jobs/Application/DTOs/TemplateTaskSchedule.php @@ -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, ) {} } diff --git a/app/Modules/Jobs/Application/DTOs/TemplateTasksResult.php b/app/Modules/Jobs/Application/DTOs/TemplateTasksResult.php new file mode 100644 index 0000000..190ae4c --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/TemplateTasksResult.php @@ -0,0 +1,19 @@ +assignments !== []) { + if ($task->assignment !== null) { return null; } diff --git a/app/Modules/Jobs/Application/Services/TaskPlanner.php b/app/Modules/Jobs/Application/Services/TaskPlanner.php index b5d928d..e7d5308 100644 --- a/app/Modules/Jobs/Application/Services/TaskPlanner.php +++ b/app/Modules/Jobs/Application/Services/TaskPlanner.php @@ -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); + } } diff --git a/app/Modules/Jobs/Application/Services/TaskReferenceChecker.php b/app/Modules/Jobs/Application/Services/TaskReferenceChecker.php index 8a06723..d192c7c 100644 --- a/app/Modules/Jobs/Application/Services/TaskReferenceChecker.php +++ b/app/Modules/Jobs/Application/Services/TaskReferenceChecker.php @@ -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 $assigneeUserIds + * @param list $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'); } } } diff --git a/app/Modules/Jobs/Application/UseCases/AddTask.php b/app/Modules/Jobs/Application/UseCases/AddTask.php index aaeeec8..700ae03 100644 --- a/app/Modules/Jobs/Application/UseCases/AddTask.php +++ b/app/Modules/Jobs/Application/UseCases/AddTask.php @@ -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), diff --git a/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php b/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php index 214b0a8..656c91f 100644 --- a/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php +++ b/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php @@ -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 $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 $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); }); } diff --git a/app/Modules/Jobs/Application/UseCases/ProvideQuickSaleTask.php b/app/Modules/Jobs/Application/UseCases/ProvideQuickSaleTask.php index 1afda04..09dc897 100644 --- a/app/Modules/Jobs/Application/UseCases/ProvideQuickSaleTask.php +++ b/app/Modules/Jobs/Application/UseCases/ProvideQuickSaleTask.php @@ -72,6 +72,7 @@ final class ProvideQuickSaleTask TaskStatus::InProgress, null, null, + null, [], $actorUserId, )); diff --git a/app/Modules/Jobs/Application/UseCases/ScheduleTask.php b/app/Modules/Jobs/Application/UseCases/ScheduleTask.php index 482d502..d5ed350 100644 --- a/app/Modules/Jobs/Application/UseCases/ScheduleTask.php +++ b/app/Modules/Jobs/Application/UseCases/ScheduleTask.php @@ -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); diff --git a/app/Modules/Jobs/Application/UseCases/UpdateTask.php b/app/Modules/Jobs/Application/UseCases/UpdateTask.php index 026acf0..866707d 100644 --- a/app/Modules/Jobs/Application/UseCases/UpdateTask.php +++ b/app/Modules/Jobs/Application/UseCases/UpdateTask.php @@ -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} + * @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(), ]; } } diff --git a/app/Modules/Jobs/Domain/Entities/Task.php b/app/Modules/Jobs/Domain/Entities/Task.php index 87efd01..e1a06ea 100644 --- a/app/Modules/Jobs/Domain/Entities/Task.php +++ b/app/Modules/Jobs/Domain/Entities/Task.php @@ -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 $assigneeUserIds + * @param list $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 $assigneeUserIds + * @param list $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 $assigneeUserIds + * @param list $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 $assigneeUserIds + * @param list $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 $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 */ - 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 $ids * @return list */ - 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; diff --git a/app/Modules/Jobs/Domain/Services/TaskScheduler.php b/app/Modules/Jobs/Domain/Services/TaskScheduler.php index 6e3ff05..9effd4c 100644 --- a/app/Modules/Jobs/Domain/Services/TaskScheduler.php +++ b/app/Modules/Jobs/Domain/Services/TaskScheduler.php @@ -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 $otherMinutes Y-m-d => minutes booked by the assignee's other open tasks. + * @param list $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 $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 $otherMinutes + * @param array $holidaySet + * @return array 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 $booked + * @param array $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 $otherMinutes */ diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php index 5460d6a..7f77341 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskModel.php @@ -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', ]; } diff --git a/app/Modules/Jobs/Infrastructure/Persistence/JobInvolvement.php b/app/Modules/Jobs/Infrastructure/Persistence/JobInvolvement.php index 3a544e0..58064ad 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/JobInvolvement.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/JobInvolvement.php @@ -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; } diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCalendarQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCalendarQueries.php index 996644c..c75110d 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCalendarQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskCalendarQueries.php @@ -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 $values + * @return list + */ + 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); diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php index 28f1b4c..595bcef 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php @@ -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() diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php index 98d4b1c..8a8458b 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php @@ -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), diff --git a/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php b/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php index 9cbe19d..a98277a 100644 --- a/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php +++ b/app/Modules/Jobs/Presentation/Livewire/Forms/TaskForm.php @@ -36,8 +36,10 @@ class TaskForm extends Form public string $description = ''; + public string $assignee_user_id = ''; + /** @var list */ - 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'], ]; } diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php index 9633e7e..2ca38a0 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php @@ -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)" > + + {{-- The day's booked time on its own grid line, above the task bars. --}} + @if ($row->userId !== null && ($booked > 0 || ! $this->isDayOff($day))) +
$booked > $this->capacityMinutes, + 'text-zinc-600 dark:text-zinc-300' => $booked === 0, + ]) + style="grid-column: {{ $index + 2 }}; grid-row: 1;" + > {{ $this->dayLabel($day) }}: - $booked > $this->capacityMinutes])> - {{ __('jobs.calendar.load', ['booked' => $this->hours($booked), 'capacity' => $capacity]) }} - @if ($booked > $this->capacityMinutes) - - @endif -
+ {{ __('jobs.calendar.load', ['booked' => $this->hours($booked), 'capacity' => $capacity]) }} + @if ($booked > $this->capacityMinutes) +