catalog->findWorkType($workTypeId) ?? throw new InvalidTaskReference('work_type'); $unit = $this->catalog->findServiceUnit($workType->serviceUnitId); $unitId = $unit !== null && ! $unit->isShared ? $unit->id : null; return $this->transactions->run(function () use ($year, $workTypeId, $workType, $unitId, $actorUserId, $jobName): int { $job = $this->jobs->findQuickSaleJob($year) ?? $this->openJob($year, $unitId, $actorUserId, $jobName); $jobId = (int) $job->id(); if ($unitId !== null && ! in_array($unitId, $job->details()->serviceUnitIds, true)) { $changes = $job->changeDetails($job->details()->withServiceUnit($unitId)); $this->jobs->save($job); $this->jobs->recordChanges($jobId, $actorUserId, $changes); } $task = $this->tasks->findByWorkType($jobId, $workTypeId) ?? $this->tasks->save(Task::create( $jobId, $job->details()->status, $workTypeId, new TaskTitle($workType->name), null, TaskStatus::InProgress, null, null, null, [], $actorUserId, )); return (int) $task->id(); }); } private function openJob(int $year, ?int $unitId, int $actorUserId, string $jobName): CustomerJob { $customerId = $this->customers->internalCustomerId() ?? throw new LogicException('The internal customer is missing.'); $unitId ??= $this->catalog->activeServiceUnits()[0]->id ?? throw new LogicException('There are no service units.'); $details = new JobDetails( name: new JobName($jobName), description: null, customerId: $customerId, serviceUnitIds: [$unitId], startsOn: null, dueOn: null, plannedFrom: null, plannedTo: null, kind: JobKind::Ongoing, status: JobStatus::InProduction, priority: Priority::Normal, paymentBasis: PaymentBasis::NotBillable, estimatedHours: null, customerReference: null, instructions: null, responsibleUserId: $actorUserId, contactUserId: null, customerContactId: null, billerUserId: null, billingUnitId: null, memberUserIds: [], tags: [], links: [], ); $job = $this->jobs->save(CustomerJob::open($this->numbers->next($year), $details, $actorUserId)); $jobId = (int) $job->id(); $this->jobs->markAsQuickSaleJob($jobId, $year); $this->jobs->recordChanges($jobId, $actorUserId, [new FieldChange('created', null, $job->number()->format())]); return $job; } }