commit SGF2311

This commit is contained in:
2026-11-23 11:48:07 +02:00
parent cd9897df05
commit 82e447a6ab
18 changed files with 1952 additions and 338 deletions
+38
View File
@@ -9,3 +9,41 @@ Compras uses its existing tables and scope `tenant_id` (company); SGF QA uses se
Load `bootstrap.php` after the host's existing vendor autoloader. For local Compras development the provider locates this source tree. A standalone deployment installs the same versioned package artifact under `packages/budget-control`, or sets `COMMON_BUDGET_PATH` to its installed artifact; the local sibling fallback is disabled in production. No second maintained source copy is created. QA records the loaded source hash in both booted Laravel hosts.
Existing tables/constraints remain valid in Compras; no live migration is run. SGF schema/rights are QA-only in this increment. SGF operational activation, full procurement UI installation and customer data migration remain pending. See the delivery report for evidence and limitations.
## Optional distribution contract — authorised isolated QA, 22 November 2026
`DISTRIBUTIONS_VERSION = COMMON-BUDGET-DISTRIBUTION-QA-v1` identifies the unpublished optional extension. The owner authorised this canonical source and the SGC host adaptation for isolated development/QA only. Published/pinned artifacts and operational hosts remain unchanged. The SGC decisions and evidence are `docs/proofs/rq01-distribution-contract-authorization.json`, `rq01-distribution-fx-decision.json` and `rq01-distribution-qa.json` in the Compras repository.
Four optional scoped tables hold the current distribution, immutable event snapshots, commitment/reservation effects and invoice consumptions. No schema is installed by bootstrap. A partial schema fails closed; an absent schema preserves the existing single-centre behaviour. An origin cannot mix the old and distributed writers. Host adapters must validate the native source, actor, department and explicit MZN reference values before invoking commands.
`recordDistribution` atomically reserves, adjusts to award, commits or releases an explicit exact plan. `consumeDistribution` uses explicit native partial-invoice values and the remaining frozen allocations. Both contribute to the existing common balance. No prices, tax or exchange conversions are recalculated here.
`checkDistributionConsumption` reuses the same authoritative consumption validator before an immutable invoice is inserted. Its host callback action is **`consume.preview`**, requiring current Finance authority. It locks and validates the committed identities, classification, tax basis, remaining net/gross capacities and commitment, without financial effects or audit events. Actual validation repeats those checks before consumption. This prevents an invalid allocation from being frozen into an uncorrectable pending document; it does not reserve quantities for pending invoices or weaken independent validation.
`amendDistribution` requires the previous plan hash, explicit replacement values, reason and operation UUID. The host callback receives **`distribution.amend`** and must require the current Finance authority; treating it as an unrestricted generic record action is invalid. Optional explicit reference-line imputations must preserve the native document's article identities, classifications and net/gross header totals. Every amendment preserves consumed floors and available funds, appends its full prior-linked version and audit, and leaves source documents and exchange rates untouched. Replays are harmless; stale/conflicting changes fail. No balancing residual is assigned automatically.
Recovery must preserve a compatible runtime when distribution data exists. The unchanged old artifact cannot be used to infer balances for a company with these optional effects. Installation/activation and any schema transition beyond disposable QA require their own concrete proposal and authorisation.
## Optional order-part contract source in development
`ORDER_PARTS_VERSION = COMMON-BUDGET-ORDER-PARTS-QA-v1` is a separately negotiated capability. The owner's specific authorization is recorded in Compras at `docs/proofs/rq01-multi-order-contract-authorization.json`. The existing `VERSION` and `DISTRIBUTIONS_VERSION` remain unchanged. This canonical source now also requires `src/BudgetOrderParts.php`; the installed seven-file V1 release is preserved independently and must not be regenerated or overwritten from this tree.
Four additional optional tables hold append-only commands, source versions, issued allocations and invoice consumptions. Bootstrap installs nothing. Partial structures fail closed. `commitOrderParts` transfers only explicit issued portions from the existing reservation journal into commitments, atomically across all origins. `consumeOrderParts` consumes one native invoice across selected order origins; `checkOrderPartsConsumption` validates before an immutable invoice is inserted. Source versions and native plan hashes are mandatory. Retries preserve one effect and one audit. Explicit zero-cent native rounding remainders preserve lineage without inventing a cent; an unknown value is never replaced by zero.
`cancelOrderParts` releases only a complete unconsumed issued order, without restoring issuance capacity or touching other reservations/orders. The host must additionally enforce its existing receipt/invoice/cancellation policy. `adoptOrderSource` accepts only an explicitly reconciled, awarded legacy reservation with no commitment, retains all original rows, and appends an exact transfer into the distributed journal. The before/after budget balance is identical. It does not authorize an already issued native order to be split retrospectively.
Host adapters must require current Procurement authority for `orders.commit` and `orders.adopt`, and Finance for `orders.cancel`, `consume` and `consume.preview`. They must validate every native source's approval, visibility, supplier, currency, quantity, conflict controls and reference allocation before calling these financial commands. The common layer does not infer quantities, prices, tax rates or exchange rates. Any composition containing order-part data must refuse balance access through a runtime without this capability; silently reverting to V1 omits the new consumption history.
The native SGC MZN issuance, consolidated source visibility, receipt, independent invoice validation and cancellation adapters are implemented in isolated QA. Full foreign-currency issuance, multi-origin Finance amendments and the remaining mobile/print journey acceptance are still in progress. No operational installation, permission grant, bank execution or JUE submission is included. See the existing SGC delivery matrix and `rq01-multi-order-native-qa.json` for verification coverage; the earlier `rq01-multi-order-qa.json` remains historical contract/preparation evidence.
## Optional landed-cost reconciliation — authorised isolated QA, 22 November 2026
The owner separately authorised the common-source and SGC landed-cost extension in `import-landed-cost-contract-authorization.json`. `BudgetLandedCostPlan::reconcile` now reconciles explicit goods, freight, insurance and customs components to each native documentary origin and creditor. The same invoice cannot acquire a second identity by changing its role. Native and frozen MZN amounts must reconcile exactly, including known zero values; missing values and aggregate overflow fail. Canonical ordering preserves the preparation fingerprint. The existing explicit subtotal/total budget basis is retained.
`BudgetLandedCosts` is the optional financial writer capability `COMMON-BUDGET-LANDED-COST-QA-v2`. The two append-only QA tables preserve immutable command and source snapshots. Reserve, commit, consume, amend and cancel use the existing company lock, budget availability and audit transaction. Validated native invoices remain excluded from additional effects: their original principals and budget consumptions retain their existing authority. Customs sources never become fictional supplier invoices.
Transitions can select explicit documentary sources and require the host's current financial revision. An empty selection means every eligible source. Mixed states retain consumed sources while later reviewed costs reserve only the increment. Amendments preserve the consumed floor, stable source identity, prior values and available-funds checks; this does not implement a consumed-cost refund or credit. Cancellation releases only unconsumed positions. Operation replays cannot create another effect, including across the other optional command contracts.
SGC supplies private evidence, immutable corrective versions, frozen Finance rates, recoverable preparations and independent review. Logistics-only version changes preserve the financial review. Optional cost-to-item references retain native item descriptions and quantities in the reviewed host snapshot; they neither allocate money nor change stock valuation. Real PostgreSQL concurrency, old-runtime refusal and same-role pre/post-extension recovery were verified, including replay of a mixed consumed/reserved position. See `import-landed-cost-qa.json` for exact evidence and remaining functional coverage.
Bootstrap installs nothing. The host must refuse incomplete structures and an older runtime when landed-cost effects exist. The previous whole-source QA capability v1 and installed/published V1 artifacts cannot interpret v2 positions. Published/pinned artifacts, operational installation/activation, stock valuation, legal-rate activation and JUE/bank execution remain excluded. Remaining estimates, import requirements, native visual/mobile/print review and operational preparation are tracked in the existing SGC matrix.
+5
View File
@@ -3,4 +3,9 @@
// One source tree, loaded by each composition; no Composer or Brick Math replacement.
require_once __DIR__.'/src/BudgetContext.php';
require_once __DIR__.'/src/BudgetFailure.php';
require_once __DIR__.'/src/BudgetDistributions.php';
require_once __DIR__.'/src/BudgetOrderParts.php';
require_once __DIR__.'/src/BudgetLandedCosts.php';
require_once __DIR__.'/src/BudgetControl.php';
require_once __DIR__.'/src/BudgetDistributionPlan.php';
require_once __DIR__.'/src/BudgetLandedCostPlan.php';
@@ -12,7 +12,13 @@ use Illuminate\Database\Query\Builder;
*/
final class BudgetControl
{
use BudgetDistributions;
use BudgetOrderParts;
use BudgetLandedCosts;
public const VERSION = 'COMMON-BUDGET-SYNTHETIC-v1';
public const DISTRIBUTIONS_VERSION = 'COMMON-BUDGET-DISTRIBUTION-QA-v1';
public const ORDER_PARTS_VERSION = 'COMMON-BUDGET-ORDER-PARTS-QA-v1';
public const LANDED_COSTS_VERSION = 'COMMON-BUDGET-LANDED-COST-QA-v2';
public const MAX_MINOR = 100000000000000;
@@ -122,6 +128,9 @@ final class BudgetControl
public function record(int $origin, int $centre, string $requiredKind, string $kind, int $amount = 0, ?int $subtotal = null): ?array
{
return $this->atomic('record', function () use ($origin, $centre, $requiredKind, $kind, $amount, $subtotal) {
if ($this->distributedOrigin($origin)) {
$this->fail('Origem distribuída exige o contrato próprio, sem segundo efeito.', 'allocations', 409);
}
if (! in_array($kind, ['reserve', 'award', 'commit', 'release'], true) || $amount < 0) {
$this->fail('Movimento orçamental inválido.');
}
@@ -178,6 +187,12 @@ final class BudgetControl
public function consume(int $origin, int $invoice, int $total, int $subtotal): array
{
return $this->atomic('consume', function () use ($origin, $invoice, $total, $subtotal) {
if ($this->orderPartsReady() && $this->query('budget_order_consumptions')->where('invoice_id', $invoice)->exists()) {
$this->fail('Factura já consumida pelo contrato de ordens parciais.', 'invoice', 409);
}
if ($this->distributedOrigin($origin)) {
$this->fail('Origem distribuída exige consumo pelas atribuições congeladas.', 'invoice', 409);
}
$own = $this->query('budget_entries')->where('requisition_id', $origin);
$commit = (clone $own)->where('kind', 'commit')->first();
if (! $commit) {
@@ -279,6 +294,21 @@ final class BudgetControl
$reserved = (int) (clone $entries)->sum('reserved_minor');
$committed = (int) (clone $entries)->sum('committed_minor');
$consumed = (int) $this->query('budget_consumptions')->where('budget_id', $budget->id)->sum('amount_minor');
if ($this->distributionReady()) {
$distributed = $this->query('budget_distribution_entries')->where('budget_id', $budget->id);
$reserved += (int) (clone $distributed)->sum('reserved_minor');
$committed += (int) (clone $distributed)->sum('committed_minor');
$consumed += (int) $this->query('budget_distribution_consumptions')->where('budget_id', $budget->id)->sum('amount_minor');
}
if ($this->orderPartsReady()) {
$consumed += (int) $this->query('budget_order_consumptions')->where('budget_id', $budget->id)->sum('amount_minor');
}
if ($this->landedCostsReady()) {
$landed = $this->query('budget_landed_entries')->where('budget_id', $budget->id);
$reserved += (int) (clone $landed)->sum('reserved_minor');
$committed += (int) (clone $landed)->sum('committed_minor');
$consumed += (int) (clone $landed)->sum('consumed_minor');
}
$total = $this->total($budget);
return ['approved_total_minor' => $budget->approved_by ? $total : 0, 'reinforced_minor' => $total - (int) $budget->amount_minor, 'reserved_minor' => $reserved, 'committed_minor' => $committed, 'consumed_minor' => $consumed, 'available_minor' => $budget->approved_by ? $total - $reserved - $committed - $consumed : 0];
@@ -0,0 +1,73 @@
<?php
namespace Tempo\Finance\Budget;
/** Exact documentary allocation contract; never computes prices, taxes or exchange rates. */
final class BudgetDistributionPlan
{
/**
* @param list<array<string,mixed>> $allocations Explicit minor units, never percentages.
* @param array<int,array{subtotal_minor:int,total_minor:int,required_kind:string}> $lines Native host line totals.
* @return list<array{allocation_key:string,line_id:int,centre_id:int,subtotal_minor:int,total_minor:int,required_kind:string}>
*/
public static function normalise(array $allocations, array $lines): array
{
if (! array_is_list($allocations) || $allocations === [] || count($allocations) > 500 || $lines === [] || count($lines) > 100) {
throw new BudgetFailure('Distribuição exige linhas nativas e entre uma e 500 atribuições explícitas.', 'allocations', 422);
}
$sums = [];
foreach ($lines as $id => $line) {
if (! is_int($id) || $id < 1 || ! is_array($line) || ! in_array($line['required_kind'] ?? null, ['operating', 'investment'], true)
|| ! self::amount($line['subtotal_minor'] ?? null) || ! self::amount($line['total_minor'] ?? null)
|| $line['total_minor'] < $line['subtotal_minor']) {
throw new BudgetFailure('Base nativa da linha incompleta ou incompatível.', 'allocations', 422);
}
$sums[$id] = ['subtotal_minor' => 0, 'total_minor' => 0];
}
$keys = $result = [];
foreach ($allocations as $allocation) {
if (! is_array($allocation) || array_diff(array_keys($allocation), ['allocation_key', 'line_id', 'centre_id', 'subtotal_minor', 'total_minor']) !== []
|| ! is_string($allocation['allocation_key'] ?? null) || ! preg_match('/^[A-Za-z0-9:_-]{1,120}$/D', $allocation['allocation_key'])
|| isset($keys[$allocation['allocation_key']]) || ! is_int($allocation['line_id'] ?? null) || ! isset($lines[$allocation['line_id']])
|| ! is_int($allocation['centre_id'] ?? null) || $allocation['centre_id'] < 1
|| ! self::amount($allocation['subtotal_minor'] ?? null) || ! self::amount($allocation['total_minor'] ?? null)
|| $allocation['total_minor'] < $allocation['subtotal_minor']) {
throw new BudgetFailure('Atribuição inválida, repetida ou fora das linhas nativas.', 'allocations', 422);
}
$id = $allocation['line_id'];
foreach (['subtotal_minor', 'total_minor'] as $field) {
// Compare before addition: no overflow or compensating value is permitted.
if ($allocation[$field] > $lines[$id][$field] - $sums[$id][$field]) {
throw new BudgetFailure('A distribuição ultrapassa o valor nativo da linha.', 'allocations', 422);
}
$sums[$id][$field] += $allocation[$field];
}
$keys[$allocation['allocation_key']] = true;
$result[] = ['allocation_key' => $allocation['allocation_key'], 'line_id' => $id, 'centre_id' => $allocation['centre_id'],
'subtotal_minor' => $allocation['subtotal_minor'], 'total_minor' => $allocation['total_minor'], 'required_kind' => $lines[$id]['required_kind']];
}
foreach ($sums as $id => $sum) {
if ($sum['subtotal_minor'] !== $lines[$id]['subtotal_minor'] || $sum['total_minor'] !== $lines[$id]['total_minor']) {
throw new BudgetFailure('A soma das atribuições deve coincidir exactamente com cada linha nativa, sem compensações.', 'allocations', 422);
}
}
usort($result, fn (array $a, array $b): int => strcmp($a['allocation_key'], $b['allocation_key']));
return $result;
}
private static function amount(mixed $value): bool
{
return is_int($value) && $value >= 0 && $value <= BudgetControl::MAX_MINOR;
}
/** @param list<array<string,mixed>> $plan */
public static function fingerprint(array $plan, string $sourceRevision): string
{
if (! preg_match('/^[a-f0-9]{64}$/D', $sourceRevision)) {
throw new BudgetFailure('Revisão da origem obrigatória para congelar a distribuição.', 'allocations', 422);
}
return hash('sha256', json_encode(['revision' => $sourceRevision, 'allocations' => $plan], JSON_THROW_ON_ERROR));
}
}
@@ -0,0 +1,369 @@
<?php
namespace Tempo\Finance\Budget;
/** Optional multi-centre commands within the existing common budget authority. */
trait BudgetDistributions
{
private ?bool $distributionSchemaAvailable = null;
private function distributionReady(): bool
{
if ($this->distributionSchemaAvailable !== null) {
return $this->distributionSchemaAvailable;
}
$found = 0;
foreach (['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) {
$found += $this->db->getSchemaBuilder()->hasTable($this->prefix.$table) ? 1 : 0;
}
if ($found !== 0 && $found !== 4) {
$this->fail('Estrutura de distribuição incompleta; saldo não presumido.', 'allocations', 503);
}
return $this->distributionSchemaAvailable = $found === 4;
}
private function distributedOrigin(int $origin): ?object
{
return $this->distributionReady() ? $this->query('budget_distributions')->where('requisition_id', $origin)->lockForUpdate()->first() : null;
}
private function requireDistributionSchema(): void
{
if (! $this->distributionReady()) {
$this->fail('Contrato de distribuição não instalado nesta composição.', 'allocations', 503);
}
}
private function distributionReplay(int $source, string $kind, string $operation, string $hash): ?array
{
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);
}
$old = $this->query('budget_distribution_events')->where('operation_key', $operation)->first()
?? $this->query('budget_distribution_events')->where('distribution_id', $source)->where('kind', $kind)->first();
if (! $old) {
return null;
}
if ((int) $old->distribution_id !== $source || $old->kind !== $kind || $old->payload_hash !== $hash) {
$this->fail('Operação já registada com outra origem, versão ou distribuição.', 'allocations', 409);
}
return json_decode($old->result, true, 64, JSON_THROW_ON_ERROR) + ['replayed' => true];
}
private function distributionEvent(int $source, string $kind, string $operation, string $hash, array $result, array $snapshot): int
{
return $this->query('budget_distribution_events')->insertGetId($this->context->scope + ['distribution_id' => $source, 'kind' => $kind,
'operation_key' => $operation, 'payload_hash' => $hash, 'result' => json_encode($result, JSON_THROW_ON_ERROR), 'snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR),
'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]);
}
private function distributionOperation(int $origin, string $operation): void
{
$this->requireDistributionSchema();
if ($this->orderPartsReady() && $this->query('budget_order_commands')->where('operation_key', $operation)->exists()) {
$this->fail('Identificador já usado numa ordem parcial.', 'allocations', 409);
}
if ($origin < 1 || ! preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/Di', $operation)) {
$this->fail('Origem e identificador da operação obrigatórios.', 'allocations');
}
if ($this->query('budget_entries')->where('requisition_id', $origin)->exists()) {
$this->fail('Origem já usa o contrato de centro único; não duplicar efeitos.', 'allocations', 409);
}
$existing = $this->query('budget_distribution_events')->where('operation_key', $operation)->first();
if ($existing && ! $this->query('budget_distributions')->where('id', $existing->distribution_id)->where('requisition_id', $origin)->exists()) {
$this->fail('Identificador da operação já usado noutra origem.', 'allocations', 409);
}
}
private static function distributionIdentities(array $allocations): array
{
$result = [];
foreach ($allocations as $allocation) {
$result[$allocation['allocation_key']] = [$allocation['line_id'], $allocation['centre_id'], $allocation['required_kind']];
}
ksort($result);
return $result;
}
/** Native host totals are authoritative. All allocations are explicit exact minor units. */
public function recordDistribution(int $origin, string $kind, array $allocations, array $lines, string $revision, string $operation): array
{
return $this->atomic('record', function () use ($origin, $kind, $allocations, $lines, $revision, $operation): array {
$this->distributionOperation($origin, $operation);
if (! in_array($kind, ['reserve', 'award', 'commit', 'release', 'cancel'], true)) {
$this->fail('Etapa de distribuição inválida.', 'allocations');
}
$plan = BudgetDistributionPlan::normalise($allocations, $lines);
$hash = hash('sha256', $kind.':'.BudgetDistributionPlan::fingerprint($plan, $revision));
$source = $this->distributedOrigin($origin);
if ($source && ($replay = $this->distributionReplay((int) $source->id, $kind, $operation, $hash))) {
return $replay;
}
$previous = $source ? json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR) : null;
$allowed = match ($kind) {
'reserve' => $source === null,
'award', 'commit', 'release' => $source && in_array($source->phase, ['reserve', 'award'], true),
'cancel' => $source && $source->phase === 'commit',
};
if (! $allowed || ($previous && self::distributionIdentities($previous['allocations']) !== self::distributionIdentities($plan))) {
$this->fail('Distribuição sem reserva compatível ou já encerrada.', 'allocations', 409);
}
if (in_array($kind, ['release', 'cancel'], true) && ($revision !== $previous['revision'] || $plan !== BudgetDistributionPlan::normalise(array_map(fn ($row) => array_intersect_key($row, array_flip(['allocation_key', 'line_id', 'centre_id', 'subtotal_minor', 'total_minor'])), $previous['allocations']), $previous['lines']))) {
$this->fail('Libertação deve conservar a distribuição congelada.', 'allocations', 409);
}
if ($kind === 'cancel' && $this->query('budget_distribution_consumptions')->where('distribution_id', $source->id)->exists()) {
$this->fail('Distribuição com consumo documental; não libertar compromisso por arrasto.', 'allocations', 409);
}
$centres = array_values(array_unique(array_column($plan, 'centre_id')));
sort($centres, SORT_NUMERIC);
$budgets = [];
foreach ($centres as $centre) {
$oldAllocation = $previous ? collect($previous['allocations'])->firstWhere('centre_id', $centre) : null;
$budget = $oldAllocation ? $this->allocation($oldAllocation['budget_id'])
: $this->query('budgets')->where('cost_center_id', $centre)->where('year', $this->context->year)->lockForUpdate()->first();
if (! $budget || (int) $budget->cost_center_id !== $centre || ! $budget->approved_by
|| (! in_array($kind, ['release', 'cancel'], true) && (int) $budget->year !== $this->context->year)
|| ($oldAllocation && (bool) $budget->includes_tax !== $oldAllocation['includes_tax'])) {
$this->fail('Cada atribuição exige dotação aprovada, compatível e no âmbito autorizado.', 'allocations');
}
$budgets[$centre] = $budget;
}
if (! $source) {
$id = $this->query('budget_distributions')->insertGetId($this->context->scope + ['requisition_id' => $origin, 'phase' => 'preparing',
'snapshot' => '{}', 'created_by' => $this->context->actorId, 'created_at' => $this->stamp(), 'updated_at' => $this->stamp()]);
$source = $this->query('budget_distributions')->where('id', $id)->lockForUpdate()->first();
}
$frozen = $effects = $changes = [];
foreach ($plan as $allocation) {
$budget = $budgets[$allocation['centre_id']];
if ($budget->kind !== $allocation['required_kind']) {
$this->fail('Classificação da dotação incompatível com a base nativa.', 'allocations');
}
$own = $this->query('budget_distribution_entries')->where('distribution_id', $source->id)->where('allocation_key', $allocation['allocation_key']);
$reserved = (int) (clone $own)->sum('reserved_minor');
$committed = (int) (clone $own)->sum('committed_minor');
$amount = $budget->includes_tax ? $allocation['total_minor'] : $allocation['subtotal_minor'];
[$rd, $cd] = match ($kind) {
'reserve', 'award' => [$amount - $reserved, 0],
'commit' => [-$reserved, $amount],
'release' => [-$reserved, 0],
'cancel' => [-$reserved, -$committed],
};
$changes[$allocation['centre_id']] = ($changes[$allocation['centre_id']] ?? 0) + $rd + $cd;
$effects[] = $this->context->scope + ['distribution_id' => $source->id,
'allocation_key' => $allocation['allocation_key'], 'budget_id' => $budget->id, 'kind' => $kind,
'reserved_minor' => $rd, 'committed_minor' => $cd, 'created_by' => $this->context->actorId, 'created_at' => $this->stamp()];
$frozen[] = $allocation + ['budget_id' => (int) $budget->id, 'includes_tax' => (bool) $budget->includes_tax];
}
foreach ($changes as $centre => $change) {
if ($this->balanceOf($budgets[$centre])['available_minor'] < $change) {
$this->fail('Saldo insuficiente numa das atribuições; operação integral recusada.', 'allocations');
}
}
foreach ($effects as $effect) {
$this->query('budget_distribution_entries')->insert($effect);
}
$snapshot = ['allocations' => $frozen, 'lines' => $lines, 'revision' => $revision, 'plan_hash' => BudgetDistributionPlan::fingerprint($plan, $revision)];
$this->query('budget_distributions')->where('id', $source->id)->update(['phase' => $kind, 'snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR), 'updated_at' => $this->stamp()]);
$result = ['distribution_id' => (int) $source->id, 'phase' => $kind, 'plan_hash' => $snapshot['plan_hash']];
$this->distributionEvent((int) $source->id, $kind, $operation, $hash, $result, $snapshot);
$this->emit('budget.distribution_'.$kind, $result, $origin);
return $result + ['replayed' => false];
});
}
/** Explicit host-authorised amendment; never changes the native document totals. */
public function amendDistribution(int $origin, array $allocations, string $expectedHash, string $reason, string $operation, ?array $referenceLines = null): array
{
return $this->atomic('distribution.amend', function () use ($origin, $allocations, $expectedHash, $reason, $operation, $referenceLines): array {
$this->distributionOperation($origin, $operation);
if (! preg_match('/^[a-f0-9]{64}$/D', $expectedHash) || mb_strlen(trim($reason)) < 10 || mb_strlen($reason) > 4000) {
$this->fail('Versão anterior e motivo explícito obrigatórios.', 'allocations');
}
$source = $this->distributedOrigin($origin);
if (! $source || $source->phase !== 'commit') {
$this->fail('Reafectação exige compromisso vigente.', 'allocations', 409);
}
$previous = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
$lines = $referenceLines ?? $previous['lines'];
$plan = BudgetDistributionPlan::normalise($allocations, $lines);
$oldLines = $previous['lines'];
ksort($lines);
ksort($oldLines);
if (array_keys($lines) !== array_keys($oldLines)
|| array_column($lines, 'required_kind') !== array_column($oldLines, 'required_kind')
|| array_sum(array_column($lines, 'subtotal_minor')) !== array_sum(array_column($oldLines, 'subtotal_minor'))
|| array_sum(array_column($lines, 'total_minor')) !== array_sum(array_column($oldLines, 'total_minor'))) {
$this->fail('Reafectação deve preservar artigos, classificação e totais documentais nativos.', 'allocations');
}
$kind = 'amend-'.substr($expectedHash, 0, 32);
$hash = hash('sha256', json_encode([$expectedHash, $plan, $lines, $reason], JSON_THROW_ON_ERROR));
if ($replay = $this->distributionReplay((int) $source->id, $kind, $operation, $hash)) {
return $replay;
}
if ($expectedHash !== $previous['plan_hash'] || self::distributionIdentities($plan) !== self::distributionIdentities($previous['allocations'])) {
$this->fail('Compromisso alterado; consulte a versão actual antes de reafectar.', 'allocations', 409);
}
$planFingerprint = BudgetDistributionPlan::fingerprint($plan, $previous['revision']);
$oldPlan = array_map(fn ($row) => array_intersect_key($row, array_flip(['allocation_key', 'line_id', 'centre_id', 'subtotal_minor', 'total_minor'])), $previous['allocations']);
if ($planFingerprint === BudgetDistributionPlan::fingerprint(BudgetDistributionPlan::normalise($oldPlan, $previous['lines']), $previous['revision'])) {
$this->fail('Reafectação sem alteração de valores.', 'allocations');
}
$nextHash = hash('sha256', $expectedHash.':'.(($previous['amendment_version'] ?? 0) + 1).':'.$planFingerprint);
$old = array_column($previous['allocations'], null, 'allocation_key');
$centres = array_values(array_unique(array_column($plan, 'centre_id')));
sort($centres, SORT_NUMERIC);
$budgets = [];
foreach ($centres as $centre) {
$frozen = collect($previous['allocations'])->firstWhere('centre_id', $centre);
$budget = $this->allocation($frozen['budget_id']);
if (! $budget->approved_by || (int) $budget->year !== $this->context->year
|| (int) $budget->cost_center_id !== $centre || (bool) $budget->includes_tax !== $frozen['includes_tax'] || $budget->kind !== $frozen['required_kind']) {
$this->fail('Dotação incompatível com o compromisso.', 'allocations');
}
$budgets[$centre] = $budget;
}
$effects = $changes = $frozenPlan = [];
foreach ($plan as $allocation) {
$frozen = $old[$allocation['allocation_key']];
$used = $this->query('budget_distribution_consumptions')->where('distribution_id', $source->id)->where('allocation_key', $allocation['allocation_key']);
foreach (['subtotal_minor', 'total_minor'] as $field) {
if ($allocation[$field] < (int) (clone $used)->sum($field)) {
$this->fail('Reafectação não pode reduzir valores já consumidos.', 'allocations');
}
}
$field = $frozen['includes_tax'] ? 'total_minor' : 'subtotal_minor';
$delta = $allocation[$field] - $frozen[$field];
$changes[$allocation['centre_id']] = ($changes[$allocation['centre_id']] ?? 0) + $delta;
$effects[] = $this->context->scope + ['distribution_id' => $source->id, 'allocation_key' => $allocation['allocation_key'],
'budget_id' => $frozen['budget_id'], 'kind' => $kind, 'reserved_minor' => 0, 'committed_minor' => $delta,
'created_by' => $this->context->actorId, 'created_at' => $this->stamp()];
$frozenPlan[] = $allocation + ['budget_id' => $frozen['budget_id'], 'includes_tax' => $frozen['includes_tax']];
}
foreach ($changes as $centre => $delta) {
if ($this->balanceOf($budgets[$centre])['available_minor'] < $delta) {
$this->fail('Saldo insuficiente para a reafectação integral.', 'allocations');
}
}
foreach ($effects as $effect) {
$this->query('budget_distribution_entries')->insert($effect);
}
$snapshot = [...$previous, 'allocations' => $frozenPlan, 'lines' => $lines, 'plan_hash' => $nextHash,
'previous_plan_hash' => $expectedHash, 'amendment_version' => ($previous['amendment_version'] ?? 0) + 1, 'reason' => trim($reason)];
$this->query('budget_distributions')->where('id', $source->id)->update(['snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR), 'updated_at' => $this->stamp()]);
$result = ['distribution_id' => (int) $source->id, 'phase' => 'commit', 'plan_hash' => $nextHash, 'amendment_version' => $snapshot['amendment_version']];
$this->distributionEvent((int) $source->id, $kind, $operation, $hash, $result, $snapshot);
$this->emit('budget.distribution_amended', $result, $origin);
return $result + ['replayed' => false];
});
}
/** Same authoritative validation for preparation and consumption; no effects or audit. */
public function checkDistributionConsumption(int $origin, array $allocations, array $lines): array
{
return $this->atomic('consume.preview', function () use ($origin, $allocations, $lines): array {
$this->requireDistributionSchema();
$source = $this->distributedOrigin($origin);
if (! $source || $this->query('budget_entries')->where('requisition_id', $origin)->exists()) {
$this->fail('Factura sem compromisso distribuído compatível.', 'invoice');
}
$this->distributionConsumptionBindings($source, BudgetDistributionPlan::normalise($allocations, $lines));
$snapshot = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
return ['distribution_id' => (int) $source->id, 'plan_hash' => $snapshot['plan_hash']];
});
}
private function distributionConsumptionBindings(object $source, array $plan): array
{
if ($source->phase !== 'commit') {
$this->fail('Distribuição não comprometida.', 'invoice', 409);
}
$snapshot = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
$committed = array_column($snapshot['allocations'], null, 'allocation_key');
$ids = [];
foreach ($plan as $allocation) {
$frozen = $committed[$allocation['allocation_key']] ?? null;
if (! $frozen || self::distributionIdentities([$allocation]) !== self::distributionIdentities([$frozen])) {
$this->fail('Atribuição da factura difere do compromisso congelado.', 'invoice');
}
$ids[] = $frozen['budget_id'];
}
$ids = array_values(array_unique($ids));
sort($ids, SORT_NUMERIC);
$budgets = [];
foreach ($ids as $id) {
$budgets[$id] = $this->allocation($id);
}
$bindings = [];
foreach ($plan as $allocation) {
$frozen = $committed[$allocation['allocation_key']];
$prior = $this->query('budget_distribution_consumptions')->where('distribution_id', $source->id)->where('allocation_key', $allocation['allocation_key']);
foreach (['subtotal_minor', 'total_minor'] as $field) {
if ($allocation[$field] > $frozen[$field] - (int) (clone $prior)->sum($field)) {
$this->fail('Consumo parcial ultrapassa a atribuição congelada.', 'invoice');
}
}
$budget = $budgets[$frozen['budget_id']];
if (! $budget->approved_by || (int) $budget->year !== $this->context->year || (bool) $budget->includes_tax !== $frozen['includes_tax']
|| $budget->kind !== $frozen['required_kind'] || (int) $budget->cost_center_id !== $allocation['centre_id']) {
$this->fail('Dotação do consumo incompatível ou fora do exercício.', 'invoice');
}
$amount = $budget->includes_tax ? $allocation['total_minor'] : $allocation['subtotal_minor'];
$entries = $this->query('budget_distribution_entries')->where('distribution_id', $source->id)->where('allocation_key', $allocation['allocation_key']);
if ($amount > (int) $entries->sum('committed_minor')) {
$this->fail('Compromisso insuficiente para a atribuição da factura.', 'invoice');
}
$bindings[] = ['allocation' => $allocation, 'budget' => $budget, 'amount' => $amount];
}
return $bindings;
}
public function consumeDistribution(int $origin, int $invoice, array $allocations, array $lines, string $revision, string $operation): array
{
return $this->atomic('consume', function () use ($origin, $invoice, $allocations, $lines, $revision, $operation): array {
$this->distributionOperation($origin, $operation);
if ($invoice < 1) {
$this->fail('Factura nativa obrigatória.', 'invoice');
}
$plan = BudgetDistributionPlan::normalise($allocations, $lines);
$kind = 'invoice-'.$invoice;
$hash = hash('sha256', $kind.':'.BudgetDistributionPlan::fingerprint($plan, $revision));
$source = $this->distributedOrigin($origin);
if (! $source) {
$this->fail('Factura sem distribuição comprometida.', 'invoice');
}
if ($replay = $this->distributionReplay((int) $source->id, $kind, $operation, $hash)) {
return $replay;
}
if (($this->orderPartsReady() && $this->query('budget_order_consumptions')->where('invoice_id', $invoice)->exists())
|| $source->phase !== 'commit' || $this->query('budget_consumptions')->where('invoice_id', $invoice)->exists()
|| $this->query('budget_distribution_consumptions')->where('invoice_id', $invoice)->exists()) {
$this->fail('Factura já consumida ou distribuição não comprometida.', 'invoice', 409);
}
$used = [];
foreach ($this->distributionConsumptionBindings($source, $plan) as $binding) {
['allocation' => $allocation, 'budget' => $budget, 'amount' => $amount] = $binding;
$this->query('budget_distribution_entries')->insert($this->context->scope + ['distribution_id' => $source->id,
'allocation_key' => $allocation['allocation_key'], 'budget_id' => $budget->id, 'kind' => $kind,
'reserved_minor' => 0, 'committed_minor' => -$amount, 'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]);
$this->query('budget_distribution_consumptions')->insert($this->context->scope + ['distribution_id' => $source->id,
'allocation_key' => $allocation['allocation_key'], 'budget_id' => $budget->id, 'invoice_id' => $invoice,
'amount_minor' => $amount, 'subtotal_minor' => $allocation['subtotal_minor'], 'total_minor' => $allocation['total_minor'],
'created_by' => $this->context->actorId, 'created_at' => $this->stamp()]);
$used[] = ['allocation_key' => $allocation['allocation_key'], 'budget_id' => (int) $budget->id, 'consumed_minor' => $amount];
}
$result = ['distribution_id' => (int) $source->id, 'invoice_id' => $invoice, 'allocations' => $used];
$this->distributionEvent((int) $source->id, $kind, $operation, $hash, $result, ['allocations' => $plan, 'lines' => $lines, 'revision' => $revision]);
$this->emit('budget.consumed', $result, $origin);
return $result + ['replayed' => false];
});
}
}
@@ -0,0 +1,132 @@
<?php
namespace Tempo\Finance\Budget;
/** Documentary reconciliation only. No debt, budget journal, tax or exchange writer. */
final class BudgetLandedCostPlan
{
public const VERSION = 'COMMON-BUDGET-LANDED-COST-QA-v1';
/**
* The host resolves authenticated native documents and their frozen MZN references.
* Components are explicit documentary portions, never estimated tax rates or percentages.
*
* @param list<array<string,mixed>> $components
* @param array<string,array<string,mixed>> $documents
* @return array<string,mixed>
*/
public static function reconcile(array $components, array $documents, bool $includesTax): array
{
if (! array_is_list($components) || $components === [] || count($components) > 500 || $documents === [] || count($documents) > 100) {
self::invalid('Indique componentes e origens documentais explícitas.');
}
$money = ['subtotal_minor', 'tax_minor', 'total_minor', 'reference_subtotal_minor', 'reference_tax_minor', 'reference_total_minor'];
$totals = array_fill_keys($money, 0);
$used = $keys = $result = $currencies = [];
foreach ($documents as $key => $document) {
if (! is_array($document) || array_diff(array_keys($document), [...$money, 'kind', 'id', 'source_key', 'source_version', 'creditor_key', 'currency', 'revision']) !== []
|| ! is_string($key) || ! preg_match('/^[A-Za-z0-9:_-]{1,120}$/D', $key)
|| ! in_array($document['kind'] ?? null, ['supplier_invoice', 'carrier_invoice', 'insurer_invoice', 'customs_assessment', 'other_charge'], true)
|| ! is_int($document['id'] ?? null) || $document['id'] < 1
|| ! is_string($document['source_key'] ?? null) || ! preg_match('/^[A-Za-z0-9:_-]{1,120}$/D', $document['source_key'])
|| ! is_int($document['source_version'] ?? null) || $document['source_version'] < 1
|| ! is_string($document['creditor_key'] ?? null) || ! preg_match('/^[A-Za-z0-9:_-]{1,120}$/D', $document['creditor_key'])
|| ! is_string($document['currency'] ?? null) || ! preg_match('/^[A-Z]{3}$/D', $document['currency'])
|| ! is_string($document['revision'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $document['revision'])) {
self::invalid('A origem nativa, credor, moeda e revisão devem estar identificados.');
}
self::amounts($document);
$identity = (in_array($document['kind'], ['supplier_invoice', 'carrier_invoice', 'insurer_invoice'], true) ? 'invoice' : $document['kind']).':'.$document['id'];
if (isset($keys[$identity]) || isset($keys['source:'.$document['source_key']])) {
self::invalid('O mesmo documento não pode ser incluído duas vezes.');
}
$keys[$identity] = true;
$keys['source:'.$document['source_key']] = true;
$documents[$key] = array_replace(array_fill_keys(['kind', 'id', 'source_key', 'source_version', 'creditor_key', 'currency', 'revision', ...$money], null), $document);
$used[$key] = array_fill_keys($money, 0);
}
$keys = [];
foreach ($components as $component) {
if (! is_array($component) || array_diff(array_keys($component), [...$money, 'component_key', 'kind', 'origin']) !== []
|| ! is_string($component['component_key'] ?? null) || ! preg_match('/^[A-Za-z0-9:_-]{1,120}$/D', $component['component_key'])
|| isset($keys[$component['component_key']]) || ! is_string($component['origin'] ?? null) || ! isset($documents[$component['origin']])
|| ! in_array($component['kind'] ?? null, ['goods', 'freight', 'insurance', 'duty', 'ice', 'vat', 'other'], true)) {
self::invalid('Componente inválido, repetido ou sem origem documental.');
}
self::amounts($component);
$origin = $component['origin'];
$document = $documents[$origin];
if (($component['kind'] === 'goods' && $document['kind'] !== 'supplier_invoice')
|| (in_array($component['kind'], ['duty', 'ice', 'vat'], true) && $document['kind'] !== 'customs_assessment')) {
self::invalid('A natureza do componente não corresponde à origem documental.');
}
foreach ($money as $field) {
if ($component[$field] > $document[$field] - $used[$origin][$field]) {
self::invalid('Os componentes ultrapassam o documento nativo.');
}
$used[$origin][$field] += $component[$field];
}
$keys[$component['component_key']] = true;
$result[] = array_replace(array_fill_keys(['component_key', 'kind', 'origin', ...$money], null), $component);
}
foreach ($documents as $key => $document) {
foreach ($money as $field) {
if ($used[$key][$field] !== $document[$field]) {
self::invalid('Os componentes devem reconciliar exactamente com cada documento, sem compensar credores.');
}
}
$currency = $document['currency'];
$currencies[$currency] ??= ['subtotal_minor' => 0, 'tax_minor' => 0, 'total_minor' => 0];
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
self::add($currencies[$currency][$field], $document[$field]);
self::add($totals['reference_'.$field], $document['reference_'.$field]);
}
}
usort($result, fn (array $a, array $b): int => strcmp($a['component_key'], $b['component_key']));
ksort($documents);
ksort($currencies);
$plan = ['contract' => self::VERSION, 'documents' => $documents, 'components' => $result, 'documentary_totals' => $currencies,
'reference_currency' => 'MZN', 'subtotal_minor' => $totals['reference_subtotal_minor'], 'tax_minor' => $totals['reference_tax_minor'],
'total_minor' => $totals['reference_total_minor'], 'includes_tax' => $includesTax,
'budget_amount_minor' => $totals[$includesTax ? 'reference_total_minor' : 'reference_subtotal_minor']];
return [...$plan, 'fingerprint' => hash('sha256', json_encode($plan, JSON_THROW_ON_ERROR)), 'financial_effects' => false];
}
/** @param array<string,mixed> $row */
private static function amounts(array $row): void
{
foreach (['', 'reference_'] as $prefix) {
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
$value = $row[$prefix.$field] ?? null;
if (! is_int($value) || $value < 0 || $value > BudgetControl::MAX_MINOR) {
self::invalid('Montante documental ou referência MZN desconhecido ou não representável.');
}
}
if ($row[$prefix.'subtotal_minor'] > $row[$prefix.'total_minor']
|| $row[$prefix.'tax_minor'] !== $row[$prefix.'total_minor'] - $row[$prefix.'subtotal_minor']) {
self::invalid('Base, imposto e total devem reconciliar exactamente.');
}
}
if (($row['currency'] ?? null) === 'MZN') {
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
if ($row[$field] !== $row['reference_'.$field]) {
self::invalid('Um documento em MZN conserva os seus valores nativos.');
}
}
}
}
private static function add(int &$sum, int $amount): void
{
if ($amount > BudgetControl::MAX_MINOR - $sum) {
self::invalid('O custo agregado excede a representação monetária suportada.');
}
$sum += $amount;
}
private static function invalid(string $message): never
{
throw new BudgetFailure($message, 'components', 422);
}
}
@@ -0,0 +1,376 @@
<?php
namespace Tempo\Finance\Budget;
/** Additional documentary origins, within the same budget authority and organisation lock. */
trait BudgetLandedCosts
{
private function landedCostsReady(): bool
{
$found = 0;
foreach (['budget_landed_commands', 'budget_landed_entries'] as $table) {
$found += $this->db->getSchemaBuilder()->hasTable($this->prefix.$table) ? 1 : 0;
}
if ($found !== 0 && $found !== 2) {
$this->fail('Estrutura do custo de aterragem incompleta; saldo não presumido.', 'components', 503);
}
return $found === 2;
}
private function landedKey(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 preparação ou operação obrigatório.', 'components');
}
}
private function landedReplay(string $planKey, string $kind, string $operation, array $input): array
{
if (! $this->landedCostsReady()) {
$this->fail('Contrato financeiro de aterragem não instalado nesta composição.', 'components', 503);
}
$this->landedKey($planKey);
$this->landedKey($operation);
$hash = hash('sha256', json_encode([$planKey, $kind, $input], JSON_THROW_ON_ERROR));
$old = $this->query('budget_landed_commands')->where('operation_key', $operation)->first();
if ($old !== null) {
if ($old->plan_key !== $planKey || $old->kind !== $kind || ! hash_equals($old->payload_hash, $hash)) {
$this->fail('Operação já usada com outra origem, versão ou conteúdo.', 'operation_key', 409);
}
return ['hash' => $hash, 'result' => json_decode($old->snapshot, true, 64, JSON_THROW_ON_ERROR)['result'] + ['replayed' => true]];
}
foreach (['budget_distribution_events', 'budget_order_commands'] as $table) {
if ($this->db->getSchemaBuilder()->hasTable($this->prefix.$table) && $this->query($table)->where('operation_key', $operation)->exists()) {
$this->fail('A operação pertence a outro contrato financeiro.', 'operation_key', 409);
}
}
if (! $this->db->getSchemaBuilder()->hasColumn($this->prefix.'budget_landed_entries', 'source_snapshot')) {
$this->fail('Preserve o histórico e prepare a estrutura compatível antes de novos movimentos.', 'components', 503);
}
return ['hash' => $hash, 'result' => null];
}
private function landedLatest(string $planKey): ?array
{
$row = $this->query('budget_landed_commands')->where('plan_key', $planKey)->latest('id')->lockForUpdate()->first();
if ($row === null) {
return null;
}
$snapshot = json_decode($row->snapshot, true, 64, JSON_THROW_ON_ERROR);
$entries = $this->query('budget_landed_entries')->whereIn('command_id', $this->query('budget_landed_commands')->where('plan_key', $planKey)->select('id'))
->select('source_key')->selectRaw('SUM(reserved_minor) AS reserved_minor, SUM(committed_minor) AS committed_minor, SUM(consumed_minor) AS consumed_minor')
->groupBy('source_key')->get();
$positions = [];
foreach ($entries as $entry) {
$position = ['reserved_minor' => (int) $entry->reserved_minor, 'committed_minor' => (int) $entry->committed_minor, 'consumed_minor' => (int) $entry->consumed_minor];
foreach ($position as $amount) {
if ($amount < 0 || $amount > self::MAX_MINOR) {
$this->fail('Posição histórica inconsistente; nenhum saldo foi compensado.', 'components', 503);
}
}
if (! isset($snapshot['book'][$entry->source_key])) {
if (array_sum($position) !== 0) {
$this->fail('Uma origem retirada conserva efeitos financeiros; reconcilie o histórico.', 'components', 503);
}
continue;
}
$frozen = $snapshot['positions'][$entry->source_key] ?? null;
if ($frozen !== null) {
foreach ($position as $field => $amount) {
if (($frozen[$field] ?? null) !== $amount) {
$this->fail('O snapshot não corresponde ao diário financeiro preservado.', 'components', 503);
}
}
}
if (array_sum($position) > $snapshot['book'][$entry->source_key]['amount_minor']) {
$this->fail('Os efeitos excedem o custo documental actual.', 'components', 503);
}
$phase = $position['reserved_minor'] > 0 ? 'reserved' : ($position['committed_minor'] > 0 ? 'committed'
: ($position['consumed_minor'] > 0 ? ($position['consumed_minor'] === $snapshot['book'][$entry->source_key]['amount_minor'] ? 'consumed' : 'cancelled')
: ($frozen['phase'] ?? $snapshot['result']['phase'])));
if (! in_array($phase, ['reserved', 'committed', 'consumed', 'cancelled'], true)) {
$this->fail('A fase da origem de valor zero está indeterminada.', 'components', 503);
}
$positions[$entry->source_key] = $position + ['phase' => $phase];
}
if (count($positions) !== count($snapshot['book'])) {
$this->fail('O diário de uma origem documental está em falta.', 'components', 503);
}
$snapshot['positions'] = $positions;
$snapshot['result']['revision'] = $this->query('budget_landed_commands')->where('plan_key', $planKey)->count();
return $snapshot;
}
public function landedCostState(string $planKey): ?array
{
return $this->atomic('view', function () use ($planKey) {
$this->landedKey($planKey);
return $this->landedCostsReady() ? $this->landedLatest($planKey) : null;
});
}
private function landedBudget(int $id, ?bool $includesTax = null): object
{
if ($this->context->currency !== 'MZN') {
$this->fail('Esta composição exige MZN como moeda de referência, conservando a moeda original de cada documento.', 'budget_id');
}
$budget = $this->allocation($id);
if (! $budget->approved_by || (int) $budget->year !== $this->context->year
|| ($includesTax !== null && (bool) $budget->includes_tax !== $includesTax)) {
$this->fail('Dotação não aprovada, fora do exercício ou com base de imposto alterada.', 'budget_id', 409);
}
return $budget;
}
private function landedBook(array $plan, string $planKey): array
{
$book = [];
foreach ($plan['documents'] as $document) {
// These invoices already have their native principal and budget authority.
if (in_array($document['kind'], ['supplier_invoice', 'carrier_invoice', 'insurer_invoice'], true)) {
continue;
}
$other = $this->query('budget_landed_entries')->where('source_key', $document['source_key'])
->whereIn('command_id', $this->query('budget_landed_commands')->where('plan_key', '!=', $planKey)->select('id'))->exists();
if ($other) {
$this->fail('A origem adicional já pertence a outra preparação financeira.', 'components', 409);
}
$source = $document + ['amount_minor' => $document[$plan['includes_tax'] ? 'reference_total_minor' : 'reference_subtotal_minor']];
$last = $this->query('budget_landed_entries')->where('source_key', $document['source_key'])->latest('id')->first();
if ($last !== null) {
$previous = json_decode($last->source_snapshot, true, 64, JSON_THROW_ON_ERROR);
if ($source['kind'] !== $previous['kind'] || $source['source_version'] < $previous['source_version']
|| ($source['source_version'] === $previous['source_version'] && $source !== $previous)) {
$this->fail('A origem deve conservar a identidade e versionar qualquer correcção documental.', 'components', 409);
}
}
$book[$document['source_key']] = $source;
}
ksort($book);
return $book;
}
private function landedAmount(array $book): int
{
$sum = 0;
foreach ($book as $source) {
if ($source['amount_minor'] > self::MAX_MINOR - $sum) {
$this->fail('Montante adicional não representável.', 'components');
}
$sum += $source['amount_minor'];
}
return $sum;
}
private function landedWrite(string $kind, string $planKey, int $version, int $budgetId, array $plan, array $book, string $phase, string $operation, string $hash, array $effects): array
{
$before = $this->landedLatest($planKey);
$positions = $before['positions'] ?? [];
foreach ($effects as $key => $effect) {
$position = $positions[$key] ?? ['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 0, 'phase' => 'cancelled'];
foreach (['reserved_minor', 'committed_minor', 'consumed_minor'] as $field) {
$position[$field] += $effect[$field];
if ($position[$field] < 0 || $position[$field] > self::MAX_MINOR) {
$this->fail('O movimento produziria uma posição negativa ou não representável.', 'components');
}
}
$position['phase'] = $effect['phase_after'] ?? $phase;
if (! isset($book[$key])) {
if ($position['reserved_minor'] + $position['committed_minor'] + $position['consumed_minor'] !== 0) {
$this->fail('Uma origem retirada não pode conservar efeitos.', 'components');
}
unset($positions[$key]);
continue;
}
if ($position['reserved_minor'] + $position['committed_minor'] + $position['consumed_minor'] > $book[$key]['amount_minor']) {
$this->fail('O movimento ultrapassaria o custo documental revisto.', 'components');
}
$positions[$key] = $position;
}
$reserved = array_sum(array_column($positions, 'reserved_minor'));
$committed = array_sum(array_column($positions, 'committed_minor'));
$consumed = array_sum(array_column($positions, 'consumed_minor'));
$phases = array_values(array_unique(array_column($positions, 'phase')));
$phase = $positions === [] ? 'cancelled' : (count($phases) === 1 ? $phases[0] : 'mixed');
if (($reserved > 0 && ($committed > 0 || $consumed > 0)) || ($committed > 0 && $consumed > 0)) {
$phase = 'mixed';
}
$origins = [];
foreach ($book as $key => $source) {
$origins[] = ['source_key' => $key, 'kind' => $source['kind'], 'id' => $source['id'], 'source_version' => $source['source_version'],
'documented_amount_minor' => $source['amount_minor'], ...$positions[$key]];
}
$result = ['plan_key' => $planKey, 'version' => $version, 'plan_hash' => $plan['fingerprint'], 'budget_id' => $budgetId,
'phase' => $phase, 'additional_amount_minor' => $this->landedAmount($book), 'total_reference_minor' => $plan['budget_amount_minor'],
'revision' => $this->query('budget_landed_commands')->where('plan_key', $planKey)->count() + 1,
'reserved_minor' => $reserved, 'committed_minor' => $committed, 'consumed_minor' => $consumed, 'origins' => $origins,
'reserved_delta_minor' => array_sum(array_column($effects, 'reserved_minor')),
'committed_delta_minor' => array_sum(array_column($effects, 'committed_minor')),
'consumed_delta_minor' => array_sum(array_column($effects, 'consumed_minor'))];
$snapshot = ['result' => $result, 'plan' => $plan, 'book' => $book, 'positions' => $positions];
$command = $this->query('budget_landed_commands')->insertGetId($this->context->scope + ['created_by' => $this->context->actorId,
'operation_key' => $operation, 'plan_key' => $planKey, 'plan_version' => $version, 'plan_hash' => $plan['fingerprint'],
'kind' => $kind, 'payload_hash' => $hash, 'snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR), 'created_at' => $this->stamp()]);
foreach ($effects as $key => $effect) {
$source = $effect['source'];
$this->query('budget_landed_entries')->insert($this->context->scope + ['command_id' => $command, 'budget_id' => $budgetId,
'source_key' => $key, 'source_kind' => $source['kind'], 'source_id' => $source['id'], 'source_version' => $source['source_version'], 'source_revision' => $source['revision'],
'source_snapshot' => json_encode($source, JSON_THROW_ON_ERROR),
'reserved_minor' => $effect['reserved_minor'], 'committed_minor' => $effect['committed_minor'], 'consumed_minor' => $effect['consumed_minor']]);
}
$this->emit('budget.landed_'.$kind, $result + ['operation_key' => $operation, 'sources' => array_keys($effects)]);
return $result + ['replayed' => false];
}
/** Host supplies the current independently reviewed plan, not a fabricated invoice. */
public function reserveLandedCosts(string $planKey, int $version, int $budgetId, array $components, array $documents, string $operation): array
{
return $this->atomic('landed.reserve', function () use ($planKey, $version, $budgetId, $components, $documents, $operation) {
$budget = $this->landedBudget($budgetId);
$plan = BudgetLandedCostPlan::reconcile($components, $documents, (bool) $budget->includes_tax);
$retry = $this->landedReplay($planKey, 'reserve', $operation, [$version, $budgetId, $plan]);
if ($retry['result'] !== null) {
return $retry['result'];
}
if ($version < 1 || $this->landedLatest($planKey) !== null) {
$this->fail('Preparação já movimentada; use uma reafectação explícita e versionada.', 'version', 409);
}
$book = $this->landedBook($plan, $planKey);
if ($book === []) {
$this->fail('As facturas conservam os efeitos nativos; não há origem adicional a reservar.', 'components');
}
if ($this->landedAmount($book) > $this->balanceOf($budget)['available_minor']) {
$this->fail('Saldo insuficiente para os custos adicionais documentados.', 'budget_id');
}
$effects = [];
foreach ($book as $key => $source) {
$effects[$key] = ['source' => $source, 'reserved_minor' => $source['amount_minor'], 'committed_minor' => 0, 'consumed_minor' => 0];
}
return $this->landedWrite('reserve', $planKey, $version, $budgetId, $plan, $book, 'reserved', $operation, $retry['hash'], $effects);
});
}
public function transitionLandedCosts(string $planKey, int $version, string $planHash, string $kind, string $operation, array $sourceKeys = [], ?int $expectedRevision = null): array
{
if (! in_array($kind, ['commit', 'consume', 'cancel'], true)) {
$this->fail('Acção financeira incompatível com o custo de aterragem.', 'action');
}
if (! array_is_list($sourceKeys) || count($sourceKeys) > 100) {
$this->fail('Seleccione origens distintas desta preparação.', 'sources');
}
foreach ($sourceKeys as $key) {
if (! is_string($key) || ! preg_match('/^[A-Za-z0-9:_-]{1,120}$/D', $key)) {
$this->fail('Origem adicional inválida.', 'sources');
}
}
if (count(array_unique($sourceKeys, SORT_STRING)) !== count($sourceKeys)) {
$this->fail('Seleccione cada origem apenas uma vez.', 'sources');
}
sort($sourceKeys, SORT_STRING);
return $this->atomic('landed.'.$kind, function () use ($planKey, $version, $planHash, $kind, $operation, $sourceKeys, $expectedRevision) {
$input = $sourceKeys === [] && $expectedRevision === null ? [$version, $planHash] : [$version, $planHash, $sourceKeys, $expectedRevision];
$retry = $this->landedReplay($planKey, $kind, $operation, $input);
if ($retry['result'] !== null) {
return $retry['result'];
}
$old = $this->landedLatest($planKey);
if ($old === null || $version !== $old['result']['version'] || ! hash_equals($old['result']['plan_hash'], $planHash)
|| ($expectedRevision !== null && $expectedRevision !== $old['result']['revision'])) {
$this->fail('A preparação financeira mudou; actualize antes de continuar.', 'version', 409);
}
$budgetId = $old['result']['budget_id'];
$this->landedBudget($budgetId, $old['plan']['includes_tax']);
$effects = [];
$keys = $sourceKeys === [] ? array_keys($old['book']) : $sourceKeys;
foreach ($keys as $key) {
$source = $old['book'][$key] ?? $this->fail('Origem fora desta preparação financeira.', 'sources', 403);
$position = $old['positions'][$key];
$eligible = $kind === 'commit' ? $position['phase'] === 'reserved'
: ($kind === 'consume' ? $position['phase'] === 'committed' : in_array($position['phase'], ['reserved', 'committed'], true));
if (! $eligible) {
if ($sourceKeys !== []) {
$this->fail('A selecção contém uma origem fora desta etapa; os consumos anteriores ficam preservados.', 'sources', 409);
}
continue;
}
$effects[$key] = ['source' => $source,
'reserved_minor' => $kind === 'commit' || $kind === 'cancel' ? -$position['reserved_minor'] : 0,
'committed_minor' => $kind === 'commit' ? $position['reserved_minor'] : -$position['committed_minor'],
'consumed_minor' => $kind === 'consume' ? $position['committed_minor'] : 0,
'phase_after' => ['commit' => 'committed', 'consume' => 'consumed', 'cancel' => 'cancelled'][$kind]];
}
if ($effects === []) {
$this->fail('Não existem origens elegíveis nesta etapa; nenhum movimento foi repetido.', 'action', 409);
}
$next = ['commit' => 'committed', 'consume' => 'consumed', 'cancel' => 'cancelled'][$kind];
return $this->landedWrite($kind, $planKey, $version, $budgetId, $old['plan'], $old['book'], $next, $operation, $retry['hash'], $effects);
});
}
/** Reviewed changes preserve consumed floors and never invent a refund or another invoice. */
public function amendLandedCosts(string $planKey, int $expectedVersion, string $expectedHash, int $newVersion, array $components, array $documents, string $operation, ?int $expectedRevision = null): array
{
return $this->atomic('landed.amend', function () use ($planKey, $expectedVersion, $expectedHash, $newVersion, $components, $documents, $operation, $expectedRevision) {
if (! $this->landedCostsReady()) {
$this->fail('Contrato financeiro de aterragem não instalado.', 'components', 503);
}
$this->landedKey($planKey);
$old = $this->landedLatest($planKey);
if ($old === null) {
$this->fail('Preparação financeira inexistente neste âmbito.', 'components', 403);
}
$budgetId = $old['result']['budget_id'];
$budget = $this->landedBudget($budgetId, $old['plan']['includes_tax']);
$plan = BudgetLandedCostPlan::reconcile($components, $documents, (bool) $budget->includes_tax);
$input = [$expectedVersion, $expectedHash, $newVersion, $plan];
if ($expectedRevision !== null) {
$input[] = $expectedRevision;
}
$retry = $this->landedReplay($planKey, 'amend', $operation, $input);
if ($retry['result'] !== null) {
return $retry['result'];
}
if ($expectedVersion !== $old['result']['version'] || ! hash_equals($old['result']['plan_hash'], $expectedHash)
|| $newVersion <= $expectedVersion || ($expectedRevision !== null && $expectedRevision !== $old['result']['revision'])) {
$this->fail('A reafectação exige a posição actual e uma nova preparação conferida.', 'version', 409);
}
$book = $this->landedBook($plan, $planKey);
$effects = [];
foreach (array_unique([...array_keys($old['book']), ...array_keys($book)]) as $key) {
$source = $book[$key] ?? $old['book'][$key];
$position = $old['positions'][$key] ?? ['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 0, 'phase' => 'cancelled'];
$amount = $book[$key]['amount_minor'] ?? 0;
if ($amount < $position['consumed_minor']) {
$this->fail('A alteração não pode apagar ou reduzir um consumo anterior. Preserve a origem e a sua correcção documental.', 'components', 409);
}
$remaining = $amount - $position['consumed_minor'];
$nextPhase = ! isset($book[$key]) ? 'cancelled'
: ($remaining === 0 && ($position['consumed_minor'] > 0 || $position['phase'] === 'consumed') ? 'consumed'
: ($position['phase'] === 'committed' ? 'committed' : 'reserved'));
$reserve = $nextPhase === 'reserved' ? $remaining : 0;
$commit = $nextPhase === 'committed' ? $remaining : 0;
$effects[$key] = ['source' => $source, 'reserved_minor' => $reserve - $position['reserved_minor'],
'committed_minor' => $commit - $position['committed_minor'], 'consumed_minor' => 0, 'phase_after' => $nextPhase];
}
$increase = array_sum(array_column($effects, 'reserved_minor')) + array_sum(array_column($effects, 'committed_minor'));
if ($increase > $this->balanceOf($budget)['available_minor']) {
$this->fail('Saldo insuficiente para a alteração documentada.', 'budget_id');
}
return $this->landedWrite('amend', $planKey, $newVersion, $budgetId, $plan, $book, 'reserved', $operation, $retry['hash'], $effects);
});
}
}
@@ -0,0 +1,383 @@
<?php
namespace Tempo\Finance\Budget;
/** Optional partial-order commands. Uses the existing distribution journal and budget authority. */
trait BudgetOrderParts
{
private function orderPartsReady(): bool
{
$found = 0;
foreach (['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'] as $table) {
$found += $this->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];
});
}
}
+8
View File
@@ -1,5 +1,13 @@
# Receipt movement writer
## Development extension authorised on 21 November 2026
The owner authorised preparing unit conversion in development/QA only. The working source now recognises an optional `quantity_conversion` receipt-line snapshot (`inventory.quantity.v1`): documentary/base units, explicit positive rational factor, source/version, original article and both accepted quantities in integer millesimals. The same writer validates the exact conversion and writes/replays one physical movement. Without that snapshot, the facts, source hash and receipt quantity are unchanged. Published `releases/0.1.0` is untouched.
`QuantityConversion` is the sole exact arithmetic implementation; it rejects nonrepresentable quantities and integer overflow. It never converts prices. The host still validates/freezes the basis, unit mapping and actor under its company lock, and retains original order/receipt/invoice quantities and prices. The prepared Compras adaptation freezes the basis on the first accepted receipt for an order line/article, then requires it on subsequent portions; lots/issues use base units and supplier returns preserve the exact documentary equivalent.
Compras holds a hash-pinned **development artifact**, not a published release. Its loader refuses this artifact outside `testing` and a guarded disposable database; default configuration remains off. No installation, activation or operational change in SGF or the pilot is authorised or performed. Different writer versions require separate kernels. Test results and remaining criteria are recorded in the existing Compras delivery trackers.
`ReceiptMovementWriter` is the single extracted writer for a new accepted physical receipt line. Source code comes from the former insert in Purchasing `ReceiptWorkflow`; versioned artifacts are distributed locally, verified by manifest and never replaced with different contents.
The host owns the company lock, current actor/policy/conflict checks, order eligibility, quantities/units/quality, explicit warehouse/item mapping, lots, downstream signals and audit. It must call the writer within that same transaction, with an authorisation callback. The writer is not a public receipt intake API and must not be used to reconstruct/backfill historical effects or bypass `ReceiptWorkflow`.
+1
View File
@@ -1,2 +1,3 @@
<?php
require_once __DIR__.'/src/QuantityConversion.php';
require_once __DIR__.'/src/ReceiptMovementWriter.php';
@@ -0,0 +1,35 @@
<?php
namespace Tempo\Inventory;
use Brick\Math\BigInteger;
use InvalidArgumentException;
/** Exact physical quantities; never prices or implicit unit assumptions. */
final class QuantityConversion
{
public static function toBase(string $quantityMilli, string $numerator, string $denominator): string
{
foreach ([$quantityMilli, $numerator, $denominator] as $value) {
if (!preg_match('/^\d{1,19}$/D', $value)) {
throw new InvalidArgumentException('A quantidade e os termos do factor devem ser inteiros explícitos.');
}
}
$quantity = BigInteger::of($quantityMilli);
$top = BigInteger::of($numerator);
$bottom = BigInteger::of($denominator);
if ($top->isZero() || $bottom->isZero() || $quantity->isGreaterThan(PHP_INT_MAX)) {
throw new InvalidArgumentException('Factor positivo e quantidade inteira suportada obrigatórios.');
}
[$converted, $remainder] = $quantity->multipliedBy($top)->quotientAndRemainder($bottom);
if (!$remainder->isZero() || $converted->isGreaterThan(PHP_INT_MAX)) {
throw new InvalidArgumentException('Quantidade física não representável em milésimos sem arredondamento.');
}
return (string)$converted;
}
public static function fromBase(string $quantityMilli, string $numerator, string $denominator): string
{
return self::toBase($quantityMilli, $denominator, $numerator);
}
}
@@ -25,9 +25,10 @@ final class ReceiptMovementWriter
$this->checkHost();$facts=$this->facts($lineId,true);$hash=$this->hash($facts);
abort_unless(hash_equals($hash,$expectedHash),409,'A origem da recepção mudou. Faça nova conferência.');
$existing=$this->db->table($this->schema.'.stock_movements')->where(['tenant_id'=>$this->tenant,'goods_receipt_item_id'=>$lineId])->first();
$stockQuantity=$this->stockQuantity($facts);
if($existing){
$snapshot=json_decode($existing->snapshot,true,512,JSON_THROW_ON_ERROR);
abort_unless(($snapshot['inventory_source_hash']??null)===$hash && (string)$existing->quantity_milli===(string)$facts['accepted_milli']
abort_unless(($snapshot['inventory_source_hash']??null)===$hash && (string)$existing->quantity_milli===$stockQuantity
&& (int)$existing->stock_item_id===(int)$facts['stock_item_id'] && (int)$existing->warehouse_id===(int)$facts['warehouse_id'],409,'A origem já tem movimento incompatível ou histórico não reconciliado.');
return ['movement_id'=>(int)$existing->id,'source_hash'=>$hash,'replayed'=>true];
}
@@ -37,13 +38,32 @@ final class ReceiptMovementWriter
'delivery_note'=>$facts['delivery_note'],'reference'=>$facts['delivery_note'],'inventory_source_hash'=>$hash];
$id=$this->db->table($this->schema.'.stock_movements')->insertGetId([
'tenant_id'=>$this->tenant,'goods_receipt_item_id'=>$lineId,'stock_item_id'=>$facts['stock_item_id'],'warehouse_id'=>$facts['warehouse_id'],
'moved_by'=>$this->actor,'quantity_milli'=>$facts['accepted_milli'],'movement_type'=>'receipt_in','moved_at'=>now(),
'moved_by'=>$this->actor,'quantity_milli'=>$stockQuantity,'movement_type'=>'receipt_in','moved_at'=>now(),
'equipment_id'=>$lineSnapshot['equipment_id']??null,'spare_part_id'=>$lineSnapshot['spare_part_id']??null,
'snapshot'=>json_encode($snapshot,JSON_THROW_ON_ERROR),
]);
return ['movement_id'=>(int)$id,'source_hash'=>$hash,'replayed'=>false];
}
/** Legacy facts/hash are unchanged. Converted facts carry their entire frozen basis in line_snapshot. */
private function stockQuantity(array $facts): string
{
$snapshot=json_decode($facts['line_snapshot'],true,512,JSON_THROW_ON_ERROR);
if(!array_key_exists('quantity_conversion',$snapshot))return (string)$facts['accepted_milli'];
$basis=$snapshot['quantity_conversion'];
abort_unless(is_array($basis) && ($basis['schema']??null)==='inventory.quantity.v1'
&& ($basis['stock_item_id']??null)===(int)$facts['stock_item_id']
&& ($basis['document_unit']??null)===($snapshot['order_item']['unit']??null)
&& ($basis['stock_unit']??null)===($snapshot['stock_item']['unit']??null)
&& is_string($basis['numerator']??null) && is_string($basis['denominator']??null)
&& is_string($basis['source']??null) && trim($basis['source'])!==''
&& is_string($basis['version']??null) && trim($basis['version'])!=='',409,'Base de conversão incompleta ou incompatível.');
$converted=QuantityConversion::toBase((string)$facts['accepted_milli'],$basis['numerator'],$basis['denominator']);
abort_unless(($basis['accepted_document_milli']??null)===(string)$facts['accepted_milli']
&& ($basis['accepted_stock_milli']??null)===$converted,409,'Quantidade física divergente da conversão congelada.');
return $converted;
}
private function checkHost(): void
{
if($this->db->transactionLevel()<1)throw new \LogicException('Receipt movement requires the host atomic transaction');