--- id: DB-DESIGN-001 parent_ids: [HLD-ATB, UC-001, UC-002, UC-003, UC-004, UC-005, UC-006, UC-007, UC-008, UC-009, UC-010, UC-011, UC-012, UC-013, UC-014, UC-015, UC-016, UC-017, UC-018, UC-019, UC-020, UC-021, UC-022, UC-023, UC-024, UC-025, UC-026] version: 1.0.0 status: Draft — Stage 9 design; Gate 9.1 passed, review pending last_cr: none --- # Database Design — PostgreSQL / SQLAlchemy / Alembic ## 1. Shared persistence rules - Tenant-owned rows include non-null `tenant_id`; tenant-scoped primary/foreign/unique constraints include tenant ownership to prevent cross-tenant references. Use transaction-local PostgreSQL context set only by the verified membership resolver; enable RLS `USING` and `WITH CHECK`. Application runtime roles do not own protected tables and do not have `BYPASSRLS`. - Control-plane records (tenant directory, platform processor inventory, platform-operated privacy cases) use separately authorized tables/role policies; never grant ordinary tenant sessions broad control-plane access. - Use UUID surrogate keys unless a business-readable identifier is explicitly defined (for example the `EXP-YYYYMM-xxx` expense number). `timestamptz` stores instants; business dates use `date` with explicit timezone policy at API boundary. - Use exact numeric types, not binary floating point. Currency precision is 2 decimal places; weight/quantity precision follows source NFR (3 decimal places); rates and percentages use adequate exact numeric scale with source validation. Units are persisted explicitly where conversion is possible. - Posted stock, receivable, payable and cash/bank journal entries are append-only. Corrections create linked reversal/adjustment entries. Mutable query projections carry source version/watermark and are rebuildable. - Every migration adds FK/check/unique indexes and RLS policies with tenant tests; large-ledger query indexes follow measured access patterns. This design is not a migration-executed claim. ## 2. Entity and constraint catalog | Domain / entity | FR scope | Key attributes / relationships | Principal constraints / access | | Identity / Tenant / Membership | FR-AUTH-001–003; FR-TENANTLIFECYCLE-001; FR-TENANTMEMBERSHIPCONTEXT-001/002 | Tenant, external identity subject, active membership, role grants, status/effective timestamps | Tenant control-plane permissions separate; unique (tenant_id, subject); active verified membership required before RLS context. | | MarketObservation | FR-MKT-001/002 | Market, commodity, variety, grade, business date, arrivals MT, stock MT, source, observed_at, holiday status, min/modal/max INR/Qtl | Tenant unique (market, commodity, variety, date); nonfuture date, arrivals >=0, holiday allows absent arrival; positive rates and min<=modal<=max. | | MarketTrendProjection | FR-MARKETTRENDANALYTICS-001 | Date/commodity/market aggregates, source observation IDs, projection watermark | Read model only; tenant keyed; rebuildable and bounded to requested date/20-day domain. | | ProcurementContract / SupplierTerms / Levy | FR-PROCUREMENTCONTRACTS-001–004 | Sauda mode, supplier, commodity, agreed rate/quantity, credit days/due date, levy type/base/rate/amount, modal comparison inputs | Credit days source-approved; configured values/levy rates not invented; contract and calculations tenant-owned. | | GateEntry / Weighment / GoodsReceipt / Lot | FR-INWARDRECEIVING-001–006 | Vehicle/source, gross/tare, packaging tare, net MT, shortage, receipt/GRN identity, warehouse, lot/batch link | Net nonnegative and source formulas/tolerance; unique tenant GRN/lot IDs; atomic GRN/lot/stock/audit/outbox commit. | | Inspection / QualityAdjustment / LotLineage | FR-QUALITYANDLOTCONTROL-001–004 | Inspection measures, officer, grade/status; base/penalty/adjusted rates; parent-child lot IDs and quantities | Percent 0..100; hold/release role FSM; held lot never allocated/dispatched; split quantities conserve parent. | | Warehouse / StockJournal / StockPosition / Transfer / Audit | FR-WAREHOUSEINVENTORY-001–003 | Warehouse capacity; signed inbound/outbound movement; MT/bag units; transfer state; physical count/reason; derived balance | Balanced append-only journal, nonnegative positions; adjustment approval at stated threshold; paired transfer movements in one transaction. | | SalesContract / CreditExposure / LotAllocation | FR-SALESCONTRACTS-001–003 | Customer, contract, quantity/rate, exposure inputs, credit decision, allocated lot/quantity/reservation | Serialize exposure and reservation; approved policy; no held/insufficient lot; idempotent command. | | Dispatch / Manifest / ProofOfDelivery | FR-DISPATCHDELIVERY-001–003 | Eligible order/lot, vehicle, outward weighment, manifest, transit state, POD evidence reference | Only credit-cleared and QC-released allocatable stock; evidence ref tenant-owned; mutation/audit and inventory boundary transactional. | | FleetVehicle | FR-FLEETREGISTRY-001 | Registration, make/model, payload MT, ownership, transporter, status, insurance/fitness expiry | Unique tenant registration; Maintenance cannot be assigned; no telematics integration table. | | Receivable / Receipt / CreditLock / PayableProjection | FR-CUSTOMERRECEIVABLES-001–004; FR-SUPPLIERPAYABLES-001 | Customer/supplier ledger entries, receipt instrument/status, due date, exposure, lock/override, daily payable snapshot | Append-only financial journal; bounced receipt reversal linked and idempotent; payables derive from accepted GRN. | | ExpenseVoucher / CashBankJournal | FR-OPERATINGEXPENSES-001 | Expense ID/date/category/amount/payee/link/payment mode/status and balanced debit-credit references | Currency exact 2 decimals; voucher balances before post; post corrections compensating only. | | OperationalAlert / DashboardSnapshot | FR-OPERATIONALALERTS-001; FR-EXECUTIVEREPORTING-001/002 | Alert condition/source/version/status/created/reviewed; dashboard and daily snapshot values | Tenant key; event consumer idempotency; reporting read model reconciles to ledgers; performance targets remain FR-derived. | | Commodity / Variety / Grade / Counterparty / Godown | FR-MASTERDATA-001/002 | Codes, labels, categories, units/standard bag weight; supplier/customer tax/contact/credit fields; godown capacity/location | Tenant-scoped unique codes; commodity with active stock cannot delete; tax-ID validation open AMB-010. | | AuditEvent / OutboxEvent / IdempotencyRecord | Cross-cutting NFR-AUDIT-001; all governed commands | Actor, tenant, resource/action, timestamp, correlation, FR-specific reason/delta; aggregate/version/event payload/status; command scope key/hash/result | Mutation audit and outbox commit in source transaction; audit append-only; outbox at-least-once; idempotency uniqueness scoped by tenant/operation. | | PrivacyPurpose / ConsentEvidence / RightsRequest | FR-PRIVACYPURPOSECONSENT-001; FR-DATAPRINCIPALRIGHTS-001 | Purpose/category/responsible role/basis/notice; consent/withdrawal evidence; principal reference, scope, request type, verification, deadline/disposition | Separate tenant Fiduciary from platform Fiduciary; consent events only if basis is consent; due dates from approved config; no-account intake. | | BreachCase / RetentionSchedule / ErasureCase / ProcessorRecord | FR-PRIVACYBREACHRESPONSE-001; FR-RETENTIONERASURE-001; FR-PROCESSORGOVERNANCE-001 | Incident/affected scope/evidence refs/roles/notification status; approved purpose schedules/legal holds; deletion workflow; processor location/safeguard/diligence | Privacy case access restricted/audited; hold blocks applicable erase; exact statutory timing/retention open AMB-006; control-plane processor inventory separated. | | TenantPolicyVersion | FR-TENANTOPERATINGPOLICIES-001 | Tenant/type/scope/value/unit/effective range/review actor/time/reason/prior value/version | No overlapping effective ranges for same scope; immutable versions; confirmed policy version referenced by governed transaction; unreviewed blocks only impacted flow. | ## 3. Requirement-to-data ownership matrix | FR | SRS | Owning entity family | |---|---|---| | `FR-AUTH-001` | `SRS-AUTH-001` | See entity catalog row for this FR. | | `FR-AUTH-002` | `SRS-AUTH-002` | See entity catalog row for this FR. | | `FR-AUTH-003` | `SRS-AUTH-003` | See entity catalog row for this FR. | | `FR-MKT-001` | `SRS-MKT-001` | See entity catalog row for this FR. | | `FR-MKT-002` | `SRS-MKT-002` | See entity catalog row for this FR. | | `FR-MARKETTRENDANALYTICS-001` | `SRS-MARKETTRENDANALYTICS-001` | See entity catalog row for this FR. | | `FR-PROCUREMENTCONTRACTS-001` | `SRS-PROCUREMENTCONTRACTS-001` | See entity catalog row for this FR. | | `FR-PROCUREMENTCONTRACTS-002` | `SRS-PROCUREMENTCONTRACTS-002` | See entity catalog row for this FR. | | `FR-PROCUREMENTCONTRACTS-003` | `SRS-PROCUREMENTCONTRACTS-003` | See entity catalog row for this FR. | | `FR-PROCUREMENTCONTRACTS-004` | `SRS-PROCUREMENTCONTRACTS-004` | See entity catalog row for this FR. | | `FR-INWARDRECEIVING-001` | `SRS-INWARDRECEIVING-001` | See entity catalog row for this FR. | | `FR-INWARDRECEIVING-002` | `SRS-INWARDRECEIVING-002` | See entity catalog row for this FR. | | `FR-INWARDRECEIVING-003` | `SRS-INWARDRECEIVING-003` | See entity catalog row for this FR. | | `FR-INWARDRECEIVING-004` | `SRS-INWARDRECEIVING-004` | See entity catalog row for this FR. | | `FR-INWARDRECEIVING-005` | `SRS-INWARDRECEIVING-005` | See entity catalog row for this FR. | | `FR-INWARDRECEIVING-006` | `SRS-INWARDRECEIVING-006` | See entity catalog row for this FR. | | `FR-QUALITYANDLOTCONTROL-001` | `SRS-QUALITYANDLOTCONTROL-001` | See entity catalog row for this FR. | | `FR-QUALITYANDLOTCONTROL-002` | `SRS-QUALITYANDLOTCONTROL-002` | See entity catalog row for this FR. | | `FR-QUALITYANDLOTCONTROL-003` | `SRS-QUALITYANDLOTCONTROL-003` | See entity catalog row for this FR. | | `FR-QUALITYANDLOTCONTROL-004` | `SRS-QUALITYANDLOTCONTROL-004` | See entity catalog row for this FR. | | `FR-WAREHOUSEINVENTORY-001` | `SRS-WAREHOUSEINVENTORY-001` | See entity catalog row for this FR. | | `FR-WAREHOUSEINVENTORY-002` | `SRS-WAREHOUSEINVENTORY-002` | See entity catalog row for this FR. | | `FR-WAREHOUSEINVENTORY-003` | `SRS-WAREHOUSEINVENTORY-003` | See entity catalog row for this FR. | | `FR-SALESCONTRACTS-001` | `SRS-SALESCONTRACTS-001` | See entity catalog row for this FR. | | `FR-SALESCONTRACTS-002` | `SRS-SALESCONTRACTS-002` | See entity catalog row for this FR. | | `FR-SALESCONTRACTS-003` | `SRS-SALESCONTRACTS-003` | See entity catalog row for this FR. | | `FR-DISPATCHDELIVERY-001` | `SRS-DISPATCHDELIVERY-001` | See entity catalog row for this FR. | | `FR-DISPATCHDELIVERY-002` | `SRS-DISPATCHDELIVERY-002` | See entity catalog row for this FR. | | `FR-DISPATCHDELIVERY-003` | `SRS-DISPATCHDELIVERY-003` | See entity catalog row for this FR. | | `FR-FLEETREGISTRY-001` | `SRS-FLEETREGISTRY-001` | See entity catalog row for this FR. | | `FR-CUSTOMERRECEIVABLES-001` | `SRS-CUSTOMERRECEIVABLES-001` | See entity catalog row for this FR. | | `FR-CUSTOMERRECEIVABLES-002` | `SRS-CUSTOMERRECEIVABLES-002` | See entity catalog row for this FR. | | `FR-CUSTOMERRECEIVABLES-003` | `SRS-CUSTOMERRECEIVABLES-003` | See entity catalog row for this FR. | | `FR-CUSTOMERRECEIVABLES-004` | `SRS-CUSTOMERRECEIVABLES-004` | See entity catalog row for this FR. | | `FR-SUPPLIERPAYABLES-001` | `SRS-SUPPLIERPAYABLES-001` | See entity catalog row for this FR. | | `FR-OPERATINGEXPENSES-001` | `SRS-OPERATINGEXPENSES-001` | See entity catalog row for this FR. | | `FR-OPERATIONALALERTS-001` | `SRS-OPERATIONALALERTS-001` | See entity catalog row for this FR. | | `FR-EXECUTIVEREPORTING-001` | `SRS-EXECUTIVEREPORTING-001` | See entity catalog row for this FR. | | `FR-EXECUTIVEREPORTING-002` | `SRS-EXECUTIVEREPORTING-002` | See entity catalog row for this FR. | | `FR-MASTERDATA-001` | `SRS-MASTERDATA-001` | See entity catalog row for this FR. | | `FR-MASTERDATA-002` | `SRS-MASTERDATA-002` | See entity catalog row for this FR. | | `FR-TENANTSECURITYAUDIT-001` | `SRS-TENANTSECURITYAUDIT-001` | See entity catalog row for this FR. | | `FR-TENANTSECURITYAUDIT-003` | `SRS-TENANTSECURITYAUDIT-003` | See entity catalog row for this FR. | | `FR-TENANTLIFECYCLE-001` | `SRS-TENANTLIFECYCLE-001` | See entity catalog row for this FR. | | `FR-TENANTMEMBERSHIPCONTEXT-001` | `SRS-TENANTMEMBERSHIPCONTEXT-001` | See entity catalog row for this FR. | | `FR-TENANTMEMBERSHIPCONTEXT-002` | `SRS-TENANTMEMBERSHIPCONTEXT-002` | See entity catalog row for this FR. | | `FR-TENANTSUPPORTSECURITY-001` | `SRS-TENANTSUPPORTSECURITY-001` | See entity catalog row for this FR. | | `FR-TENANTSUPPORTSECURITY-002` | `SRS-TENANTSUPPORTSECURITY-002` | See entity catalog row for this FR. | | `FR-PRIVACYPURPOSECONSENT-001` | `SRS-PRIVACYPURPOSECONSENT-001` | See entity catalog row for this FR. | | `FR-DATAPRINCIPALRIGHTS-001` | `SRS-DATAPRINCIPALRIGHTS-001` | See entity catalog row for this FR. | | `FR-PRIVACYBREACHRESPONSE-001` | `SRS-PRIVACYBREACHRESPONSE-001` | See entity catalog row for this FR. | | `FR-RETENTIONERASURE-001` | `SRS-RETENTIONERASURE-001` | See entity catalog row for this FR. | | `FR-PROCESSORGOVERNANCE-001` | `SRS-PROCESSORGOVERNANCE-001` | See entity catalog row for this FR. | | `FR-TENANTOPERATINGPOLICIES-001` | `SRS-TENANTOPERATINGPOLICIES-001` | See entity catalog row for this FR. | ## 4. Indexing and retention boundaries - All tenant unique indexes include `tenant_id`; all tenant joins validate matching ownership. - Index common filters by tenant plus business date/status/foreign key. Composite indexes for reports are chosen against the 50,000-row/tenant validation scenario and measured plans, not speculative blanket indexes. - Do not hard-code privacy durations. `RetentionSchedule` must reference purpose/category, approving fiduciary, effective period, legal-hold rule, and review evidence; `AMB-006` blocks concrete values. - Object/evidence references carry tenant, purpose and sensitivity tags as applicable; physical storage provider and backup/erasure contract remain undecided (`AMB-009`). - RLS policy, constraints, and migrations require PostgreSQL integration tests across reused connections and direct SQL paths before the FRs can advance implementation status.