$input * @return array */ public function preview(User $actor, array $input): array { abort_unless($this->ready(), 503); return DB::transaction(function () use ($actor, $input): array { $selection = app(OrderPartsPreparation::class)->selection($input); $prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection); $financial = []; foreach ($prepared['sources'] as $source) { $distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first(); if ($distribution === null) { $financial[] = ['origin' => $source['requisition_id'], 'award_id' => $source['award_id'], 'requires_adoption' => true, 'allocations' => []]; continue; } $snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR); $selected = array_column($source['items'], null, 'requisition_item_id'); $rows = []; foreach ($snapshot['allocations'] as $row) { if (! isset($selected[$row['line_id']])) { continue; } $line = $selected[$row['line_id']]; $count = count(array_filter($snapshot['allocations'], fn ($part) => $part['line_id'] === $row['line_id'])); $rows[] = ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'], 'description' => $line['description'], 'subtotal' => $count === 1 && $source['currency'] === 'MZN' ? (string) BigDecimal::of($line['subtotal_minor'])->dividedBy(100, 2) : '', 'total' => $count === 1 && $source['currency'] === 'MZN' ? (string) BigDecimal::of($line['total_minor'])->dividedBy(100, 2) : '']; } $financial[] = ['origin' => $source['requisition_id'], 'award_id' => $source['award_id'], 'requires_adoption' => false, 'plan_hash' => $snapshot['plan_hash'], 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(), 'allocations' => $rows]; } return ['selection' => $selection, 'prepared' => $prepared, 'financial' => $financial, 'can_issue' => $prepared['currency'] === 'MZN' && ! in_array(true, array_column($financial, 'requires_adoption'), true)]; }); } public function adopt(User $actor, PurchaseAward $award, string $operation): void { abort_unless($this->ready(), 503); Validator::make(['operation_key' => $operation], ['operation_key' => 'required|uuid'])->validate(); DB::transaction(function () use ($actor, $award, $operation): void { app(ConflictGuard::class)->lockCompany($actor); $actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]); $quote = app(PurchaseWorkflow::class)->approvedSource($actor, $award); $request = Requisition::query()->whereKey($quote->requisition_id)->firstOrFail(); abort_unless($quote->currency === 'MZN', 503, 'A adopção multimoeda ainda está em preparação.'); $adopted = DB::table('budget_order_commands')->where('tenant_id', $actor->tenant_id)->where('kind', 'adopt') ->where('document_key', 'origin-'.$request->id)->where('operation_key', strtolower($operation))->exists(); abort_if(! $adopted && PurchaseOrderItem::query()->whereIn('requisition_item_id', $request->items()->select('id'))->exists(), 409, 'Uma ordem já emitida não pode ser dividida retroactivamente.'); $kind = $request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating'; $lines = $allocations = []; foreach ($quote->items()->orderBy('id')->get() as $line) { $lines[$line->requisition_item_id] = ['subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor, 'required_kind' => $kind]; $allocations[] = ['allocation_key' => 'legacy-line-'.$line->requisition_item_id, 'line_id' => $line->requisition_item_id, 'centre_id' => $request->cost_center_id, 'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor]; } $revision = hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR)); $adapter = app(CommonBudget::class); $engine = $adapter->for($actor); $adapter->execute(fn () => (new \ReflectionMethod($engine, 'adoptOrderSource'))->invoke($engine, $request->id, $allocations, $lines, $revision, strtolower($operation))); }); } public function ready(): bool { foreach (['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions', 'purchase_order_sources'] as $table) { if (! Schema::hasTable($table)) { return false; } } return app(OrderPartsPreparation::class)->ready() && app(RequisitionBudgetDistributions::class)->ready() && Schema::hasTable('budget_order_commands') && Schema::hasTable('purchase_order_sources') && Schema::hasColumn('purchase_orders', 'order_key') && Schema::hasColumn('purchase_orders', 'order_source_count') && Schema::hasColumn('purchase_order_items', 'quantity_offset_milli'); } /** @param array $input */ public function issue(User $actor, array $input): PurchaseOrder { abort_unless($this->ready(), 503, 'Emissão por parcelas indisponível nesta composição.'); $selection = app(OrderPartsPreparation::class)->selection($input); $data = Validator::make($input, [ 'operation_key' => 'required|uuid', 'order_key' => 'required|uuid', 'fingerprint' => 'required|regex:/^[a-f0-9]{64}$/D', 'budget_sources' => 'required|array|min:1|max:100', 'budget_sources.*' => 'required|array:origin,version,plan_hash,allocations', 'budget_sources.*.origin' => 'required|integer|min:1|distinct', 'budget_sources.*.version' => 'required|integer|min:0', 'budget_sources.*.plan_hash' => 'required|regex:/^[a-f0-9]{64}$/D', 'budget_sources.*.allocations' => 'required|array|min:1|max:500', 'budget_sources.*.allocations.*' => 'required|array:allocation_key,subtotal_minor,total_minor', 'budget_sources.*.allocations.*.allocation_key' => 'required|string|max:120', 'budget_sources.*.allocations.*.subtotal_minor' => 'required|integer|min:0|max:100000000000000', 'budget_sources.*.allocations.*.total_minor' => 'required|integer|min:0|max:100000000000000', 'agreement_bindings' => 'sometimes|array|max:100', 'tenant_id' => 'prohibited', 'snapshot' => 'prohibited', 'status' => 'prohibited', 'issued_by' => 'prohibited', ])->validate(); foreach ($selection['sources'] as &$source) { $source['award_id'] = BigDecimal::of($source['award_id'])->toInt(); foreach ($source['items'] as &$line) { $line['quotation_item_id'] = BigDecimal::of($line['quotation_item_id'])->toInt(); $line['quantity'] = (string) BigDecimal::of($line['quantity'])->toScale(3); } unset($line); usort($source['items'], fn ($a, $b) => $a['quotation_item_id'] <=> $b['quotation_item_id']); } unset($source); usort($selection['sources'], fn ($a, $b) => $a['award_id'] <=> $b['award_id']); $budgetSources = $data['budget_sources']; foreach ($budgetSources as &$source) { $source['origin'] = BigDecimal::of($source['origin'])->toInt(); $source['version'] = BigDecimal::of($source['version'])->toInt(); foreach ($source['allocations'] as &$row) { $row['subtotal_minor'] = BigDecimal::of($row['subtotal_minor'])->toInt(); $row['total_minor'] = BigDecimal::of($row['total_minor'])->toInt(); ksort($row); } unset($row); usort($source['allocations'], fn ($a, $b) => $a['allocation_key'] <=> $b['allocation_key']); ksort($source); } unset($source); usort($budgetSources, fn ($a, $b) => $a['origin'] <=> $b['origin']); $orderKey = strtolower($data['order_key']); $hash = hash('sha256', json_encode([$selection, $budgetSources, $data['fingerprint'], $data['agreement_bindings'] ?? []], JSON_THROW_ON_ERROR)); return DB::transaction(function () use ($actor, $selection, $data, $budgetSources, $orderKey, $hash): PurchaseOrder { app(ConflictGuard::class)->lockCompany($actor); $actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]); abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403); $existing = PurchaseOrder::query()->where('order_key', $orderKey)->lockForUpdate()->first(); if ($existing !== null) { abort_unless(hash_equals($existing->getAttribute('order_payload_hash'), $hash), 409, 'A ordem já foi emitida com outra preparação.'); PurchaseOrder::query()->visibleTo($actor)->whereKey($existing->id)->firstOrFail(); app(OrderPartsAccess::class)->assertProcess($actor, $existing, true); app(OrderCancellationWorkflow::class)->assertOperational($existing); return $existing; } $prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection); abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.'); // Foreign references require the full per-origin invoice conversion bridge, never an averaged rate. abort_unless($prepared['currency'] === 'MZN', 503, 'O percurso de emissão multimoeda por origem ainda está em preparação.'); $this->checkAllocations($actor, $prepared['sources'], $budgetSources); $frames = $requests = $lines = $catalogue = $tariffs = []; $firstQuote = null; foreach ($prepared['sources'] as $source) { $request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail(); $award = PurchaseAward::query()->whereKey($source['award_id'])->firstOrFail(); $quote = Quotation::query()->whereKey($source['quotation_id'])->firstOrFail(); $firstQuote ??= $quote; $requests[] = $request; $request->load(['department', 'costCenter', 'requester']); abort_unless($request->department !== null && $request->costCenter !== null && $quote->supplier !== null, 409, 'Preserve os intervenientes e as referências de cada origem.'); $requested = $request->items()->get()->keyBy('id'); $tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id')); foreach ($source['items'] as $item) { $native = $requested->get($item['requisition_item_id']); abort_unless($native !== null, 409); $lines[] = ['tenant_id' => $actor->tenant_id, ...array_intersect_key($item, array_flip(['quotation_item_id', 'requisition_item_id', 'description', 'quantity_offset_milli', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor'])), 'quantity' => (string) BigDecimal::of($item['quantity_milli'])->dividedBy(1000, 3), ...$native->only(['unit', 'category', 'purchase_type', 'equipment_id', 'spare_part_id'])]; if ($native->catalogue_snapshot !== null) { $catalogue[$native->id] = $native->catalogue_snapshot; } } $frames[] = ['requisition' => $request->only(['id', 'number', 'justification']), 'department' => $request->department->only(['id', 'name']), 'cost_center' => $request->costCenter->only(['id', 'code', 'name']), 'requester' => $request->requester?->only(['id', 'name']), 'quotation' => [...$source['quotation_terms'], 'id' => $quote->id, 'currency' => $quote->currency], 'award' => [...$source['award_terms'], 'id' => $award->id], 'approval_rules' => $award->approval_snapshot, 'investment_rules' => $award->investment_snapshot, 'admission' => $award->admission_snapshot, 'recommendation' => $award->recommendation_snapshot, 'estimate_approvals' => $request->steps()->get()->toArray(), 'final_approvals' => $award->approvals()->get()->toArray(), 'decision_matrix' => $award->decision_matrix, 'comparison_policy' => app(ComparisonPolicy::class)->forRequest($request), 'native_preparation' => $source]; } $first = $prepared['sources'][0]; $limits = app(AgreementOrderLimits::class)->freeze($actor, $firstQuote, $requests[0], $lines, $data['agreement_bindings'] ?? [], array_slice($requests, 1)); $adapter = app(CommonBudget::class); $engine = $adapter->for($actor); $commit = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'commitOrderParts'))->invoke($engine, $orderKey, $budgetSources, strtolower($data['operation_key']))); $snapshot = [...$frames[0], ...$limits, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']), 'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']), 'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue, 'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true, 'order_parts' => ['version' => 1, 'order_key' => $orderKey, 'preparation_fingerprint' => $prepared['fingerprint'], 'sources' => $prepared['sources'], 'frames' => $frames, 'budget_sources' => $budgetSources]]; $order = new PurchaseOrder(['tenant_id' => $actor->tenant_id, 'requisition_id' => $first['requisition_id'], 'purchase_award_id' => $first['award_id'], 'supplier_id' => $first['supplier_id'], 'issued_by' => $actor->id, 'currency' => $prepared['currency'], 'subtotal_minor' => $prepared['subtotal_minor'], 'tax_minor' => $prepared['tax_minor'], 'total_minor' => $prepared['total_minor'], 'snapshot' => $snapshot, 'issued_at' => now()]); // Trusted metadata must survive an ORM column cache warmed before the optional QA schema. $order->setAttribute('order_key', $orderKey); $order->setAttribute('order_payload_hash', $hash); $order->setAttribute('order_source_count', count($prepared['sources'])); $order->save(); DB::table('purchase_orders')->where('id', $order->id)->update(['number' => sprintf('OC-%s-%06d', now()->format('Y'), $order->id)]); $order->refresh(); foreach ($lines as $line) { $record = new PurchaseOrderItem(array_diff_key($line, array_flip(['quotation_item_id', 'quantity_offset_milli']))); $record->setAttribute('quotation_item_id', $line['quotation_item_id']); $record->setAttribute('quantity_offset_milli', $line['quantity_offset_milli']); $order->items()->save($record); } foreach ($prepared['sources'] as $index => $source) { DB::table('purchase_order_sources')->insert(['tenant_id' => $actor->tenant_id, 'purchase_order_id' => $order->id, 'requisition_id' => $source['requisition_id'], 'purchase_award_id' => $source['award_id'], 'quotation_id' => $source['quotation_id'], 'snapshot' => json_encode($frames[$index], JSON_THROW_ON_ERROR)]); app(RequisitionWorkflow::class)->audit($actor, 'purchase_order.issued', $requests[$index], null, ['order_id' => $order->id, 'number' => $order->number, 'order_key' => $orderKey, 'source' => $source, 'budget_control' => $commit]); } return $order; }); } /** @param list> $sources * @param list> $financial */ private function checkAllocations(User $actor, array $sources, array $financial): void { $expected = array_column($sources, 'requisition_id'); $actual = array_column($financial, 'origin'); sort($expected, SORT_NUMERIC); sort($actual, SORT_NUMERIC); if ($expected !== $actual) { throw ValidationException::withMessages(['budget_sources' => 'Distribua exactamente as origens seleccionadas.']); } $byOrigin = array_column($financial, null, 'origin'); foreach ($sources as $source) { $distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first(); abort_unless($distribution !== null, 422, 'Prepare a distribuição ou a adopção explícita da reserva antes de emitir parcelas.'); $snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR); $frozen = array_column($snapshot['allocations'], null, 'allocation_key'); $amounts = []; foreach ($byOrigin[$source['requisition_id']]['allocations'] as $row) { $binding = $frozen[$row['allocation_key']] ?? null; if ($binding === null) { throw ValidationException::withMessages(['budget_sources' => 'Atribuição fora da origem seleccionada.']); } $id = $binding['line_id']; $amounts[$id] ??= ['subtotal_minor' => 0, 'total_minor' => 0]; $amounts[$id]['subtotal_minor'] += $row['subtotal_minor']; $amounts[$id]['total_minor'] += $row['total_minor']; } $selected = array_column($source['items'], null, 'requisition_item_id'); if (array_diff(array_keys($amounts), array_keys($selected)) !== []) { throw ValidationException::withMessages(['budget_sources' => 'Não inclua artigos que não pertencem a esta parcela.']); } foreach ($selected as $id => $line) { if (($amounts[$id] ?? null) !== array_intersect_key($line, array_flip(['subtotal_minor', 'total_minor']))) { throw ValidationException::withMessages(['budget_sources' => 'As atribuições devem reconciliar exactamente com cada linha nativa emitida.']); } } } } }