Files
SGF/packages/budget-control/README.md
T
2026-11-23 11:48:07 +02:00

50 lines
10 KiB
Markdown

# Shared budget control — COMMON-BUDGET-SYNTHETIC-v1
Canonical source: this directory. PHP 8.4+, Illuminate Database 13 as supplied by each host. No Brick Math dependency, new vendor packages or version changes. Monetary inputs are exact existing integer MZN cents; document tax/quantity calculations remain in their current host workflows.
`BudgetContext` explicitly carries actor, organisation scope, fiscal reference year and supported currency. `BudgetControl` is the single writer for allocations, approvals, reinforcements, reservation/award/commit/release and invoice budget consumption. Host callbacks acquire the organisation lock, revalidate identity/permissions, audit within the same transaction and check proposer eligibility. No call to auth/session/global DB facade occurs in the package.
Compras uses its existing tables and scope `tenant_id` (company); SGF QA uses separate `cb_` tables scoped by tenant/company/unit with mapped centres/origins. No automatic identifier conversion. There are no sales, payable, payment, industrial budget or remote SGF dependencies.
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.