$steps * * @throws InvalidProductionStep with nothing saved * @throws ProductionMachineNotAllowed */ public function execute(int $productId, array $steps): void { $product = $this->priceList->findProduct($productId) ?? throw new InvalidProductionStep; $allowedUnits = $this->allowedUnits($product->workTypeId); $parsed = []; foreach ($steps as $step) { if ($this->catalog->findWorkType($step->workTypeId) === null) { throw new InvalidProductionStep; } if ($step->machineId !== null) { $machine = $this->machines->findById($step->machineId); if ($machine === null || ! $machine->isActive() || ! $machine->servesAnyOf($allowedUnits)) { throw new ProductionMachineNotAllowed; } } $parsed[] = new ProductionStep($step->machineId, $this->quarters($step->duration), $step->workTypeId, $this->materials($step->materials)); } $this->transactions->run(fn () => $this->processes->replace($productId, $parsed)); } /** * @return list */ private function allowedUnits(?int $workTypeId): array { $stockUnits = $this->catalog->stockServiceUnitIds(); $workType = $workTypeId === null ? null : $this->catalog->findWorkType($workTypeId); $unit = $workType === null ? null : $this->catalog->findServiceUnit($workType->serviceUnitId); return $unit === null || $unit->isShared ? $stockUnits : array_values(array_intersect([$unit->id], $stockUnits)); } /** * @throws InvalidProductionStep */ private function quarters(string $duration): int { $duration = str_replace(',', '.', trim($duration)); if ($duration === '') { return 0; } if (! is_numeric($duration) || fmod((float) $duration * 4, 1.0) !== 0.0) { throw new InvalidProductionStep; } return (int) round((float) $duration * 4); } /** * @param list $materials * @return list * * @throws InvalidProductionStep */ private function materials(array $materials): array { $parsed = []; foreach ($materials as $material) { try { $parsed[] = ['stockItemId' => $material['stockItemId'], 'quantityMilli' => Reading::parse($material['quantity']) ?? 0]; } catch (InvalidReading) { throw new InvalidProductionStep; } } return $parsed; } }