# State Machines, Invariants & UAT — MVP v0.2.0

## 1. State machines: proposed configuration templates
Transitions are controlled by published workflow rules, role policies, guard conditions and audit. These are **proposed pilot presets**, not hardcoded enumerations shared across all industries.

| Domain | States / possible path | Guards and exceptions |
|---|---|---|
| Organization | Invited → Onboarding → Active → Suspended → Archived | validated membership, authorized approver |
| Contract | Draft → InternalReview → AwaitingParties → Active → Expired/Superseded/Terminated | effective dates, version, approval quorum |
| Lot | Draft → Declared → PendingVerification → Accepted → Available → Reserved/Consumed | Quarantined, Disputed, Rejected, Recalled |
| PurchaseOrder | Draft → Submitted → UnderReview → CounterProposed → Confirmed → Allocated → PartialFulfilled → Fulfilled → Closed | Rejected, Cancelled, Expired, Disputed |
| ProductionOrder | Planned → MaterialsReserved → Released → InProgress → OutputRecorded → QC → Completed | Paused, Failed, Scrapped |
| Shipment | Planned → Packed → Dispatched → InTransit → PartiallyReceived/Received → Accepted | Damaged, Disputed, Returned |
| SaleFeed | Received → Validated → Accepted → Reconciled | Quarantined, Duplicate, Rejected, Corrected |
| FinanceCalculation | Draft → Prepared → InReview → Approved → Posted | Disputed, Voided (before posting), Reversed/Adjusted (after) |
| SettlementProof | Claimed → UnderVerification → Verified → Matched | Rejected, Unmatched, PartiallyMatched |
| Period | Open → ClosingReview → AwaitingApproval → Closed | Blocked, ControlledAdjustment |
| DiscrepancyCase | Open → Assigned → EvidenceRequested → UnderReview → Resolved → Closed | Escalated, Reopened with reason |

## 2. Hard invariants
- All stock is scoped by organization, location, product, lot, unit and quality disposition. **Available = OnHand − Reserved − Quarantined** (and other policy holds) must never be negative.
- Each transformation records actual input/output and attributed losses; configured tolerance deviations require resolution and sign-off. No assumed 1:1 wheat→flour.
- A product batch may have many input lots and an input lot may feed many outputs; lineage relationships retain quantity and event evidence.
- GTIN/SKU sales signals do not imply true batch lineage. Exact vs inferred vs unavailable lineage are distinguishable API response states.
- Physical custody, legal ownership, contract claims, liabilities and external funds movements are separate models.
- Journal posting is balanced and not overwritten. Mistakes create documented reversal/adjustment.
- Contract, BOM, workflow and pricing decisions store effective version. Closed-period calculations are not retroactively mutated.
- Integration imports preserve sourceID, externalRecordID, timestamp, raw payload checksum and mappingVersion; duplicates are idempotent.
- No missing tenant/organization scope; no identity-only trust without policy guards; file attachments permission-scoped.
- Unapproved external banking/insurance/securities actions cannot be represented as completed.

## 3. UAT matrix
| UAT ID | User scenario | Given → When → Then |
|---|---|---|
| U01 | Platform config | God Admin adds supported flour-quality field → publishes → API+form render without core edit |
| U02 | Isolation | User in organization A requests organization B lot → 403/404 per policy; no content leakage |
| U03 | Manual/API parity | Same type of lot via form and approved connector → same domain validation/outcomes |
| U04 | Duplicate | POS file/sale event sent twice → exactly one accepted sale and one ledger-impact eligible event |
| U05 | Inventory concurrency | Two requests reserve last 100kg concurrently → sum reservations never exceeds available |
| U06 | Lot genealogy | Mix wheat lots A and B with real consumption → flour batch linked to both with quantity |
| U07 | Mass balance | Unrealistic output exceeds tolerance → run blocked and discrepancy recorded |
| U08 | Order amendment | Confirmed order quantity changed → revision/approval/reservation compensation |
| U09 | Partial delivery | 100 units shipped, 80 accepted, 20 disputed → recipient inventory increases by accepted only |
| U10 | Missing POS batch | POS has GTIN+store only → sale reported SKU level and no false exact lot |
| U11 | Return | Valid return references sale → net sales/eligible finance event adjusted by compensating records |
| U12 | Finance version | Share rate changed effective next period → old posted document unchanged |
| U13 | Balanced ledger | Multi-party calculation → debit=credit; rejected if unbalanced |
| U14 | Payment evidence | Uploaded bank receipt → still unverified until authorized validation |
| U15 | Period closing | Period has unresolved blocker → cannot close; after resolution requires approval |
| U16 | API-only | Every critical command executed without website/UI and passes identical validation |
| U17 | Industry reuse | Second industry org added with new fields + workflow → core domain code unchanged |
| U18 | Dispute audit | Correction after QC/stock issue → complete actor/reason/link to original remains |

## 4. Observability / nonfunctional acceptance (targets need approval)
- OpenAPI schema for every public API and recorded breaking-change rules.
- Trace IDs link API call → domain transaction → outbox → consumer → report.
- Test backups, restore, config publication rollback procedures and data protection.
- Security negative tests, idempotency tests, concurrency tests and migration rehearsal.
- WCAG-oriented accessible RTL UI for basic data entry; clear progress/loading/errors.
- RPO/RTO, p95 latency, throughput, file limits and retention are **open requirements**, not invented commitments.

## 5. Definition of Done per slice
[ ] contract/API documented and validated without UI  
[ ] dynamic customization scenario and versioned metadata documented  
[ ] organization isolation + permission matrix tested  
[ ] positive, negative, partial, retry, duplicate, concurrency and reversal paths tested  
[ ] traceability/source provenance and audit shown  
[ ] docs/changelog updated and real API spec linked when implemented  
[ ] demo in at least two configured organizations; no name hardcoding  
[ ] product/engineering owner has signed relevant acceptance criteria
