--- id: API-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 --- # API Design — REST/OpenAPI Contracts | Field | Value | |---|---| | **Base path** | `/api/v1` for application APIs; identity protocol endpoints remain at Keycloak | | **Transport** | HTTPS; JSON request/response except documented evidence-upload references | | **AuthN/AuthZ** | Configured OIDC/JWT, role/action policy, verified tenant context before tenant data access (`DEC-021`) | | **Error envelope** | `code`, safe `message`, `correlation_id`, field errors; no secrets or cross-tenant existence disclosure | | **Idempotency** | Required for retryable financial, inventory, state-transition, tenant lifecycle, and evidence-finalization commands; scope key by verified tenant + operation | Paths and method groups below are Stage 9 contracts. Combined method notation (for example POST/GET/PATCH) represents separate operations on the resource. The application must enforce all FR rules and NFR scopes from the Stage 8 SRS. Exact field schemas, pagination limits, error codes and generated OpenAPI components are maintained during construction without changing these semantics. ## Endpoint and component matrix | FR | Operation / endpoint | Contract summary | Authorization / boundary | HLD / LLD | |---|---|---|---|---| | `FR-AUTH-001` | `IdP OIDC authorization-code/PKCE flow; GET /api/v1/auth/session` | Integration / session validation; no credentials or token material are accepted as ordinary business resource fields. | OIDC identity or policy evaluation; no untrusted tenant selector | `HLD-IAM` / `LLD-001` | | `FR-AUTH-002` | `Cross-cutting policy decision at each protected API command/query` | No standalone CRUD endpoint; evaluate role/action/resource permission and segregation rules. | Middleware/worker + RLS invariant; no endpoint | `HLD-IAM` / `LLD-001` | | `FR-AUTH-003` | `POST /api/v1/auth/logout` | End application session; exact provider revocation semantics remain AMB-009. | OIDC identity or policy evaluation; no untrusted tenant selector | `HLD-IAM` / `LLD-001` | | `FR-MKT-001` | `POST /api/v1/market-observations; GET /api/v1/market-observations` | Create/list by explicit tenant-scoped filters; enforce date, quantity, holiday and duplicate rules. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-MARKET-DESK` / `LLD-007` | | `FR-MKT-002` | `PUT /api/v1/market-observations/{observation_id}/rates` | Atomically store min/modal/max; reject nonpositive or out-of-range modal rate. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-MARKET-DESK` / `LLD-007` | | `FR-MARKETTRENDANALYTICS-001` | `GET /api/v1/market-analytics/trends` | Return requested intraday/20-day benchmark series within source FR response-time and data-scope rules. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-REPORTING` / `LLD-005` | | `FR-PROCUREMENTCONTRACTS-001` | `GET /api/v1/procurement/price-variance` | Calculate against tenant policy and current market modal data; explain variance basis. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-PROCUREMENT` / `LLD-004` | | `FR-PROCUREMENTCONTRACTS-002` | `POST /api/v1/procurement/contracts` | Create auction/direct-purchase sauda with source-defined commercial terms. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-PROCUREMENT` / `LLD-004` | | `FR-PROCUREMENTCONTRACTS-003` | `PUT /api/v1/suppliers/{supplier_id}/credit-terms` | Set approved supplier credit days and return computed due date on related purchase. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-PROCUREMENT` / `LLD-004` | | `FR-PROCUREMENTCONTRACTS-004` | `POST /api/v1/procurement/contracts/{contract_id}/levies:calculate` | Calculate/apportion configured cess and statutory levies without inventing rates. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-PROCUREMENT` / `LLD-004` | | `FR-INWARDRECEIVING-001` | `POST /api/v1/receipts/gate-entries` | Create verified inbound vehicle/gate entry. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVING` / `LLD-003` | | `FR-INWARDRECEIVING-002` | `POST /api/v1/receipts/{receipt_id}/weighments` | Record gross/tare measurements and source. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVING` / `LLD-003` | | `FR-INWARDRECEIVING-003` | `POST /api/v1/receipts/{receipt_id}/net-quantity:calculate` | Compute tare deduction/final net quantity using approved policy/contract inputs. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVING` / `LLD-003` | | `FR-INWARDRECEIVING-004` | `POST /api/v1/receipts/{receipt_id}/shortage:assess` | Compare shortage against approved tolerance and capture disposition. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVING` / `LLD-003` | | `FR-INWARDRECEIVING-005` | `POST /api/v1/goods-receipts` | Post GRN, warehouse placement, lot/stock/audit/outbox atomically. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVING` / `LLD-003` | | `FR-INWARDRECEIVING-006` | `POST /api/v1/lots:generate` | Create unique lot/batch identity linked to its source receipt. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVING` / `LLD-003` | | `FR-QUALITYANDLOTCONTROL-001` | `POST /api/v1/lots/{lot_id}/inspections` | Record QC parameters with numeric bounds. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-QUALITY` / `LLD-003` | | `FR-QUALITYANDLOTCONTROL-002` | `POST /api/v1/lots/{lot_id}/quality-adjustments:calculate` | Calculate contract/policy deduction and require authorization at the stated floor. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-QUALITY` / `LLD-003` | | `FR-QUALITYANDLOTCONTROL-003` | `POST /api/v1/lots/{lot_id}/transitions` | Apply allowed QC transition; prevent allocation/dispatch while held. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-QUALITY` / `LLD-003` | | `FR-QUALITYANDLOTCONTROL-004` | `POST /api/v1/lots/{lot_id}/lineage-operations` | Split/blend with exact parent/child quantity conservation and lineage. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-QUALITY` / `LLD-003` | | `FR-WAREHOUSEINVENTORY-001` | `GET /api/v1/inventory/positions; POST /api/v1/inventory/adjustments` | Read derived double-entry positions; adjustment uses reason/approval and cannot create negative stock. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-INVENTORY` / `LLD-003` | | `FR-WAREHOUSEINVENTORY-002` | `GET /api/v1/godowns/{godown_id}/capacity` | Return capacity, current MT and utilization with source warning threshold. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-INVENTORY` / `LLD-003` | | `FR-WAREHOUSEINVENTORY-003` | `POST /api/v1/inventory/transfers` | Post a tenant-scoped transfer aggregate with paired movements and idempotency. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-INVENTORY` / `LLD-003` | | `FR-SALESCONTRACTS-001` | `POST /api/v1/sales/contracts` | Create sales contract with actor authorization and source business constraints. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-SALES` / `LLD-004` | | `FR-SALESCONTRACTS-002` | `GET /api/v1/customers/{customer_id}/credit-exposure; POST /api/v1/credit-checks` | Calculate exposure and credit decision under serialized/consistent transaction semantics. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-SALES` / `LLD-004` | | `FR-SALESCONTRACTS-003` | `POST /api/v1/sales/contracts/{contract_id}/allocations` | Reserve eligible released stock atomically; reject QC-held or unavailable lots. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-SALES` / `LLD-004` | | `FR-DISPATCHDELIVERY-001` | `GET /api/v1/dispatches/board` | Return eligible dispatch work and current blockers. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-DISPATCH` / `LLD-004` | | `FR-DISPATCHDELIVERY-002` | `POST /api/v1/dispatches/{dispatch_id}/manifest` | Record outward weighment/manifest and transition dispatch under inventory/credit rules. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-DISPATCH` / `LLD-004` | | `FR-DISPATCHDELIVERY-003` | `POST /api/v1/dispatches/{dispatch_id}/proof-of-delivery` | Record POD/tracking evidence and status; document storage provider remains unselected. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-DISPATCH` / `LLD-004` | | `FR-FLEETREGISTRY-001` | `POST/GET/PATCH /api/v1/fleet/vehicles` | Maintain vehicle record; reject maintenance vehicles for dispatch assignment. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-FLEET` / `LLD-009` | | `FR-CUSTOMERRECEIVABLES-001` | `GET /api/v1/receivables/ledger` | Query immutable receivable entries and tenant-scoped aging. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVABLES` / `LLD-004` | | `FR-CUSTOMERRECEIVABLES-002` | `GET /api/v1/receivables/credit-exposure; POST /api/v1/receivables/credit-evaluations` | Compute exposure and issue threshold alert from approved tenant policy. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVABLES` / `LLD-004` | | `FR-CUSTOMERRECEIVABLES-003` | `POST /api/v1/customers/{customer_id}/credit-overrides` | Authorize, justify, audit and time-scope partner override; preserve required lock state. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVABLES` / `LLD-004` | | `FR-CUSTOMERRECEIVABLES-004` | `POST /api/v1/receivables/receipts` | Record receipt in append-only financial ledger; bounced reversal uses compensating entry. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-RECEIVABLES` / `LLD-004` | | `FR-SUPPLIERPAYABLES-001` | `GET /api/v1/payables/aging` | Derive payable aging from accepted GRNs and supplier credit days. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-PAYABLES` / `LLD-004` | | `FR-OPERATINGEXPENSES-001` | `POST /api/v1/expenses/vouchers` | Create and post only balanced cash/bank expense voucher. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-EXPENSES` / `LLD-009` | | `FR-OPERATIONALALERTS-001` | `GET /api/v1/alerts; PATCH /api/v1/alerts/{alert_id}/review` | List/review tenant-scoped alerts; notification channel is configurable and no provider is selected. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-EVENTS-ALERTS` / `LLD-005` | | `FR-EXECUTIVEREPORTING-001` | `GET /api/v1/reports/executive-dashboard` | Return the requested KPI/source aggregates within the FR dashboard response target. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-REPORTING` / `LLD-005` | | `FR-EXECUTIVEREPORTING-002` | `GET /api/v1/reports/trading-snapshots` | Return rolling 20-day daily ledger-derived management snapshot. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-REPORTING` / `LLD-005` | | `FR-MASTERDATA-001` | `POST/GET/PATCH /api/v1/master-data/commodities; /varieties; /grades` | Maintain tenant-scoped catalogs; code uniqueness and active-stock delete restriction. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-MASTERDATA` / `LLD-008` | | `FR-MASTERDATA-002` | `POST/GET/PATCH /api/v1/master-data/suppliers; /customers; /godowns` | Maintain tenant-scoped counterparty/location masters; tax ID details subject to AMB-010. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-MASTERDATA` / `LLD-008` | | `FR-TENANTSECURITYAUDIT-001` | `Cross-cutting request/worker/data access enforcement` | No direct endpoint; verified tenant context plus PostgreSQL RLS on all tenant records. | Middleware/worker + RLS invariant; no endpoint | `HLD-ISOLATION-AUDIT` / `LLD-002` | | `FR-TENANTSECURITYAUDIT-003` | `GET /api/v1/audit/events (authorized audit readers only)` | Read immutable events; filters and response fields follow UC permissions/privacy constraints. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-ISOLATION-AUDIT` / `LLD-002` | | `FR-TENANTLIFECYCLE-001` | `POST /api/v1/platform/tenants; PATCH /api/v1/platform/tenants/{tenant_id}/status` | Platform-admin-only create/activate/suspend lifecycle commands with audit. | Platform administrator / operator role, control-plane boundary | `HLD-TENANCY` / `LLD-002` | | `FR-TENANTMEMBERSHIPCONTEXT-001` | `POST/PATCH /api/v1/tenants/{tenant_id}/memberships` | Tenant-admin membership/role administration restricted to that verified tenant. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-TENANCY` / `LLD-002` | | `FR-TENANTMEMBERSHIPCONTEXT-002` | `POST /api/v1/session/active-tenant; cross-cutting request resolver` | Validate chosen tenant membership/role on every API and worker operation; client ID alone grants nothing. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-TENANCY` / `LLD-002` | | `FR-TENANTSUPPORTSECURITY-001` | `Cross-cutting API/worker/export/file/cache isolation` | No direct endpoint; resource ownership and tenant context enforced end to end. | Middleware/worker + RLS invariant; no endpoint | `HLD-ISOLATION-AUDIT` / `LLD-002` | | `FR-TENANTSUPPORTSECURITY-002` | `POST /api/v1/platform/support-access/requests; POST /grants; POST /revocations` | Apply tenant-approved case access or urgent, reasoned, maximum one-hour break-glass grant and alert/notice requirements. | Tenant-admin approval or designated platform security admin with scoped support grant; separate control-plane authorization | `HLD-ISOLATION-AUDIT` / `LLD-002` | | `FR-PRIVACYPURPOSECONSENT-001` | `POST/GET/PATCH /api/v1/privacy/purposes; POST /consent-events` | Maintain responsible-entity-scoped purposes/notices; record consent only when selected basis is consent; process withdrawal. | Responsible fiduciary privacy role; verified tenant or platform scope | `HLD-PRIVACY-INCIDENT-LIFECYCLE` / `LLD-011` | | `FR-DATAPRINCIPALRIGHTS-001` | `POST /api/v1/privacy/requests; GET/PATCH /api/v1/privacy/requests/{request_id}` | Allow no-account intake, verify subject/scope, route to responsible fiduciary, track due date/disposition/evidence. | Public no-account intake creates an unverified case only; protected staff actions require the responsible fiduciary privacy role and verified scope | `HLD-PRIVACY-INCIDENT-LIFECYCLE` / `LLD-011` | | `FR-PRIVACYBREACHRESPONSE-001` | `POST/GET/PATCH /api/v1/privacy/breaches` | Coordinate incident, impact, evidence, roles and notification tasks; statutory deadline values require approved legal configuration. | Responsible fiduciary privacy role; verified tenant or platform scope | `HLD-PRIVACY-INCIDENT-LIFECYCLE` / `LLD-006` | | `FR-RETENTIONERASURE-001` | `POST /api/v1/privacy/retention-schedules; POST /api/v1/privacy/erasure-cases` | Resolve approved schedule/legal holds across stores, execute authorized lifecycle, produce non-sensitive evidence. | Responsible fiduciary privacy role; verified tenant or platform scope | `HLD-PRIVACY-INCIDENT-LIFECYCLE` / `LLD-006` | | `FR-PROCESSORGOVERNANCE-001` | `POST/GET/PATCH /api/v1/platform/processors` | Operator-only processor inventory/due diligence; no live connector implied by inventory. | Platform administrator / operator role, control-plane boundary | `HLD-PROCESSOR-GOVERNANCE` / `LLD-011` | | `FR-TENANTOPERATINGPOLICIES-001` | `POST/GET/PATCH /api/v1/tenant/policies; POST /confirmations` | Version tenant/scope/effective dates; authorized confirmation; block only impacted workflows while unreviewed. | Authenticated role from FR permission matrix; verified active tenant + RLS | `HLD-TENANT-POLICY` / `LLD-010` | ## Shared request, response and failure rules - Tenant ID is resolved from authenticated membership; body/query tenant selectors only scope an already-authorized request. - List endpoints require bounded pagination and deterministic sort; filters apply after tenant scope. Export/report jobs preserve tenant identity, actor, filter and purpose in the job record. - State-changing requests carry an idempotency key when repeated delivery could duplicate a financial, inventory, lifecycle or privacy action. Duplicate keys return the original result or a typed conflict if payload differs. - Validation failures identify a stable rule code and affected field without returning sensitive values. Authorization failures do not disclose whether another tenant’s resource exists. - Concurrency conflicts return a retryable conflict only when the command is safe to retry; financial/stock conflicts require re-read/re-evaluation, not blind overwrite. - `FR-TENANTSECURITYAUDIT-001` and `FR-TENANTSUPPORTSECURITY-001` are enforced across all endpoints, workers and data surfaces. - Authentication/session endpoint details must respect `AMB-009`; browser token storage, exact callback and provider revocation timing are not asserted here. - Privacy deadlines and retention behavior use approved configured rules; missing legal configuration does not silently substitute a guessed duration (`AMB-006`).