Architecture — Warehouse Stock Entry: Creation, Approval-Gated Balance Mutation, and Immutable Ledger
| Metadata | Details |
|---|---|
| System | inventory-service — Admin Stock Entry (StockEntryService) |
| Document ID | ARCH-2026-INV-002 |
| Author | Engineering Team |
| Status | Approved |
Implements SR-020, per the decisions in ADR-00036. This is the admin-recorded counterpart to Architecture — Inventory Stock Reservation, Consumption, and Concurrency Control, which covers the checkout-driven side of the same shared balance-mutation routine — this doc does not re-describe ReserveInventory/ConsumeInventory’s own sequencing.
Diagram

This diagram is shared with Architecture-00015 — this document is about its “Stock Entry Transaction” and “Open Entry Transaction” rows (admin-recorded movements), not its “Reserver Quantity” / “Consume Quantity” / “Reverse Quantity” rows (checkout-driven, covered by Architecture-00015). The diagram draws “Stock Entry Transaction” flowing directly into “Insert Balance Entry for Stock Entry” as one visual step; the real implementation splits this into two distinct actions — Create (writes the movement, no balance effect) and a separate Approve (performs the balance insert and ledger write) — see flow (A) below for the actual sequencing the diagram’s single arrow summarizes.
Components
| Component | Language / Runtime | Role in this flow |
|---|---|---|
ui-admin-application (React admin panel) |
TypeScript, MUI + Zustand | Operator-facing Stock Entry screens — create/edit a movement, review and approve/reject, clone a prior movement. |
inventory-service — Stock Entry REST API (transport/api/stockentry/) |
Go, Echo | POST/GET/PUT /stock-entries[/:id], POST /stock-entries/:id/approve, POST /stock-entries/:id/reject, POST /stock-entries/:id/clone — every handler wrapped in otel.WithSpan[error]. |
stock_entry_write_impl_svc.go |
Go, service layer | Owns CreateStockEntry, UpdateStockEntry, ApproveStockEntry, RejectStockEntry, CloneStockEntry — SR-020 FR-03–FR-08. |
stock_balance_write_impl_svc.go |
Go, service layer | Owns ProcessWarehouseStockBalance — the single shared balance-mutation routine also used by checkout’s ConsumeInventory (Architecture-00015); ApproveStockEntry calls into it per line item — SR-020 FR-06. |
domain/stockentryprocess/ + its REST handler |
Go, domain + transport layer | PUT /sku-opening-entry, POST /sku-opening-entry/process — bulk opening-entry initialization across many SKU × warehouse pairs in one call, each pair going through the same Create-then-Approve shape as a single manually-recorded Opening Entry movement. |
tenant-migration + tenant-migration-orchestrator |
Node (NestJS) | A second, genuinely automated caller of the two endpoints above: tenant-migration parses PRODUCT_OPENING_ENTRY/PRODUCT_OPENING_ENTRY_PROCESS rows out of an uploaded CSV bundle and publishes them to Pub/Sub; tenant-migration-orchestrator’s product-opening-entry-migration.repository.ts dispatches each one to inventory-service over plain HTTP. Triggered by a bulk tenant-catalog-migration run, not by a product being published for sale — see Technical Debt below. |
stock_transactions (PostgreSQL) |
PostgreSQL table | Movement header — mode, warehouse, product, requires_supervisor_check, status (PENDING/APPROVED/REJECTED), approved_user_id/approved_at. |
stock_transaction_entries (PostgreSQL) |
PostgreSQL table | Line items — one row per SKU × signed quantity_changed, ON DELETE CASCADE from its parent stock_transactions row. |
inventory_balances (PostgreSQL) |
PostgreSQL table | Same table Architecture-00015 describes — ApproveStockEntry mutates it through the identical upsert-acquired row lock checkout consumption uses. |
stock_ledger_entries (PostgreSQL) |
PostgreSQL table | Immutable ledger row, one per approved line item — a BEFORE UPDATE OR DELETE trigger (enforce_immutable_ledger, backed by block_ledger_modifications()) rejects any attempt to alter or remove a row here, unconditionally — SR-020 FR-12. |
sku_opening_entry_warehouse_status (PostgreSQL) |
PostgreSQL table | Tracks which SKU × warehouse pairs have already been opening-entry-initialized, written by MarkSkusWarehouseInitializedTx on approval of an Opening Entry movement — backs the uq_ledger_opening_entry_sku_warehouse uniqueness guard — SR-020 FR-11. |
End-to-end flow (A) — Create → Update → Approve: deferred, transactional balance mutation
- An operator submits a new movement under one of six selectable modes (Purchase, Returns, Adjustment, Opening Entry, Internal Loss, Damage Stock —
Saleis excluded from the mode-selector, reachable only via checkout’sConsumeInventory).CreateStockEntryvalidates each line’s quantity sign against its mode (strictly positive for Purchase/Returns/Opening Entry, strictly negative for Internal Loss/Damage Stock, either sign for Adjustment), then inserts the header and line items withstatus = PENDING— SR-020 FR-01, FR-02. No row ininventory_balancesorstock_ledger_entriesis touched at this step — SR-020 FR-03. - While
statusremainsPENDING, the operator (or another operator) can callUpdateStockEntryto correct the header or line items. An update attempt against a movement that is no longerPENDINGis rejected as a validation error — SR-020 FR-04. - A supervisor calls
ApproveStockEntry. Inside a single database transaction:- For each line item, the sign contract from step 1 is re-validated immediately before mutation — a second, independent check, not a re-trust of the value already validated at creation.
ProcessWarehouseStockBalanceis called per line, applying the already-signedquantity_changedvia the sameINSERT ... ON CONFLICT (warehouse_id, sku_id) DO UPDATE ... RETURNINGupsert-as-lock Architecture-00015 describes for checkout consumption — SR-020 FR-06.- One
stock_ledger_entriesrow is appended per line item, capturingbalance_before/balance_afteras returned by that same upsert. - If the movement’s mode is Opening Entry,
MarkSkusWarehouseInitializedTxmarks each affected SKU × warehouse pair as initialized insku_opening_entry_warehouse_status, in the same transaction — SR-020 FR-07. - The header’s
statusflips toAPPROVED, withapproved_user_id/approved_atset from the approving caller’s own auth context, never the request body — SR-020 NFR-02. - All of the above commit together or none do — SR-020 FR-05.
RejectStockEntryis the only other terminal action fromPENDING— it flipsstatustoREJECTEDwithapproved_user_id/approved_atset to the rejecting caller and timestamp, and performs no balance mutation and no ledger write at all — SR-020 FR-08.
End-to-end flow (B) — Retrieval: frozen ledger balances on an approved movement
GetStockEntryalways returns the movement’s header and line items as stored.- If the movement’s
statusisAPPROVED, each line item is additionally enriched with thebalance_before/balance_aftervalues read back from its correspondingstock_ledger_entriesrow (filteredtransaction_name = 'STOCK_ENTRY') — never recalculated from the current state ofinventory_balances— SR-020 FR-10. APENDINGorREJECTEDmovement has no such values, since no ledger entry was ever written for it. ListStockTransactionssupports pagination plus filtering by warehouse, product, transaction mode, and status — SR-020 FR-09.
End-to-end flow (C) — Clone: start a new movement from a prior one
CloneStockEntryreads the source movement’s header and copies its mode, warehouse, product, and supervisor-review flag into a brand-new header row (status = PENDING, a freshly generated ID,ReferenceInvoiceIDprefixed"CLONE-").- As implemented today, this is where the flow stops short of what BRD-019 BR-05 describes — the source movement’s line items are never read or copied onto the new header, so the clone is a header-only shell with zero line items. (Technical Debt — TD-00014, TD-02.)
End-to-end flow (D) — Opening-Entry Bulk Initialization
A batch of SKU × warehouse pairs reaches PUT /sku-opening-entry / POST /sku-opening-entry/process through either of two real callers today:
- An operator, acting directly in the admin UI.
- The tenant-catalog-migration pipeline — matching this document’s “Migration Open Entry” diagram row:
tenant-migrationparses opening-entry rows out of an uploaded CSV bundle and publishes one Pub/Sub message per record;tenant-migration-orchestratorconsumes each message and calls the same two REST endpoints via itsproduct-opening-entry-migration.repository.ts, mapping CSV-derived product/SKU/warehouse IDs through its ownmigration_id_mappingbefore building the request.
Either way, for each pair not already marked initialized in sku_opening_entry_warehouse_status, the handler follows the same Create → Approve shape as flow (A) above, specifically for the Opening Entry mode — any pair already marked initialized is rejected, enforced at the database level via uq_ledger_opening_entry_sku_warehouse — SR-020 FR-11.
ProcessOpeningEntry’s own doc-comment describes this as gRPC-triggered automatically when a product is published from product-catalog — no such gRPC wiring or product-catalog caller exists in the codebase today. The migration pipeline above is a real, working automated caller, but it is triggered by a bulk catalog-migration run, not by a product going live for sale, and it calls over REST, not gRPC — it is not the integration the doc-comment describes. (See Technical Debt — TD-00014, TD-03 for the full gap and its remediation direction.)
Why this is reliable and auditable
- A movement can never change stock on hand before a supervisor acts on it.
CreateStockEntrywrites only aPENDINGheader and line items — there is no code path by which creation alone mutatesinventory_balances— so BRD-019 BR-02 holds by construction, not by a convention that could be bypassed. See ADR-00036 Part 1 for why this was chosen over an immediate-apply-then-reverse design. - Approval inherits checkout consumption’s own concurrency safety, by construction. Because
ApproveStockEntrycalls the identicalProcessWarehouseStockBalanceroutine Architecture-00015 describes, an approval running concurrently with a checkout sale against the same SKU × warehouse pair is safe under the same row-lock guarantee, with no second concurrency mechanism to get right. - The ledger cannot be altered after the fact, even outside the application.
enforce_immutable_ledger’sBEFORE UPDATE OR DELETEtrigger rejects any modification tostock_ledger_entriesunconditionally — a guarantee that holds against a direct database session, not only againstinventory-service’s own code choosing never to attempt one — SR-020 FR-12, see ADR-00036 Part 2. - A SKU × warehouse pair can never be opening-entry-initialized twice, even under a retried or duplicated bulk request —
uq_ledger_opening_entry_sku_warehouseenforces this at the database, andMarkSkusWarehouseInitializedTxruns in the same transaction as the balance mutation that establishes the pair’s opening count. - What this flow does not yet guarantee: the
requires_supervisor_checkflag is not currently enforced as an actual approval-role gate, and the Clone action does not yet copy line items — both named, tracked gaps rather than silent limitations — Technical Debt — TD-00014.
Related Documents
- BRD-019 — Warehouse Stock Entry: Auditable Movement Recording & Approval Control
- SR-020 — Warehouse Stock Entry: Ledger & Approval Control System Requirements
- ADR-00036 — Deferred, Approval-Gated Balance Mutation and a Database-Enforced Immutable Ledger for Stock Entry
- Technical Debt — Warehouse Stock Entry Gaps
- Architecture — Inventory Stock Reservation, Consumption, and Concurrency Control — the checkout-driven side of the same shared balance-mutation routine and ledger table
- ADR-00035 — Conditional-Update Reservation vs. Row-Locked Consumption, and the Redis/Token-Bucket Scaling Decision
- Microservices: inventory-service