$schedules In step order; a missing one leaves the task without a due date and estimate. * @return int How many tasks were added. * * @throws CustomerJobNotFound * @throws InvalidEstimatedHours * @throws TasksNotAllowedYet * @throws WorkflowTemplateNotAvailable * @throws InvalidTaskReference when a step's work type is not available for the job */ public function execute(int $jobId, int $templateId, int $actorUserId, array $schedules = []): int { $dueDates = array_map(fn (TemplateTaskSchedule $schedule) => TaskInput::date($schedule->dueOn), $schedules); $estimates = array_map(fn (TemplateTaskSchedule $schedule) => TaskInput::hours($schedule->estimatedHours), $schedules); return $this->transactions->run(function () use ($jobId, $templateId, $actorUserId, $dueDates, $estimates): int { $job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId); $template = $this->availableTemplate($templateId, $job->details()->serviceUnitIds); foreach ($template->steps as $index => $step) { $this->references->check($job, $step->effectiveWorkTypeId, [$actorUserId]); $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, [$actorUserId], $actorUserId, )); } return count($template->steps); }); } /** * @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); } }