Architecture — Warehouse Stock Entry: Creation, Approval-Gated Balance Mutation, and Immutable Ledger

By Engineering Team•October 8, 2026•7 min read
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

Warehouse Stock Entry — recording a movement (top-left "Stock Entry" row) and opening-entry initialization (top "Open Entry Transaction" row), both writing into the same shared Manage Stock Ledger Entry step the checkout-driven Reserve/Consume/Reverse rows below also share

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

  1. An operator submits a new movement under one of six selectable modes (Purchase, Returns, Adjustment, Opening Entry, Internal Loss, Damage Stock — Sale is excluded from the mode-selector, reachable only via checkout’s ConsumeInventory). CreateStockEntry validates 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 with status = PENDING — SR-020 FR-01, FR-02. No row in inventory_balances or stock_ledger_entries is touched at this step — SR-020 FR-03.
  2. While status remains PENDING, the operator (or another operator) can call UpdateStockEntry to correct the header or line items. An update attempt against a movement that is no longer PENDING is rejected as a validation error — SR-020 FR-04.
  3. 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.
    • ProcessWarehouseStockBalance is called per line, applying the already-signed quantity_changed via the same INSERT ... ON CONFLICT (warehouse_id, sku_id) DO UPDATE ... RETURNING upsert-as-lock Architecture-00015 describes for checkout consumption — SR-020 FR-06.
    • One stock_ledger_entries row is appended per line item, capturing balance_before/balance_after as returned by that same upsert.
    • If the movement’s mode is Opening Entry, MarkSkusWarehouseInitializedTx marks each affected SKU × warehouse pair as initialized in sku_opening_entry_warehouse_status, in the same transaction — SR-020 FR-07.
    • The header’s status flips to APPROVED, with approved_user_id/approved_at set 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.
  4. RejectStockEntry is the only other terminal action from PENDING — it flips status to REJECTED with approved_user_id/approved_at set 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

  1. GetStockEntry always returns the movement’s header and line items as stored.
  2. If the movement’s status is APPROVED, each line item is additionally enriched with the balance_before/balance_after values read back from its corresponding stock_ledger_entries row (filtered transaction_name = 'STOCK_ENTRY') — never recalculated from the current state of inventory_balances — SR-020 FR-10. A PENDING or REJECTED movement has no such values, since no ledger entry was ever written for it.
  3. ListStockTransactions supports 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

  1. CloneStockEntry reads 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, ReferenceInvoiceID prefixed "CLONE-").
  2. 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:

  1. An operator, acting directly in the admin UI.
  2. The tenant-catalog-migration pipeline — matching this document’s “Migration Open Entry” diagram row: tenant-migration parses opening-entry rows out of an uploaded CSV bundle and publishes one Pub/Sub message per record; tenant-migration-orchestrator consumes each message and calls the same two REST endpoints via its product-opening-entry-migration.repository.ts, mapping CSV-derived product/SKU/warehouse IDs through its own migration_id_mapping before 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. CreateStockEntry writes only a PENDING header and line items — there is no code path by which creation alone mutates inventory_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 ApproveStockEntry calls the identical ProcessWarehouseStockBalance routine 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’s BEFORE UPDATE OR DELETE trigger rejects any modification to stock_ledger_entries unconditionally — a guarantee that holds against a direct database session, not only against inventory-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_warehouse enforces this at the database, and MarkSkusWarehouseInitializedTx runs 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_check flag 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.