$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, or the assignee is not active */ 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, $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) { $assigneeUserId = array_key_exists($index, $assignees) ? $assignees[$index] : $actorUserId; $this->references->check($job, $step->effectiveWorkTypeId, $assigneeUserId); $task = $this->tasks->save(Task::create( $jobId, $job->details()->status, $step->effectiveWorkTypeId, new TaskTitle($step->title), $step->description, TaskStatus::Waiting, $dueDates[$index] ?? null, $estimates[$index] ?? null, $assigneeUserId, [], $actorUserId, )); if ($scheduleToDueDates && $task->dueOn() !== null) { $late += $this->planner->planBackwards($task, $today) ? 1 : 0; $scheduled++; $this->tasks->save($task); } $added = PeopleAddedToTask::between(null, $task, $job, $actorUserId); if ($added !== null) { $this->events->dispatch($added); } } return new TemplateTasksResult(count($template->steps), $scheduled, $late); }); } /** * @param list $serviceUnitIds */ private function availableTemplate(int $templateId, array $serviceUnitIds): WorkflowTemplateDetails { foreach ($this->templates->activeFor($serviceUnitIds) as $template) { if ($template->id === $templateId) { return $template; } } throw new WorkflowTemplateNotAvailable($templateId); } }