db->getSchemaBuilder()->hasTable($this->prefix.$table) ? 1 : 0; } if ($found !== 0 && $found !== 4) { $this->fail('Estrutura de ordens parciais incompleta; saldo não presumido.', 'allocations', 503); } if ($found === 4 && ! $this->distributionReady()) { $this->fail('Ordens parciais exigem o diário de distribuição preservado.', 'allocations', 503); } return $found === 4; } private function orderPartsRequire(): void { $this->requireDistributionSchema(); if (! $this->orderPartsReady()) { $this->fail('Contrato de ordens parciais não instalado nesta composição.', 'allocations', 503); } } private function orderPartsKey(string $key): void { if (! preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/D', $key)) { $this->fail('Identificador estável da operação ou ordem obrigatório.', 'allocations'); } } /** Canonical ordering makes retries independent of the host's display order. */ private function orderPartsInput(array $sources, bool $consume): array { if ($sources === [] || count($sources) > 100) { $this->fail('Seleccione entre uma e cem origens explícitas.', 'allocations'); } $seen = []; foreach ($sources as &$source) { $fields = ['origin', 'version', 'plan_hash', 'allocations']; if (! is_array($source) || array_diff(array_keys($source), $fields) !== [] || array_diff($fields, array_keys($source)) !== [] || ! is_int($source['origin']) || $source['origin'] < 1 || isset($seen[$source['origin']]) || ! is_int($source['version']) || $source['version'] < 0 || ! is_string($source['plan_hash']) || ! preg_match('/^[a-f0-9]{64}$/D', $source['plan_hash']) || ! is_array($source['allocations']) || $source['allocations'] === [] || count($source['allocations']) > 500) { $this->fail('Origem, versão e distribuição explícitas obrigatórias, sem duplicados.', 'allocations'); } $seen[$source['origin']] = true; $keys = []; foreach ($source['allocations'] as &$row) { $fields = ['allocation_key', 'subtotal_minor', 'total_minor']; if ($consume) { $fields[] = 'order_key'; } if (! is_array($row) || array_diff(array_keys($row), $fields) !== [] || array_diff($fields, array_keys($row)) !== [] || ! is_string($row['allocation_key']) || $row['allocation_key'] === '' || strlen($row['allocation_key']) > 120 || ! is_int($row['subtotal_minor']) || ! is_int($row['total_minor']) || $row['subtotal_minor'] < 0 || $row['total_minor'] < 0 || $row['subtotal_minor'] > $row['total_minor'] || $row['total_minor'] > self::MAX_MINOR) { $this->fail('Atribuição e montantes nativos inteiros obrigatórios.', 'allocations'); } if ($consume) { if (! is_string($row['order_key'])) { $this->fail('Ordem de origem obrigatória.', 'allocations'); } $this->orderPartsKey($row['order_key']); } $key = ($consume ? $row['order_key'].':' : '').$row['allocation_key']; if (isset($keys[$key])) { $this->fail('Atribuição repetida na mesma origem e ordem.', 'allocations'); } $keys[$key] = true; ksort($row); } unset($row); usort($source['allocations'], fn ($a, $b) => [$a['order_key'] ?? '', $a['allocation_key']] <=> [$b['order_key'] ?? '', $b['allocation_key']]); ksort($source); } unset($source); usort($sources, fn ($a, $b) => $a['origin'] <=> $b['origin']); return array_values($sources); } private function orderPartsReplay(string $kind, string $document, string $operation, array $input): array { $this->orderPartsRequire(); if ($this->landedCostsReady() && $this->query('budget_landed_commands')->where('operation_key', $operation)->exists()) { $this->fail('A operação pertence ao custo de aterragem.', 'operation_key', 409); } $this->orderPartsKey($operation); $hash = hash('sha256', json_encode([$kind, $document, $input], JSON_THROW_ON_ERROR)); $old = $this->query('budget_order_commands')->where('operation_key', $operation)->first() ?? $this->query('budget_order_commands')->where('kind', $kind)->where('document_key', $document)->first(); if ($old) { if ($old->kind !== $kind || $old->document_key !== $document || ! hash_equals($old->payload_hash, $hash)) { $this->fail('Operação ou documento já registado com outras origens, versões ou montantes.', 'allocations', 409); } return ['hash' => $hash, 'result' => json_decode($old->result, true, 64, JSON_THROW_ON_ERROR) + ['replayed' => true]]; } if ($this->query('budget_distribution_events')->where('operation_key', $operation)->exists()) { $this->fail('Identificador já usado no contrato anterior.', 'allocations', 409); } return ['hash' => $hash, 'result' => null]; } /** All source and budget rows are locked before any effect is written. */ private function orderPartsBindings(array $sources, bool $consume, bool $cancel = false): array { $bindings = []; foreach ($sources as $input) { $source = $this->distributedOrigin($input['origin']); if (! $source || ! in_array($source->phase, ['award', 'orders'], true)) { $this->fail('Origem sem adjudicação distribuída compatível.', 'allocations', 409); } $snapshot = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR); $legacy = $this->query('budget_entries')->where('requisition_id', $input['origin']); if ((clone $legacy)->exists() && (! isset($snapshot['adopted_entry_ids']) || (int) (clone $legacy)->sum('reserved_minor') !== 0 || (int) (clone $legacy)->sum('committed_minor') !== 0 || (clone $legacy)->where('kind', 'order-adoption')->count() !== 1)) { $this->fail('Origem legada sem adopção explícita e reconciliada.', 'allocations', 409); } $version = $this->query('budget_order_bindings')->where('distribution_id', $source->id)->count(); if ($version !== $input['version'] || ! hash_equals($snapshot['plan_hash'], $input['plan_hash'])) { $this->fail('A origem mudou; actualize a preparação antes de confirmar.', 'allocations', 409); } $frozen = array_column($snapshot['allocations'], null, 'allocation_key'); foreach ($input['allocations'] as $row) { $allocation = $frozen[$row['allocation_key']] ?? null; if (! $allocation) { $this->fail('Atribuição fora da distribuição congelada.', 'allocations'); } $budget = $this->allocation($allocation['budget_id']); if (! $budget->approved_by || (! $cancel && (int) $budget->year !== $this->context->year) || (int) $budget->cost_center_id !== $allocation['centre_id'] || $budget->kind !== $allocation['required_kind'] || (bool) $budget->includes_tax !== $allocation['includes_tax']) { $this->fail('Dotação alterada, encerrada ou fora do âmbito.', 'allocations', 409); } $prior = $this->query('budget_order_allocations')->where('distribution_id', $source->id)->where('allocation_key', $row['allocation_key'])->where('kind', 'commit'); $limit = $allocation; if ($consume) { if ($this->query('budget_order_commands')->where('kind', 'cancel')->where('document_key', $row['order_key'])->exists()) { $this->fail('Ordem cancelada; consumo recusado.', 'invoice', 409); } $limit = (clone $prior)->where('order_key', $row['order_key'])->first(); if (! $limit) { $this->fail('Atribuição sem compromisso nesta ordem.', 'invoice', 409); } $limit = (array) $limit; $prior = $this->query('budget_order_consumptions')->where('distribution_id', $source->id)->where('allocation_key', $row['allocation_key'])->where('order_key', $row['order_key']); } foreach ($cancel ? [] : ['subtotal_minor', 'total_minor'] as $field) { if ($row[$field] > (int) $limit[$field] - (int) (clone $prior)->sum($field)) { $this->fail('Montante cumulativo ultrapassa a origem ou a parcela emitida.', 'allocations'); } } $amount = $allocation['includes_tax'] ? $row['total_minor'] : $row['subtotal_minor']; if (! $consume && ! $cancel) { $reserved = (int) $this->query('budget_distribution_entries')->where('distribution_id', $source->id)->where('allocation_key', $row['allocation_key'])->sum('reserved_minor'); if ($amount > $reserved) { $this->fail('Parcela sem reserva suficiente.', 'allocations'); } } $bindings[] = ['source' => $source, 'input' => $input, 'row' => $row, 'allocation' => $allocation, 'amount' => $amount]; } } return $bindings; } private function orderPartsEvent(string $kind, string $document, string $operation, string $hash, array $input, array $bindings): array { $versions = []; foreach ($bindings as $binding) { $versions[$binding['input']['origin']] = $binding['input']['version'] + 1; } $result = ['document_key' => $document, 'source_versions' => $versions]; $id = $this->query('budget_order_commands')->insertGetId($this->context->scope + [ 'kind' => $kind, 'document_key' => $document, 'operation_key' => $operation, 'payload_hash' => $hash, 'result' => json_encode($result, JSON_THROW_ON_ERROR), 'snapshot' => json_encode($input, JSON_THROW_ON_ERROR), 'created_by' => $this->context->actorId, 'created_at' => $this->stamp(), ]); $seen = []; foreach ($bindings as $binding) { $source = $binding['source']; if (! isset($seen[$source->id])) { $this->query('budget_order_bindings')->insert($this->context->scope + ['command_id' => $id, 'distribution_id' => $source->id, 'source_version' => $binding['input']['version'] + 1]); $this->query('budget_distributions')->where('id', $source->id)->update(['phase' => 'orders', 'updated_at' => $this->stamp()]); $seen[$source->id] = true; } } return [$id, $result]; } /** Explicit adoption of an unissued legacy award. Original entries remain immutable. */ public function adoptOrderSource(int $origin, array $allocations, array $lines, string $revision, string $operation): array { return $this->atomic('orders.adopt', function () use ($origin, $allocations, $lines, $revision, $operation): array { $plan = BudgetDistributionPlan::normalise($allocations, $lines); if ($origin < 1 || ! preg_match('/^[a-f0-9]{64}$/D', $revision)) { $this->fail('Origem e versão nativa obrigatórias.', 'allocations'); } ksort($lines); $input = ['origin' => $origin, 'allocations' => $plan, 'lines' => $lines, 'revision' => $revision]; $replay = $this->orderPartsReplay('adopt', 'origin-'.$origin, $operation, $input); if ($replay['result']) { return $replay['result']; } if ($this->distributedOrigin($origin)) { $this->fail('Origem já distribuída; não repetir adopção.', 'allocations', 409); } $entries = $this->query('budget_entries')->where('requisition_id', $origin)->orderBy('id')->lockForUpdate()->get(); if ($entries->isEmpty() || ! $entries->contains('kind', 'award') || $entries->contains(fn ($entry) => ! in_array($entry->kind, ['reserve', 'award'], true)) || $entries->pluck('budget_id')->unique()->count() !== 1 || (int) $entries->sum('committed_minor') !== 0) { $this->fail('Só é adoptável uma reserva adjudicada, ainda sem ordem ou consumo.', 'allocations', 409); } $budget = $this->allocation((int) $entries->first()->budget_id); if (! $budget->approved_by || (int) $budget->year !== $this->context->year) { $this->fail('Dotação de origem indisponível para emissão.', 'allocations', 409); } $frozen = []; foreach ($plan as $allocation) { if ($allocation['centre_id'] !== (int) $budget->cost_center_id || $allocation['required_kind'] !== $budget->kind) { $this->fail('Adopção conserva o centro e a classificação da reserva original.', 'allocations'); } $frozen[] = $allocation + ['budget_id' => (int) $budget->id, 'includes_tax' => (bool) $budget->includes_tax]; } $reserved = (int) $entries->sum('reserved_minor'); $amount = array_sum(array_column($plan, $budget->includes_tax ? 'total_minor' : 'subtotal_minor')); if ($reserved !== $amount || $reserved < 1) { $this->fail('A base nativa deve reconciliar exactamente com a reserva adjudicada.', 'allocations'); } $snapshot = ['allocations' => $frozen, 'lines' => $lines, 'revision' => $revision, 'plan_hash' => BudgetDistributionPlan::fingerprint($plan, $revision), 'adopted_entry_ids' => $entries->pluck('id')->all()]; $id = $this->query('budget_distributions')->insertGetId($this->context->scope + ['requisition_id' => $origin, 'phase' => 'orders', 'snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR), 'created_by' => $this->context->actorId, 'created_at' => $this->stamp(), 'updated_at' => $this->stamp()]); $this->query('budget_entries')->insert($this->context->scope + ['budget_id' => $budget->id, 'requisition_id' => $origin, 'kind' => 'order-adoption', 'reserved_minor' => -$reserved, 'committed_minor' => 0, 'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]); foreach ($frozen as $allocation) { $this->query('budget_distribution_entries')->insert($this->context->scope + ['distribution_id' => $id, 'allocation_key' => $allocation['allocation_key'], 'budget_id' => $budget->id, 'kind' => 'order-adoption', 'reserved_minor' => $allocation[$budget->includes_tax ? 'total_minor' : 'subtotal_minor'], 'committed_minor' => 0, 'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]); } $result = ['distribution_id' => $id, 'plan_hash' => $snapshot['plan_hash'], 'source_versions' => [$origin => 0]]; $this->query('budget_order_commands')->insert($this->context->scope + ['kind' => 'adopt', 'document_key' => 'origin-'.$origin, 'operation_key' => $operation, 'payload_hash' => $replay['hash'], 'result' => json_encode($result, JSON_THROW_ON_ERROR), 'snapshot' => json_encode($input + ['original_entry_ids' => $snapshot['adopted_entry_ids']], JSON_THROW_ON_ERROR), 'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]); $this->emit('budget.order_source_adopted', $result, $origin); return $result + ['replayed' => false]; }); } /** Host supplies approved native amounts and checks supplier, quantities and document access. */ public function commitOrderParts(string $order, array $sources, string $operation): array { return $this->atomic('orders.commit', function () use ($order, $sources, $operation): array { $this->orderPartsKey($order); $input = $this->orderPartsInput($sources, false); $replay = $this->orderPartsReplay('commit', $order, $operation, $input); if ($replay['result']) { return $replay['result']; } $bindings = $this->orderPartsBindings($input, false); [$event, $result] = $this->orderPartsEvent('commit', $order, $operation, $replay['hash'], $input, $bindings); foreach ($bindings as $binding) { ['source' => $source, 'row' => $row, 'allocation' => $allocation, 'amount' => $amount] = $binding; $this->query('budget_order_allocations')->insert($this->context->scope + ['command_id' => $event, 'distribution_id' => $source->id, 'order_key' => $order, 'allocation_key' => $row['allocation_key'], 'budget_id' => $allocation['budget_id'], 'kind' => 'commit', 'subtotal_minor' => $row['subtotal_minor'], 'total_minor' => $row['total_minor'], 'amount_minor' => $amount]); $this->query('budget_distribution_entries')->insert($this->context->scope + ['distribution_id' => $source->id, 'allocation_key' => $row['allocation_key'], 'budget_id' => $allocation['budget_id'], 'kind' => 'order-'.$event, 'reserved_minor' => -$amount, 'committed_minor' => $amount, 'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]); } $this->emit('budget.orders_committed', $result); return $result + ['replayed' => false]; }); } public function checkOrderPartsConsumption(array $sources): void { $this->atomic('consume.preview', function () use ($sources): void { $this->orderPartsRequire(); $this->orderPartsBindings($this->orderPartsInput($sources, true), true); }); } /** Full cancellation of one unconsumed order; other orders and unissued reservations remain intact. */ public function cancelOrderParts(string $order, array $sources, string $operation): array { return $this->atomic('orders.cancel', function () use ($order, $sources, $operation): array { $this->orderPartsKey($order); $input = $this->orderPartsInput($sources, false); $replay = $this->orderPartsReplay('cancel', $order, $operation, $input); if ($replay['result']) { return $replay['result']; } $commit = $this->query('budget_order_commands')->where('kind', 'commit')->where('document_key', $order)->first(); if (! $commit || $this->query('budget_order_consumptions')->where('order_key', $order)->exists()) { $this->fail('Ordem inexistente ou com consumo; cancelamento integral recusado.', 'allocations', 409); } $original = json_decode($commit->snapshot, true, 64, JSON_THROW_ON_ERROR); $versions = array_column($input, 'version', 'origin'); foreach ($original as &$source) { $source['version'] = $versions[$source['origin']] ?? -1; } unset($source); if ($original !== $input) { $this->fail('O cancelamento deve conservar todas as parcelas da ordem emitida.', 'allocations', 409); } $bindings = $this->orderPartsBindings($input, false, true); [$event, $result] = $this->orderPartsEvent('cancel', $order, $operation, $replay['hash'], $input, $bindings); foreach ($bindings as $binding) { ['source' => $source, 'row' => $row, 'allocation' => $allocation, 'amount' => $amount] = $binding; $this->query('budget_order_allocations')->insert($this->context->scope + ['command_id' => $event, 'distribution_id' => $source->id, 'order_key' => $order, 'allocation_key' => $row['allocation_key'], 'budget_id' => $allocation['budget_id'], 'kind' => 'cancel', 'subtotal_minor' => $row['subtotal_minor'], 'total_minor' => $row['total_minor'], 'amount_minor' => $amount]); $this->query('budget_distribution_entries')->insert($this->context->scope + ['distribution_id' => $source->id, 'allocation_key' => $row['allocation_key'], 'budget_id' => $allocation['budget_id'], 'kind' => 'order-cancel-'.$event, 'reserved_minor' => 0, 'committed_minor' => -$amount, 'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]); } $this->emit('budget.orders_cancelled', $result); return $result + ['replayed' => false]; }); } /** One native invoice, one atomic command, potentially several approved order origins. */ public function consumeOrderParts(int $invoice, array $sources, string $operation): array { return $this->atomic('consume', function () use ($invoice, $sources, $operation): array { if ($invoice < 1) { $this->fail('Factura nativa obrigatória.', 'invoice'); } $input = $this->orderPartsInput($sources, true); $replay = $this->orderPartsReplay('consume', 'invoice-'.$invoice, $operation, $input); if ($replay['result']) { return $replay['result']; } if ($this->query('budget_consumptions')->where('invoice_id', $invoice)->exists() || $this->query('budget_distribution_consumptions')->where('invoice_id', $invoice)->exists() || $this->query('budget_order_consumptions')->where('invoice_id', $invoice)->exists()) { $this->fail('Factura já consumida; não duplicar a obrigação.', 'invoice', 409); } $bindings = $this->orderPartsBindings($input, true); [$event, $result] = $this->orderPartsEvent('consume', 'invoice-'.$invoice, $operation, $replay['hash'], $input, $bindings); $effects = []; foreach ($bindings as $binding) { ['source' => $source, 'row' => $row, 'allocation' => $allocation, 'amount' => $amount] = $binding; $this->query('budget_order_consumptions')->insert($this->context->scope + ['command_id' => $event, 'distribution_id' => $source->id, 'order_key' => $row['order_key'], 'allocation_key' => $row['allocation_key'], 'budget_id' => $allocation['budget_id'], 'invoice_id' => $invoice, 'subtotal_minor' => $row['subtotal_minor'], 'total_minor' => $row['total_minor'], 'amount_minor' => $amount]); $key = $source->id.':'.$row['allocation_key']; $effects[$key] ??= $this->context->scope + ['distribution_id' => $source->id, 'allocation_key' => $row['allocation_key'], 'budget_id' => $allocation['budget_id'], 'kind' => 'order-invoice-'.$event, 'reserved_minor' => 0, 'committed_minor' => 0, 'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]; $effects[$key]['committed_minor'] -= $amount; } foreach ($effects as $effect) { $this->query('budget_distribution_entries')->insert($effect); } $this->emit('budget.consumed', $result); return $result + ['replayed' => false]; }); } }