POS Backend Documentation
Backend architecture, data model, services, cache, queues, runtime rules, and operational behavior for POS.
POS - Backend Documentation
1. Documentation Evidence
| Area | Files Inspected | Verified Details |
|---|---|---|
| Module wiring | apps/api/src/modules/pos/*.module.ts | Aggregate + two admin leaves + worker; imports of Auth, Inventory, Order, Outbox, Payment shared modules |
| Controllers | admin/sale/pos-sale-admin.controller.ts, admin/lookup/pos-lookup-admin.controller.ts, admin/sale-support/pos-sale-support-admin.controller.ts, admin/config/pos-config-admin.controller.ts, admin/return/pos-return-admin.controller.ts | 20 routes, guards, permissions, rate limits, ParseUUIDPipe on every id |
| Services | shared/*.service.ts, pos-totals.util.ts, pos-counter-return.util.ts | One-transaction completion, lock order, outbox mails, lookup semantics, identity resolution, the counter return transaction |
| DTOs | admin/sale/dto/*.ts, admin/lookup/dto/*.ts | Request, query, response validation and shapes |
| Schema | packages/db/src/schema/pos/*.ts, schema/order/enums.ts, migrations 0070-0072 | pos_sale, pos_sale_item, pos_sale_event, pos_counter_returns; enums; CHECK constraints; the Counter Walk-in constant |
| Jobs | packages/jobs/src/index.ts | QueueName.POS, PosJob, payloads (PosSendReceiptPayload.resendKey); the token is not in the payload |
| Cache | cache-invalidation.tags.ts, pos.constants.ts | product_review-style domain: inventory cleared after completion |
| Infra | env.validation.ts | POS_STORE_* config; order-creation.service.ts executor option; order-counter-handover.service.ts |
2. Backend Scope and Boundaries
Owns
- The counter draft: opening a sale, attaching/creating the customer, lines, fulfilment.
- Completion — the one transaction that reserves stock, materialises the checkout pipeline, creates the order and (for pickup) hands over.
- Walk-in account provisioning (no password) and the set-password invitation.
- The
pos_saleaudit timeline. - The hourly abandoned-draft sweep.
- The
channellabel on orders and checkout sessions (defaultsonline). - The
pos_cash/pos_card/pos_qrpayment methods and their counter gateway. - Counter returns: the single transaction that composes the order module's return and refund steps (
PosCounterReturnService), and thepos_counter_returnsidempotency record. - Customer identity resolution for a walk-in (
PosCustomerIdentityService) and the shared Counter Walk-in customer. - SKU lookup, sale search, receipt resend, till config and the returnable view.
Does Not Own
- Inventory movement (delegated to
InventoryReservationService). - Order creation and lifecycle (delegated to
OrderCreationService; the Order module owns every state afterconfirmed). - Payment gateway logic (a
payment_attemptrow is written directly, but the Payment module owns the table and its admin surface). - The return and refund state machines and the stock restore. The order module owns them (
OrderReturnService,OrderReturnInspectionService,OrderRefundSettlementService,InventoryWriteService); POS only composes their*InTxmethods. - Barcode search (does not exist —
producthassku, nobarcodecolumn). A scanner that emits the SKU usesGET /lookup/products/by-sku. - Receipt/invitation sending (delegated to the Notifications queue).
Source of Truth
| Concern | Source of Truth | Notes |
|---|---|---|
| Sale state | pos_sale row | Status + fulfilment + downstream keys, guarded by chk_pos_sale_status_completion |
| What was sold | pos_sale_item (draft) → checkout_session_item → order_item | Frozen at the till, copied not converted |
| Money taken | payment_attempt | Same shape as online payments; the sale number is in gateway_transaction_id |
| Order | order | The Order module owns it; POS references it |
| Audit | pos_sale_event | Append-only, same transaction as the change |
| Counter return idempotency | pos_counter_returns | Unique on (sale, key); survives Redis expiry |
| Counter Walk-in | customers row POS_COUNTER_WALK_IN_CUSTOMER_ID | Inserted by migration 0072; valid only while live, active, unbanned, no email, no phone |
3. Module Composition
| Module | Type | Path | Controllers | Providers | Exports | Responsibility |
|---|---|---|---|---|---|---|
PosModule | Aggregate | apps/api/src/modules/pos/pos.module.ts | None | — | PosAdminAggregateModule | Composes the admin leaves with shared services |
PosAdminAggregateModule | Aggregate | .../admin/pos-admin-aggregate.module.ts | None | — | Sale, Lookup, ManualOrder, Config, Return, SaleSupport leaves | No controllers of its own |
PosSaleAdminModule | Leaf | .../admin/sale/pos-sale-admin.module.ts | PosSaleAdminController | PosSaleAdminService | — | The till routes |
PosLookupAdminModule | Leaf | .../admin/lookup/pos-lookup-admin.module.ts | PosLookupAdminController | — | — | Customer, product and SKU lookup |
PosConfigAdminModule | Leaf | .../admin/config/pos-config-admin.module.ts | PosConfigAdminController | PosConfigAdminService | — | GET /config |
PosSaleSupportAdminModule | Leaf | .../admin/sale-support/pos-sale-support-admin.module.ts | PosSaleSupportAdminController | PosSaleSupportAdminService | — | Receipt resend, customer addresses, returnable |
PosReturnAdminModule | Leaf | .../admin/return/pos-return-admin.module.ts | PosReturnAdminController | PosReturnAdminService | — | Counter return. Imports PosSharedModule, RoleModule, IdempotencyModule |
PosSharedModule | Shared | .../pos-shared.module.ts | None | Includes PosCustomerIdentityService, PosCounterReturnService | Includes both | Every decision in the module |
PosWorkerModule | Worker | .../pos-worker.module.ts | None | Processor + handlers + scheduler | — | One @Processor on QueueName.POS |
4. File and Directory Map
apps/api/src/modules/pos/
pos.module.ts
pos-shared.module.ts
pos-worker.module.ts
admin/
pos-admin-aggregate.module.ts
sale/
pos-sale-admin.controller.ts
pos-sale-admin.module.ts
pos-sale-admin.service.ts
dto/ # request, response, list-query
lookup/
pos-lookup-admin.controller.ts
pos-lookup-admin.module.ts
dto/pos-lookup.dto.ts, pos-sku-lookup.dto.ts
sale-support/
pos-sale-support-admin.controller.ts, .service.ts, .module.ts
dto/pos-receipt-email-response.dto.ts, pos-returnable.dto.ts
config/
pos-config-admin.controller.ts, .service.ts, .module.ts
dto/pos-config-response.dto.ts
return/
pos-return-admin.controller.ts, .service.ts, .module.ts
dto/create-pos-counter-return.dto.ts, pos-counter-return-response.dto.ts
shared/
pos.constants.ts
pos-counter-return.service.ts
pos-counter-return.util.ts
pos-customer.service.ts
pos-customer-identity.service.ts
pos-idempotency-key.guard.ts
pos-lookup.service.ts
pos-mail-queue.service.ts
pos-sale-access.service.ts
pos-sale-completion.service.ts
pos-sale-draft.service.ts
pos-sale-event.service.ts
pos-sale-line.service.ts
pos-sale-number.service.ts
pos-sale-query.service.ts
pos-totals.util.ts
workers/
pos-draft-sweep.processor.ts
pos-email.processor.ts
pos-maintenance.scheduler.ts
pos-queue.processor.ts
emails/
pos-receipt.email.ts
pos-walk-in-invite.email.ts| File | Purpose | Key Exports | Notes |
|---|---|---|---|
pos.constants.ts | Fixed values | POS_SALE_NUMBER_PREFIX, POS_MAX_QUANTITY_PER_LINE (99), POS_DRAFT_ABANDON_HOURS (24), POS_INVITE_NEVER_EXPIRES_AT, POS_CACHE_DOMAIN (inventory) | The never-expiring invite is policy, documented as not-a-bug |
pos-customer.service.ts | Walk-in provisioning + token minting, Counter Walk-in checks | provisionWalkIn, issueInvite, assertCounterWalkInUsable, archiveWalkInDeliveryAddress | No password; createEmailVerification, never createPasswordReset (no OTP); nullable email means no account row |
pos-customer-identity.service.ts | Who owns an email or phone | resolve, withIdentityRaceRetry, toWalkInRefusal, isBanned, masks | Shared with manual orders; the banned rule is applied in the POS mapping only |
pos-counter-return.service.ts | Counter return and returnable view | createCounterReturn, getReturnable | One transaction under withSerializationRetry |
pos-counter-return.util.ts | Pure helpers and shapes for the return | resolveCounterRefundMethod, isReturnWindowClosed, counterLineKey, isCounterReturnKeyRace, COUNTER_RETURN_NOT_ALLOWED_COPY | Split out of the service by the size gate |
pos-idempotency-key.guard.ts | UUID check of Idempotency-Key | PosIdempotencyKeyGuard | Runs before the interceptor reserves the key; an absent key is left to the interceptor |
pos-lookup.service.ts | Bounded ILIKE searches + SKU scan | searchCustomers, searchProducts, findBySku | 2-char minimum; escapeLikePattern; active customers only; product search also matches variant SKU |
pos-mail-queue.service.ts | Outbox enqueues | queueReceipt, queueReceiptResend, queueWalkInInvite | Same transaction as the sale; dedupe on sale/customer id; a resend dedupes on <sale>:resend:<key> |
pos-sale-access.service.ts | Locks + totals | lockSale, lockDraft, loadLines, recomputeTotals | FOR UPDATE; totals recomputed, never incremental |
pos-sale-completion.service.ts | The one transaction | complete | Lock order sale → products asc → cart → session → payment → order |
pos-sale-draft.service.ts | Draft mutations | open, attachCustomer, createWalkInCustomer, setPaymentMethod, setFulfilment, cancel | Customer change resets to pickup; cancel reason mandatory; archives a Counter Walk-in's one-time address |
pos-sale-event.service.ts | Append-only audit | record | No update path anywhere |
pos-sale-line.service.ts | Lines on the draft | upsertLine, removeLine | PUT replaces the quantity; ON CONFLICT DO UPDATE |
pos-sale-number.service.ts | POS-2026-000042 | issue | Own sequence, DB clock in Asia/Kathmandu, gaps expected |
pos-sale-query.service.ts | Admin reads | findAll, findOne, findTimeline | Page + total in one transaction; offset pagination (10k-row cap noted) |
pos-totals.util.ts | Pure total math | computePosSaleTotals, computePosLineAmounts | Integer minor units; subtotal = Σ lineTotal, not netAmount |
pos-checkout-materializer.service.ts | Pipeline rows | resolveShipping, materialize | Cart born converted, session born completed, attempt born succeeded |
5. Data Model
5.1 Schema Source
packages/db/src/schema/pos/
index.ts
enums.ts
pos-sale.ts
pos-sale-item.ts
pos-sale-event.ts
pos-counter-return.ts
pos-counter-walk-in.tsAlso modified: sales_channel enum in packages/db/src/schema/checkout/enums.ts,
payment_method enum gains pos_cash/pos_card/pos_qr, order.channel and
checkout_session.channel columns (both default online). Migration 0054 adds whatsapp to
sales_channel and to inventory_source; 0055 adds pos_sale.channel. The whatsapp channel is
used by the manual-order routes (see Manual orders); the POS
routes themselves only ever handle channel = 'pos'.
5.2 Tables and Collections
pos_sale
| Column/Field | Type | Nullable | Default | Index/Constraint | Relation | Notes |
|---|---|---|---|---|---|---|
id | serial | No | generated | PK | N/A | Internal |
public_id | uuid | No | uuid7 | unique | N/A | External handle |
sale_number | varchar(32) | No | — | unique | N/A | POS-2026-000042; WA-2026-000001 for a WhatsApp sale |
channel | sales_channel enum | No | pos | chk_pos_sale_channel, chk_pos_sale_number_prefix | N/A | pos (the counter) or whatsapp; never online. Added by 0055 |
status | enum | No | draft | — | N/A | draft/picked_up/ordered/cancelled |
fulfilment | enum | No | none | — | N/A | pickup/delivery; unset is unrepresentable |
customer_id | uuid | No | — | index + FK RESTRICT | customers | Every sale belongs to an account |
customer_created | boolean | No | false | — | N/A | §48 Customer Type, stored not derived |
created_by_admin_id | uuid | No | — | index + FK RESTRICT | adminUsers | Sales-by-administrator must not drift |
cart_id | integer | Yes (draft) | NULL | partial unique | carts (RESTRICT) | Born converted |
checkout_session_id | integer | Yes (draft) | NULL | partial unique | checkoutSessions (RESTRICT) | Born completed |
payment_attempt_id | integer | Yes (draft) | NULL | partial unique | paymentAttempts (RESTRICT) | Born succeeded |
order_id | integer | Yes (draft) | NULL | partial unique | orders (RESTRICT) | Set at completion |
delivery_address_id | integer | Yes | NULL | index + FK RESTRICT | customerAddresses | NULL for pickup |
payment_method | enum | No | — | — | N/A | Counter: pos_cash/pos_card/pos_qr. WhatsApp: cod/pos_card/pos_qr. Never esewa, and cod never on a pos sale (see constraints) |
payment_reference | varchar(128) | Yes | NULL | — | N/A | Recorded, never validated; refused beside cash |
currency | varchar(3) | No | NPR | — | N/A | Uppercased, length 3 |
subtotal/discount_amount/shipping_amount/grand_total | bigint | No | 0 | — | N/A | Integer minor units |
total_quantity/line_count | integer | No | 0 | — | N/A | Derived |
correlation_id | uuid | No | uuid7 | — | N/A | Ties logs/events/outbox |
version | integer | No | 1 | — | N/A | Bumped on every change |
completed_at/cancelled_at | timestamp tz | Yes | NULL | — | N/A | Terminal stamps |
created_at/updated_at | timestamp tz | No | now | — | N/A | — |
Key constraints:
uq_pos_sale_{cart,checkout_session,payment_attempt,order}_id— partial on NOT NULL, so a replayed completion collides instead of double-charging.chk_pos_sale_status_completion— one exhaustive disjunction: a completed sale must hold every downstream key;picked_uponly withpickupandchannel = 'pos'(only the counter hands over at completion);orderedwithdelivery, or — new in0055— withpickupwhenchannel = 'whatsapp'(the goods wait for the order's own ready-for-pickup and collect steps; a counter pickup atorderedis still refused);cancelledhas no order.chk_pos_sale_channel—channelisposorwhatsapp(compared::text).chk_pos_sale_number_prefix—WA-…numbers belong towhatsappand to nothing else;posnumbers never startWA-.chk_pos_sale_payment_method_not_esewa—payment_method <> 'esewa'.chk_pos_sale_pos_not_cod—channel <> 'pos' OR payment_method <> 'cod'(0057). The POS request DTO already offers only the threepos_*methods; this is the database backstop, so a violation would surface as a bare23514. Enforced onpos_saleonly:orderandcheckout_sessionstay unconstrained.chk_pos_sale_fulfilment_address— pickup ⇒ no address and shipping 0; delivery ⇒ address present.chk_pos_sale_payment_reference_method— reference NULL or method ispos_card/pos_qr(compared::textbecause a new enum value cannot be used in the transaction that adds it).chk_pos_sale_grand_total_matches—grand_total = subtotal − discount + shipping, written as an equality.chk_pos_sale_completed_has_contents— a completed sale has lines; drafts may be empty.chk_pos_sale_currency_normalized,chk_pos_sale_number_not_blank,chk_pos_sale_version_positive,chk_pos_sale_money_non_negative,chk_pos_sale_discount_within_subtotal,chk_pos_sale_counts_non_negative.
pos_sale_item
| Column/Field | Type | Nullable | Default | Index/Constraint | Relation | Notes |
|---|---|---|---|---|---|---|
id / public_id | serial / uuid | No | uuid7 | PK / unique | N/A | — |
pos_sale_id | integer | No | — | FK CASCADE + index | posSales | Deleting a sale deletes its lines |
product_id | integer | No | — | FK RESTRICT + index | products | A counter line is money that changed hands |
product_public_id | uuid | No | — | — | N/A | Denormalised |
product_name | varchar(255) | No | — | — | N/A | Snapshot; survives rename/delist |
sku | varchar(64) | Yes | NULL | — | N/A | Snapshot |
unit_price/mrp/line_total/discount_amount/net_amount | bigint | No | — | — | N/A | Price snapshot, unlike the cart |
quantity | integer | No | — | — | N/A | 1–99 (chk_pos_sale_item_quantity_range) |
uq_pos_sale_item_pos_sale_id_product_id— one line per product; the upsert isON CONFLICT DO UPDATE.chk_pos_sale_item_line_total_matches(line_total = unit_price × quantity),chk_pos_sale_item_net_amount_matches(net_amount = line_total − discount),chk_pos_sale_item_discount_within_line,chk_pos_sale_item_price_not_above_mrp,chk_pos_sale_item_money_non_negative,chk_pos_sale_item_product_name_not_blank.
pos_sale_event
| Column/Field | Type | Nullable | Default | Index/Constraint | Relation | Notes |
|---|---|---|---|---|---|---|
id / public_id | serial / uuid | No | uuid7 | PK / unique | N/A | — |
pos_sale_id | integer | No | — | FK CASCADE + composite index | posSales | Timeline read |
event_type | enum | No | — | — | N/A | 10 values from created to cancelled |
from_status/to_status | enum | Yes | NULL | — | N/A | Both or neither |
actor_admin_id | uuid | Yes | NULL | FK SET NULL + composite index | adminUsers | Audit survives offboarding; differs from RESTRICT on the sale |
reason | text | Yes | NULL | — | N/A | Mandatory non-blank for cancelled |
metadata | jsonb | Yes | NULL | — | N/A | Product/quantity/old-new values; never the invite token |
correlation_id | uuid | No | — | — | N/A | — |
created_at | timestamp tz | No | now | — | N/A | No updated_at — append-only |
chk_pos_sale_event_transition_pair,chk_pos_sale_event_transition_moves,chk_pos_sale_event_cancel_reason(theIS NOT NULLarm is load-bearing — the original constraint passed on NULL reason, fixed by migration 0015),chk_pos_sale_event_reason_not_blank(~ '[^[:space:]]', notbtrim).
pos_counter_returns
One row per committed counter return. It is the durable idempotency record and links the sale to the order_return and order_refund the order services created. Source: packages/db/src/schema/pos/pos-counter-return.ts, migration 0071.
| Column/Field | Type | Nullable | Default | Index/Constraint | Relation | Notes |
|---|---|---|---|---|---|---|
id | serial | No | generated | PK | N/A | Internal only |
public_id | uuid | No | uuid7() | UNIQUE | N/A | Not exposed by any response; the API returns the order return's public id |
pos_sale_id | integer | No | — | FK RESTRICT; leads two indexes | pos_sale | — |
order_return_id | integer | No | — | FK RESTRICT; uq_pos_counter_returns_order_return_id UNIQUE | order_return | One counter-return row per return |
order_refund_id | integer | Yes | NULL | FK RESTRICT; idx_pos_counter_returns_order_refund_id | order_refund | NULL when nothing was refundable (inspection creates no refund) |
idempotency_key | uuid | No | — | uq_pos_counter_returns_sale_key UNIQUE with pos_sale_id | N/A | The client's Idempotency-Key |
request_hash | char(64) | No | — | — | N/A | SHA-256 of the canonical request (RequestHashUtil); a replay with a different hash is IDEMPOTENCY_KEY_CONFLICT |
created_by_admin_id | uuid | No | — | FK RESTRICT; idx_pos_counter_returns_created_by_admin_id | admin_users | The cashier |
created_at | timestamptz | No | now | idx_pos_counter_returns_sale_created_at (sale, created_at DESC) | N/A | — |
RESTRICT everywhere: deleting a sale, return, refund or admin must never silently drop the record that money left the till.
Other schema changes
order_refund_methodgainscard_reversalandqr_reversal(migration0070, appended withIF NOT EXISTS; there is noDROP VALUE, so the labels remain after a down migration). The application, not the type, restricts them tochannel = 'pos'orders.- Migration
0072inserts the shared Counter Walk-incustomersrow (nameCounter Walk-in, no email, no phone, active, not banned). Its id isPOS_COUNTER_WALK_IN_CUSTOMER_ID(01a2076e-fe59-73dc-9d64-ee3ce2edb086) exported from@nano-store/db;customershas nopublic_id, socustomers.idis the exposed id. PosReturnsis added to the permission catalog (permission-catalog.ts).
5.3 Relationship Diagram
5.4 Migrations 0054 to 0057 (the whatsapp channel)
drizzle-kit migrate applies every pending migration in one transaction. That shapes all four:
PostgreSQL refuses a freshly added enum label as an enum literal in the transaction that adds it
(55P04, "unsafe use of new value"), so every constraint after 0054 compares channel::text
rather than the enum literal.
| Migration | Up | Down |
|---|---|---|
0054_sales_channel_whatsapp | ALTER TYPE sales_channel ADD VALUE IF NOT EXISTS 'whatsapp' and the same on inventory_source. IF NOT EXISTS is a hand edit: the down is a no-op (PostgreSQL has no DROP VALUE), the down runner deletes the ledger row, and a plain ADD VALUE would then fail on re-apply with 42710 | No-op (SELECT 1); the labels stay, so up, down, up is a fixpoint |
0055_pos_sale_channel | SET LOCAL lock_timeout = '5s' first; creates whatsapp_sale_number_seq; adds channel sales_channel NOT NULL DEFAULT 'pos' (metadata only, every existing row is pos); adds chk_pos_sale_channel, chk_pos_sale_number_prefix (preceded by a guard that raises, naming the count, if any existing sale number already starts WA-) and chk_pos_sale_payment_method_not_esewa (fails with 23514, rolling back the deploy, if any pos_sale was ever recorded as esewa); rebuilds chk_pos_sale_status_completion | Refuses (Cannot revert 0055) while any pos_sale has a channel other than pos, because dropping the column would relabel WhatsApp sales as counter sales; otherwise drops the three CHECKs and the column, restores 0014's completion CHECK whole, and drops the sequence |
0056_pos_pickup_fulfilment_backfill | Data only. Sets fulfilment_type = 'pickup' (and updated_at = now(), version + 1) on the checkout session and order behind every counter pickup sale that was stored as delivery. A guard refuses, naming the counts, if any such row carries a shipping charge or a delivery address | No-op: the forward left no marker separating corrected rows from rows written correctly since |
0057_pos_sale_pos_not_cod | SET LOCAL lock_timeout = '5s'; a guard that raises, naming the count, if any pos_sale is pos with cod; chk_pos_sale_pos_not_cod | DROP CONSTRAINT IF EXISTS "chk_pos_sale_pos_not_cod"; cannot fail on real data |
The 0056 defect. PosCheckoutMaterializerService inserted the checkout session without
fulfilmentType, so the column default delivery applied to every counter sale and the order copied
it: a pickup pos_sale sat on a session and an order that both said delivery, and the pickup
routes then refused the order with ORDER_NOT_PICKUP. The materializer now writes
fulfilmentType: sale.fulfilment; 0056 corrects the rows already written. updated_at moves
because analytics re-projects a row only when updated_at advances. No order_event is written:
it is a correction of a mis-recorded field, not something that happened to the order.
Re-running the backfill. Until the API carrying the materializer fix is live on every instance,
an old one can still write delivery after 0056 ran. After the rollout, count again and re-run:
cd packages/db
pnpm exec tsx src/scripts/backfill-pos-pickup-fulfilment.ts --dry-run # count only
pnpm exec tsx src/scripts/backfill-pos-pickup-fulfilment.ts # count, fix, countThe script executes 0056's SQL file read from disk, so the two cannot drift. It is idempotent
(every UPDATE filters on fulfilment_type <> 'pickup'), runs in one transaction with
SET LOCAL lock_timeout = '5s' so it fails fast instead of queueing behind a long transaction on
live order rows, uses DIRECT_DATABASE_URL when set and DATABASE_URL otherwise, and exits
non-zero if rows remain afterwards (a sale may have completed during the run; run it again).
Deploy in a quiet window. Each ADD CONSTRAINT scans pos_sale under ACCESS EXCLUSIVE, and the
whole pending set — including 0056's row locks on order and checkout_session — commits as one
transaction. lock_timeout = '5s' makes a migration that cannot get a lock abort the entire batch
cleanly (nothing applied, ledger unchanged) rather than queue behind live traffic. If it times out,
re-run it; it is all-or-nothing. SET LOCAL lasts to the end of the migrate transaction, so the one in
0055 also covers 0056.
6. Services and Responsibilities
6.1 PosSaleAccessService
| Method | Called By | Reads | Writes | Side Effects | Errors |
|---|---|---|---|---|---|
lockSale | All mutations | pos_sale FOR UPDATE, filtered channel = 'pos' | — | — | 404 POS_SALE_NOT_FOUND (also for a WhatsApp sale) |
lockDraft | All draft mutations | pos_sale | — | — | 409 POS_SALE_ALREADY_COMPLETED / POS_SALE_NOT_DRAFT |
loadLines | completion, totals | pos_sale_item | — | — | — |
recomputeTotals | line mutations, fulfilment | lines | pos_sale totals | — | — |
FOR UPDATE rather than optimistic version: the caller is about to make several dependent
writes, and a version mismatch at the end would discard them all.
Channel isolation. lockSale is the chokepoint every POS mutation reaches, and it filters
channel = 'pos'; the list, count, detail and timeline reads in PosSaleQueryService do too, as do
the analytics projector for pos_sale and the orphan sweep's pos_sales target. A WhatsApp sale is
therefore invisible to every /api/admin/pos/... route. The manual-order service does not go through
lockSale: it inserts its sale in its own transaction and calls the ...Within cores
(openWithin, setFulfilmentWithin, upsertLineWithin, completeWithin), which take the caller's
executor.
6.2 PosSaleEventService
One method: record. Written in the SAME transaction as the change (16-observability-rules).
No update, no amend, no soft delete — a correction is a new row.
6.3 PosSaleNumberService
issue → POS-2026-000042 from pos_sale_number_seq (cache: 1), year from
timezone('Asia/Kathmandu', now()) in the DB. Its own sequence so till numbers and order
numbers never interleave. Gaps are expected and correct — a rolled-back sale consumed its
number.
issue(executor, channel = "pos") keeps one book per channel: pos draws POS-… from
pos_sale_number_seq; whatsapp draws WA-… from whatsapp_sale_number_seq. A WhatsApp sale never
consumes a till number, which would otherwise leave gaps in the till roll nobody at the counter can
explain. chk_pos_sale_number_prefix ties the prefix to the channel.
6.4 PosCustomerService
| Method | Reads | Writes | Notes |
|---|---|---|---|
provisionWalkIn | customers (email check) | customers, account | password: null; email_verified: false; same rows as registration, minus the password |
issueInvite | — | verification token | createEmailVerification (no OTP), expiresInMs = far-future sentinel; minted by the worker, never carried in outbox payload |
provisionWalkIn takes a nullable email: with no email it writes a customers row only (no account), and OTP login on the phone is the claim. assertCounterWalkInUsable(executor) returns the Counter Walk-in id only while that row is not deleted, active, not banned and has no email and no phone; otherwise it throws 503 POS_COUNTER_CUSTOMER_MISSING. archiveWalkInDeliveryAddress(executor, sale) soft-deletes (deleted_at) the sale's delivery address when the customer is the Counter Walk-in, and is a no-op otherwise.
The email check exists only to name the remedy; customers_email_unique enforces. It matches
the index exactly — no deleted_at filter, because the unique index is not partial.
6.4a PosCustomerIdentityService
resolve({ name, email?, phone?, detachPhone? }, tx) classifies the contact details into one of: provision (nobody owns them), exists (an attachable customer owns them; carries customerId, matchedOn, a masked preview and the name), conflict (the email and phone belong to different customers), closed (the owner is closed or deleted) and unverified (the owner is live but unverified). It is shared with the manual-order service, which maps each kind 1:1 to its existing codes; its behaviour is unchanged. withIdentityRaceRetry catches a 23505 on email or phone in a savepoint and re-resolves once; a second loss throws the caller-supplied error.
For POST /sales/{id}/customer, toWalkInRefusal maps the result: exists is 409 POS_CUSTOMER_CONTACT_EXISTS (details: { customerId, name, matchedOn }) unless the owner is banned; conflict is POS_CUSTOMER_CONTACT_CONFLICT; everything else (closed, unverified, banned, phone-only with a non-attachable phone) is POS_CUSTOMER_CONTACT_UNAVAILABLE. When the phone owner is closed or unverified and a free email was given, the account is created with phone: null and the response carries phoneDropped: true. This disclosure is for the till only; manual orders keep their non-disclosure rule.
6.5 PosLookupService
ILIKE %term% on name/email/phone (customers) and name/SKU (products), min 2 characters,
escapeLikePattern + normalizeSearchTerm, PaginationUtil offset. Customers restricted to
status = 'active' and not deleted; products to published, not deleted. Product search also matches product_variants.sku. Deliberately not
trigram: an operator wants the exact row, not the closest miss.
findBySku(sku) (N2) calls PosSaleLineService.resolveSellableBySku: an equality match on btrim(sku) over the variant table and the product table; two different products or two variant rows are 409 POS_SKU_AMBIGUOUS with details.candidates; a product-table hit resolves to the default variant; a miss retries case-insensitively and succeeds only for exactly one product and at most one variant row (several is 404 POS_SKU_NOT_FOUND, never a guess); sellability then goes through loadSellable unchanged.
6.6 PosSaleDraftService
| Method | Transaction | Behavior |
|---|---|---|
open | own | Inserts draft + pickup; customerId required; event created |
attachCustomer | own | Locks, validates customer, applies patch + CLEAR_DELIVERY_ON_CUSTOMER_CHANGE (fulfilment: pickup, address NULL, shipping 0), event customer_assigned |
createWalkInCustomer | own | Normalises the phone (normalizeToE164; 400 POS_WALK_IN_PHONE_INVALID), requires email or phone (400 POS_WALK_IN_CONTACT_REQUIRED), locks the draft, resolves identity, provisions the account, archives the previous one-time address, updates the sale (customerCreated: true), enqueues the invite only when an email is stored, event customer_created |
setPaymentMethod | own | Locks the draft, updates the tender, clears the payment reference for pos_cash, bumps version and updated_at. No timeline event (the event enum would need a migration); INFO log with the admin id |
setFulfilment | own | Refuses addressPublicId for the Counter Walk-in; resolves address.districtId (uuid) to the integer id (404 POS_DISTRICT_NOT_FOUND); normalises the recipient phone (400 POS_RECIPIENT_PHONE_INVALID); archives the previous one-time address; then pickup clears address + shipping, delivery resolves saved address (scoped to this customer) or inserts a new one (is_default: false); event fulfilment_set |
cancel | own | Locks, sets cancelled + cancelled_at, archives the one-time walk-in address, event cancelled with mandatory reason. Touches no stock |
6.7 PosSaleLineService
upsertLine: validates quantity (1–99), locks, loads sellable product (published, not deleted, price ≤ MRP), computes amounts,INSERT ... ON CONFLICT DO UPDATE, eventitem_added/item_quantity_changed, recomputes totals.removeLine: locks, hard deletes by(pos_sale_id, product_public_id)plus the optionalvariantPublicIdquery param, eventitem_removed, recomputes totals. OmittingvariantPublicIdworks only when the product is on the sale as one configuration; several is 409POS_LINE_VARIANT_REQUIRED. 404POS_LINE_NOT_FOUNDif absent.
6.8 PosSaleCompletionService
complete — one transaction:
lockDraft(first lock, the start of the global order).applyPaymentReference— trims, refuses besidepos_cash.assertCompletable— lines, customer, delivery address.assertPricesUnchanged— currentsellingPricevs frozenunitPrice; refuse loudly.reserveAll— ascending product id; insufficient stock translated toPOS_INSUFFICIENT_STOCK(narrowed on the code, never the class); nothing queried after a failed statement (25P02).resolveShipping+materialize— cart bornconverted, session borncompleted(channelandfulfilmentTypecopied from the sale —posfor a counter sale), frozencheckout_session_items,payment_attemptbornsucceededwithgateway_transaction_id = POS-{saleNumber}and a real random callback token hash.reservations.finalizeper line — holds become deductions.orders.createFromCheckout(..., { executor: tx, suppressOpeningEmail: pickup })— the order inside the sale's transaction.handover.handOverfor pickup — drives the order todelivered.finalise— statuspicked_up/ordered, all keys,version + 1, guardedWHERE status = 'draft'(replay →POS_SALE_ALREADY_COMPLETED).mail.queueReceipt— outbox row in the same transaction.- Events
payment_recorded+completed.
After commit: cache.triggerForWrite({ domain: "inventory", reason: "pos_sale_completed" }) —
never inside the transaction (a network call must not hold the locks).
completeWithin — the same body for two callers. Steps 3 to 12 live in
completeWithin(executor, draft, lines, opts), which runs inside a transaction the caller already
holds, takes the row and never locks it, and also accepts an optional paymentReference that it applies
by the same guarded update. complete is lockDraft → applyPaymentReference → loadLines →
completeWithin with handover: true, sendPosReceipt: true. The manual-order service calls it with
handover: false, sendPosReceipt: false (so a WhatsApp pickup finalises at ordered and is emailed its
opening confirmation, and no counter receipt is queued) and an optional customerSnapshot: { phone }
that the order uses in place of the customer row's phone. In the
materializer the session channel and fulfilmentType come from the sale, and
gateway_transaction_id is POS-{saleNumber} or WA-{saleNumber}; stock holds and movements use
CHANNEL_INVENTORY_SOURCE[channel] (online → online_store, pos → pos, whatsapp →
whatsapp).
6.9 PosCheckoutMaterializerService
Writes the rows the Order module needs: cart (born converted to dodge
uq_cart_customer_id_live), session (born completed to dodge
uq_checkout_session_customer_live; channel: "pos"; payment_started_at/completed_at
honest — the operator did take the money), lines frozen 1:1, and a settled payment_attempt
whose shape, terminal status and audit trail match an online one. chk_checkout_session_status_timestamps still applies in full.
6.10 PosSaleQueryService
findAll: offset pagination, filters (status, fulfilment, payment method, customer, administrator,from/to,search), page + total in ONE transaction,created_at DESC, id DESC. 09-pagination-rules: offset is fine here, cap at 10k/100k rows noted (~3 years at 100 sales/day).searchis anILIKE %term%onsale_numberOR anEXISTSover the linked order'sorder_number, escaped withescapeLikePattern(normalizeSearchTerm(term)); the count query uses the same filter.findOne: sale + lines + customer/admin names + order refs; 404POS_SALE_NOT_FOUND.findTimeline: events oldest first, actor name left-joined.
6.10a PosSaleSupportAdminService, PosConfigAdminService, PosReturnAdminService
| Service | Method | Called By | Reads | Writes | Side Effects | Errors |
|---|---|---|---|---|---|---|
PosSaleSupportAdminService | resendReceipt | POST /receipt-email | sale (locked), customers.email, outbox_events (last 24 h) | one outbox_events row | Outbox job pos.send_receipt with resendKey | POS_RECEIPT_NOT_AVAILABLE, POS_CUSTOMER_NO_EMAIL, POS_RECEIPT_RESEND_LIMIT |
PosSaleSupportAdminService | listCustomerAddresses | GET /customer/addresses | sale, active addresses | — | — | POS_SALE_NOT_DRAFT, POS_WALK_IN_NO_ADDRESS_BOOK |
PosSaleSupportAdminService | getReturnable | GET /returnable | delegates to PosCounterReturnService | — | — | POS_SALE_NOT_FOUND, POS_COUNTER_RETURN_NOT_ALLOWED |
PosConfigAdminService | getConfig | GET /config | Counter Walk-in row | — | — | POS_COUNTER_CUSTOMER_MISSING (503) |
PosReturnAdminService | create | POST /returns | via PosCounterReturnService | — | After a fresh commit: activity record pos.counter_return.created; the audit write is in a try/catch and a failure is logged | see §6.13 |
resendReceipt runs in one transaction: it locks the sale, checks the status (picked_up or ordered), checks the customer has an email, counts the sale's pos.send_receipt outbox rows whose dedupe_key is <sale>:resend:% in the last 24 hours (limit 3; the sale lock serialises the count), then calls queueReceiptResend. listCustomerAddresses calls AddressQueryService.list with status: "active" and no pagination, so archived addresses are excluded. PosConfigAdminService returns returnWindowDays from ORDER_RETURN_WINDOW_DAYS (7) and currency: "NPR".
6.11 PosMailQueueService
The mails are enqueued through the outbox in the sale's transaction: queueReceipt
(pos.sale_completed, dedupe on the sale id — a sale completes exactly once),
queueReceiptResend (pos.receipt_resend_requested, job pos.send_receipt, dedupe key
<salePublicId>:resend:<Idempotency-Key>, so each resend is a new row and a replayed key sends nothing) and
queueWalkInInvite (pos.walk_in_created, dedupe on the customer id). No token in the
payload. The resend payload carries resendKey, and the handler's notification jobId becomes
pos-receipt-<salePublicId>-<resendKey>; without it BullMQ silently dropped the second resend because
the id already existed.
The outbox dedupes the enqueue; the HANDLER needed keying too. Both handlers are
at-least-once, and their own queue.add into the notifications queue carried no jobId — so a
worker SIGKILLed after adding the email but before BullMQ acknowledged completion re-ran and
queued a second one. Both now pass a deterministic id (pos-receipt-<salePublicId>,
pos-walkin-invite-<customerId>), hyphen-separated because BullMQ rejects a custom id containing
:.
For the invite that was more than a duplicate email. The handler MINTS the set-password token
before enqueuing, and VerificationTokenService.createVerification clears any existing
verification for the same (user, purpose) first — so a replay minted a second token and
invalidated the one already in the customer's inbox.
The invite link is deliberately non-expiring (POS_INVITE_NEVER_EXPIRES_AT) because a walk-in
"may not open their email for weeks", which makes them very likely to open the older message, get
an invalid token, and have no password, no other route in, and no self-service way to request
another — precisely the stranding the non-expiry policy exists to prevent.
An operator deliberately re-inviting is a different action with its own outbox row, and that one should supersede the old token.
6.11a What a receipt line says
The line query reads variant_name and net_amount, not just product_name and line_total.
variant_name is frozen onto pos_sale_item at the sale (migration 0030) so a receipt can say
which configuration left the shop. Without it a sale holding the 256GB and the 512GB of one
phone printed the same product name on both lines at two different prices, and a support query
about "the wrong one" was unanswerable from the receipt. It is read from the frozen column rather
than joined from the live variant, because the variant may since have been renamed or withdrawn
and the receipt must say what was sold.
net_amount equals line_total today — no path sets a per-line discount — so this is not a
visible change. It is correct by construction if one is ever added, where line_total would
print the pre-discount line beside a post-discount total.
The meta string is built by buildLineMeta in common/email/email-components.ts, shared with
the order-confirmation email. Both surfaces had made the same omission independently, which is the
case for one function rather than a third copy — and the shape it produces
("256GB · Qty 1") is the one EmailLineItem's own doc comment had specified all along.
6.11b Receipt content
The emailed receipt (emails/pos-receipt.email.ts) has the subject Receipt for sale <saleNumber> and lists the sale number, order number, payment method, lines, subtotal, discount, shipping and total. It does not carry the "Estimate invoice" wording. The "Estimate invoice — non-taxable receipt" rule (no PAN/VAT bill format, no IRD numbering, the sale number as the document reference) is a product decision for the printed receipt, which the desktop till renders; the backend code in this module does not produce it. Not verified in the desktop client's code from this repository.
6.12 PosTotalsUtil
Pure functions: computePosSaleTotals (Σ lineTotal, discount, shipping; grandTotal = subtotal − discount + shipping) and computePosLineAmounts (lineTotal = unitPrice × quantity). Integer arithmetic only — no division, no rounding. The client never supplies a
total.
6.13 PosCounterReturnService
| Method | Called By | Reads | Writes | Side Effects | Errors |
|---|---|---|---|---|---|
createCounterReturn(req) | PosReturnAdminService.create | pos_sale (locked), pos_counter_returns, orders, order_items | order_return*, order_refund*, inventory (restock), pos_counter_returns | After commit, fresh returns only: triggerForWrite({ domain: "inventory", reason: "pos_counter_return" }) | POS_COUNTER_RETURN_NOT_ALLOWED (7 reasons), IDEMPOTENCY_KEY_CONFLICT, POS_SALE_NOT_FOUND |
getReturnable(salePublicId) | PosSaleSupportAdminService | pos_sale, orders, order_items, pos_counter_returns + joins | — | — | POS_SALE_NOT_FOUND, POS_COUNTER_RETURN_NOT_ALLOWED (not_completed) |
createInTx order of work, inside one db.transaction wrapped by withSerializationRetry (budget from DB_TX_RETRY_*; the function contains DB writes and outbox rows only, no queue call and no fetch):
| Step | Code Location | What Happens | Why It Happens | Failure/Edge Case |
|---|---|---|---|---|
| 1 | access.lockSale | FOR UPDATE on the sale | Serialises two tills; lock order is sale then order then return/refund | 404 POS_SALE_NOT_FOUND |
| 2 | replay check | Looks up (pos_sale_id, idempotency_key) in pos_counter_returns | Durable idempotency that does not depend on Redis | Same hash returns replayed: true with no writes; different hash is 409 IDEMPOTENCY_KEY_CONFLICT |
| 3 | completedOrderOf | The sale must be picked_up or ordered with an order | Draft and cancelled sales have nothing to return | not_completed |
| 4 | order status and window | returned is fully_returned; a status other than delivered or partially_returned is window_closed (for completed) or not_completed; a null window is not_completed; a closed window (returnWindowEndsAt <= now) is window_closed | Same comparison as OrderReturnService.assertEligible | 409 |
| 5 | line checks | Duplicate (product, variant) keys, a key not on the order, a quantity above deliveredQuantity - returnPending - returned | Server-side limits; the client cannot over-return | duplicate_line, line_not_in_sale, quantity_exceeds_returnable |
| 6 | resolveCounterRefundMethod | Uses the requested method when given, any of cash, card_reversal, qr_reversal on any tender; otherwise the default from the tender (pos_cash to cash, pos_card to card_reversal, pos_qr to qr_reversal) | The shop may refund by any method on any POS sale | None; the method is never refused here |
| 7 | order services | requestOnBehalfInTx, decideInTx (approve), receiveInTx, inspectInTx (every line accepted; restocks via InventoryWriteService.adjustStock) | Reuses the order module's rules and events instead of copying them | Composed ORDER_* codes are mapped to one POS_COUNTER_RETURN_NOT_ALLOWED reason |
| 8 | refund | If inspection created a refund: approveInTx with the method, then settleInTx with the reference | Cash has no terminal, so a missing reference becomes POS <saleNumber> RET <last 12 of return id> (no terminal ref) | approveInTx refuses reversals on a non-pos order (ORDER_REFUND_METHOD_NOT_ALLOWED) |
| 9 | insert | pos_counter_returns row | The unique (sale, key) index closes a race between two identical requests | A 23505 on that constraint aborts the transaction; retryOnceOnKeyRace re-runs it once and the replay check then finds the row |
Waivers, by product decision, for counter returns only: separation of duties (inspector differs from approver) is not applied because it is a permission-level rule and the composition here is the waiver; each composed step is still called with the same admin id (the order services log it, for example inspected by <adminId>). { counterReturn: true } suppresses RETURN_REQUESTED (and the live admin notification) and RETURN_DECIDED. REFUND_SETTLED is still sent.
The result is read back after commit (loadCounterReturns) for fresh returns and replays alike, so the two are identical by construction. getReturnable computes returnable = max(deliveredQuantity - returnPending - returned, 0) and unitNetMinor = floor(netAmount / quantity), a display estimate.
7. Runtime Flows
7.1 Completion — the one transaction
| Step | Code Path | Behavior | Failure Case |
|---|---|---|---|
| 1 | lockDraft | Serialises on the sale | 404/409 on missing/terminal |
| 2 | assertCompletable | Empty/uncustomered/addressless refused | 409 POS_SALE_EMPTY / POS_SALE_NO_CUSTOMER / POS_DELIVERY_ADDRESS_REQUIRED |
| 3 | assertPricesUnchanged | Frozen price vs live price | 409 POS_PRODUCT_PRICE_CHANGED — nothing charged |
| 4 | reserveAll | Stock held, ascending ids | 409 POS_INSUFFICIENT_STOCK — nothing charged |
| 5 | createFromCheckout | Order inside the tx | Rollback of the whole sale |
| 6 | handOver | Pickup → delivered via recompute | Rollback |
| 7 | finalise | Terminal status + keys | 409 POS_SALE_ALREADY_COMPLETED on replay |
7.2 The walk-in creation + invitation
The token is minted by the worker at send time — a raw non-expiring credential must never sit
in outbox_events.payload, whose dead rows are never auto-purged.
A phone-only walk-in has no account row and gets no invitation. The shared Counter Walk-in is not created by this flow; it already exists (migration 0072) and is the customerId a till passes to POST /sales when the buyer gives no contact.
7.2a The one-time walk-in address
For a sale whose customer is the Counter Walk-in, a delivery address typed into PATCH /fulfilment is inserted into customer_addresses under the Counter Walk-in's id and referenced by pos_sale.delivery_address_id. archiveWalkInDeliveryAddress soft-deletes it when: the customer changes (attach or walk-in create), the address is replaced or the fulfilment is set again, the sale is cancelled, the sweep cancels it, and the sale completes. At completion the order is created first and the archive runs after it, in the same transaction, so the order's shipping snapshot is already taken. The address is never listed (GET /customer/addresses answers 404 POS_WALK_IN_NO_ADDRESS_BOOK for this customer, and filters to status: "active" for others).
7.2b The counter return
7.3 The abandoned-draft sweep
Hourly cron (pos-draft-abandon-sweep, Asia/Kathmandu) enqueues pos.sweep_abandoned_drafts
directly — the documented outbox exemption for a cron with no accompanying write. The handler
claims up to 100 drafts (FOR UPDATE SKIP LOCKED, updated_at <= now() − 24h, oldest first)
and cancels each in its OWN transaction with a guarded WHERE status = 'draft' update — an
operator resuming the sale beats the sweep. Event reason: POS_DRAFT_ABANDONED_REASON. Each cancellation also archives a Counter Walk-in's one-time delivery address (§7.2a).
Stock. Drafts hold none: completion reserves and finalizes stock in its one transaction. Cancel and the sweep release nothing because nothing was reserved. The only POS path that adds stock back is a counter return (§6.13, via the inspection step).
8. Caching
| Cache Key Pattern | Builder | Value | TTL | Invalidation | Caller |
|---|---|---|---|---|---|
inventory:* (existing) | existing inventory keys | — | existing | triggerForWrite({ domain: "inventory" }) after a completed sale, and after a fresh counter return (reason: "pos_counter_return") | PosSaleCompletionService, PosCounterReturnService |
POS has no cache keys of its own. Its one cache interaction is clearing the inventory domain
after completion (stock moved), and it is deliberately product_review-style: the write-side
triggerForWrite runs AFTER commit, fire-and-forget by contract — a committed sale must never
5xx because a cache did not clear.
These two triggers are kept as a latency optimisation. Since the stock-cache-invalidation change, the inventory writer also records a storefront-stale outbox row in the same transaction, so a POS completion or counter return is cleared a second time through the inventory_storefront_cache queue after the outbox tick. The double clear is harmless. See Inventory Backend section 7.3.
9. BullMQ, Schedulers, and Async Work
| Queue | Job | Producer | Processor | Payload | Retry/Backoff | Idempotency |
|---|---|---|---|---|---|---|
QueueName.POS | pos.send_receipt | outbox (sale tx, or receipt-email resend) | PosReceiptHandler | { correlationId, posSalePublicId, resendKey? } | BullMQ policy; HttpException = not retried | outbox dedupe on sale id; a resend on <sale>:resend:<key>; notification jobId pos-receipt-<sale> or pos-receipt-<sale>-<resendKey> |
QueueName.POS | pos.send_walk_in_invite | outbox (sale tx) | PosWalkInInviteHandler | { correlationId, posSalePublicId, customerId } — no token | same | outbox dedupe on customer id |
QueueName.POS | pos.sweep_abandoned_drafts | cron (direct) | PosDraftSweepHandler | { correlationId, batchSize } | same | jobId per hour |
PosQueueProcessor is the ONE @Processor on the queue (concurrency: 3), dispatching via an
exhaustive Record<PosJob, handler> — a second decorated class would race and silently drop
jobs (it happened on QueueName.INVENTORY). HttpException with an errorCode is a
deterministic failure returned as { success: false, retryable: false, errorCode }; anything
else is rethrown for retry.
Receipt and invite handlers render the email, enqueue NotificationJob.SEND_EMAIL onto
QueueName.NOTIFICATIONS, and may return outcome: "skip" (customer deleted themselves, no
email on file) — expected, no remedy, never thrown.
That downstream enqueue carries its own deterministic jobId — pos-receipt-<salePublicId> and
pos-walkin-invite-<customerId>. The outbox dedupes the POS job; nothing deduped the notification
job it produced, so a handler that died between the add and BullMQ's completion ack re-ran and
queued a second email. Hyphens, not colons: BullMQ builds its keys as bull:<queue>:<jobId> and
rejects a custom id containing : — the failure mode that once stopped the newsletter sweep from
ever running (see pnpm rules:job-ids, which now catches it statically).
9.1 The cron entry point catches its own enqueue
PosMaintenanceScheduler wraps posQueue.add in a try/catch that logs and returns.
This is the one place in the module where swallowing is the correct behaviour and the reason is
specific to @Cron: an exception escaping a scheduled handler propagates into the scheduler
itself, and the job stops firing. The sweep would then not merely miss the tick that failed — it
would never run again, with abandoned drafts holding their stock reservations indefinitely and no
error after the first one.
A caught enqueue failure is invisible to every gate. pnpm check-types, pnpm build, pnpm test
and pnpm rules all observe an exit code or an assertion, and none of them can see a catch that
behaved as designed. The only channel this failure has is the log line, which is why the sweep's
ERROR must be read as a finding and not as noise.
10. Realtime and Events
| Event | Producer | Room/Target | Payload | Consumer | Reliability Notes |
|---|---|---|---|---|---|
pos.sale_completed (outbox) | PosMailQueueService | QueueName.POS | { correlationId, posSalePublicId } | PosReceiptHandler → NOTIFICATIONS | Row in the sale's transaction |
pos.walk_in_created (outbox) | PosMailQueueService | QueueName.POS | { correlationId, posSalePublicId, customerId } | PosWalkInInviteHandler → NOTIFICATIONS | Deduped on customer |
pos.receipt_resend_requested (outbox) | PosMailQueueService.queueReceiptResend | QueueName.POS | { correlationId, posSalePublicId, resendKey } | PosReceiptHandler → NOTIFICATIONS | Row in the resend transaction; capped at 3 per sale per 24 h |
pos_sale_event rows | every mutation service | pos_sale_event table | type + statuses + actor + metadata | timeline endpoint, audits | Same transaction as the change |
No WebSocket/realtime surface exists in this module.
11. Security, Auth, and Abuse Controls
- Guards:
JwtAuthGuard+RoleGuardon both controllers;IpThrottlerGuardper route. - Permissions:
Pos_CREATE/Pos_READ/Pos_UPDATE/Pos_DELETE, from thePospermission module — spell itPos, neverPOS. The counter return route requiresPos_UPDATEandPosReturns_CREATEtogether (RoleGuardusesevery);PosReturnsis its own module so a cashier can refund a counter sale without authority over online returns and refunds. Runpermissions:syncso the rows exist.Pos_READalso exposes customer lookup, so it is grantable separately fromUsers_READ. - Identity:
@CurrentUser() user.idis the operator; every mutation records them on the event. The sweep recordsactor_admin_id: null. - Rate limits (all keyed on the user because every till in a shop shares one IP; values from
ip-throttler.config.ts):ADMIN_POS_WRITE180/min (every draft mutation — 10/minADMIN_WRITEwould throttle a 15-item basket mid-sale),ADMIN_POS_COMPLETE30/min,ADMIN_POS_READ120/min (sales list, customer addresses, returnable, config),ADMIN_POS_SEARCH120/min (customer and product lookup, re-keyed fromPUBLIC_SEARCH),ADMIN_POS_SCAN300/min (SKU lookup),ADMIN_POS_RECEIPT10/min andADMIN_POS_RETURN20/min. Sale detail and timeline still useADMIN_READ(30/min). - Idempotency:
receipt-emailandreturnsrequire anIdempotency-KeyUUID.PosIdempotencyKeyGuardrejects a malformed key (400POS_IDEMPOTENCY_KEY_INVALID) beforeIdempotencyInterceptorreserves it in Redis; an absent key is answered by the interceptor (IDEMPOTENCY_KEY_REQUIRED). The return additionally has the durablepos_counter_returnsrecord. - Counter Walk-in integrity: the shared row is trusted only while live, active, unbanned and without email or phone; otherwise config and delivery for it answer 503
POS_COUNTER_CUSTOMER_MISSING, so a sale cannot attach to a row that someone altered to carry a person's contact details. - Identity disclosure:
POS_CUSTOMER_CONTACT_EXISTSreturns onlycustomerId,nameandmatchedOn.phoneDroppeddiscloses that a phone could not be saved; this is accepted for the till only. - PII: customer lookup is bounded — 2-char minimum, paginated, never an unbounded list; returns no addresses or history; never the invite token.
- Ownership-scoped reads: a saved address is checked
WHERE customer_id = sale.customer_idin the query — another customer's address returns 404, never 403. - IDOR/leak hygiene:
ParseUUIDPipeon every id (its absence caused 500s in Reviews); responses expose onlypublic_ids, never integer PKs; a malformed id is a clean 400. - Fail-closed: the transaction aborts on any guard;
finaliseis guarded onstatus = 'draft'; a completed sale cannot be re-priced or re-charged. - Audit: every mutation writes
pos_sale_eventin the same transaction; the event table is append-only with noupdated_at.
13. Error Handling
| Error Code | HTTP Status | Thrown By | Condition | Client Action |
|---|---|---|---|---|
POS_SALE_NOT_FOUND | 404 | access/query/email handlers | Sale id does not resolve | Return to the sales list |
POS_SALE_NOT_DRAFT | 409 | lockDraft, applyToDraft | Cancelled (or otherwise not draft) | Start a new sale |
POS_SALE_ALREADY_COMPLETED | 409 | lockDraft, finalise | Money already taken | Do not retry — show the order number |
POS_SALE_EMPTY | 409 | assertCompletable | No lines | Block complete until a line exists |
POS_SALE_NO_CUSTOMER | 409 / 404 | assertCompletable / assertCustomerExists | No customer attached / customer missing | Send the operator to lookup |
POS_DELIVERY_ADDRESS_REQUIRED | 409 | draft + completion | Delivery without an address, or both address forms | Open the address form |
POS_ADDRESS_NOT_FOUND | 404 | draft / completion | Address not this customer's / store district missing | Re-fetch addresses / fix POS_STORE_DISTRICT_ID |
POS_PRODUCT_NOT_SELLABLE | 404 / 409 | line + completion | Unpublished, deleted or mispriced | Remove the line, name the product |
POS_PRODUCT_PRICE_CHANGED | 409 | assertPricesUnchanged | Price moved mid-sale | Tell the operator; remove and re-add |
POS_INSUFFICIENT_STOCK | 409 | reserveAll | Someone else took the last one | Show remaining; reduce quantity |
POS_PAYMENT_REFERENCE_NOT_ALLOWED | 409 | applyPaymentReference | Reference sent with cash | Clear the field or change method |
POS_CUSTOMER_EMAIL_TAKEN | 409 | PosCustomerService | Email already has an account (incl. closed). No longer thrown by POST /customer, which uses the three POS_CUSTOMER_CONTACT_* codes | n/a for the till walk-in |
POS_WALK_IN_CONTACT_REQUIRED | 400 | createWalkInCustomer | Neither email nor phone | Ask for one |
POS_WALK_IN_PHONE_INVALID | 400 | createWalkInCustomer | Phone cannot be normalised to E.164 | Fix the number |
POS_RECIPIENT_PHONE_INVALID | 400 | setFulfilment | Recipient phone fails normalizeToE164 | Fix the number |
POS_CUSTOMER_CONTACT_EXISTS | 409 | toWalkInRefusal | Contact owned by an attachable customer; details { customerId, name, matchedOn } | Attach that customer |
POS_CUSTOMER_CONTACT_CONFLICT | 409 | toWalkInRefusal | Email and phone belong to two customers | Correct one, or search |
POS_CUSTOMER_CONTACT_UNAVAILABLE | 409 | toWalkInRefusal, race retry | Owner closed, deleted, banned or unverified; phone-only on a non-attachable phone; second race loss | Use other contact details |
POS_SKU_NOT_FOUND | 404 | resolveSellableBySku | No match, or several case-insensitive matches | Re-scan or search by name |
POS_SKU_AMBIGUOUS | 409 | pickSkuCandidate | Exact SKU on two products or two variant rows; details.candidates | Pick one by hand |
POS_VARIANT_NOT_SELLABLE | 404 | loadSellable | The configuration is not sellable | Choose another |
POS_DISTRICT_NOT_FOUND | 404 | setFulfilment | districtId matches no district | Re-pick the district |
POS_WALK_IN_SAVED_ADDRESS_NOT_ALLOWED | 409 | setFulfilment | addressPublicId with the Counter Walk-in | Type the address |
POS_WALK_IN_NO_ADDRESS_BOOK | 404 | listCustomerAddresses | Customer is the Counter Walk-in | Type the address |
POS_COUNTER_CUSTOMER_MISSING | 503 | assertCounterWalkInUsable | Counter Walk-in row missing or altered | Restore the row (an operations fix) |
POS_RECEIPT_NOT_AVAILABLE | 409 | resendReceipt | Sale is not picked_up or ordered | Complete the sale first |
POS_CUSTOMER_NO_EMAIL | 409 | resendReceipt | Customer has no email | Offer a printout |
POS_RECEIPT_RESEND_LIMIT | 409 | resendReceipt | 3 resends in 24 h | Wait |
POS_IDEMPOTENCY_KEY_INVALID | 400 | PosIdempotencyKeyGuard | Header is not a UUID | Send a UUID |
POS_COUNTER_RETURN_NOT_ALLOWED | 409 | PosCounterReturnService | details.reason is one of not_completed, window_closed, fully_returned, line_not_in_sale, quantity_exceeds_returnable, duplicate_line | Branch on the reason (see the API reference) |
IDEMPOTENCY_KEY_CONFLICT | 409 | createInTx | Same key, different body | Generate a new key for a new return |
ORDER_REFUND_METHOD_NOT_ALLOWED | 409 | OrderRefundSettlementService.approveInTx | Card or QR reversal on a non-pos order | Pick another method (not reachable from the till) |
POS_LINE_NOT_FOUND | 404 | removeLine | Removing a line that is not there | Re-fetch the sale |
POS_QUANTITY_OUT_OF_RANGE | 400 | assertQuantity | Not a whole number in 1–99 | Clamp in the UI |
POS_PRODUCT_PRICE_CHANGED and POS_INSUFFICIENT_STOCK mean nothing was charged and nothing
was reserved — the whole completion rolled back, the sale is still a live draft.
14. Observability
| Signal | Location | Purpose |
|---|---|---|
| Log | Logger in completion, sweep, queue processor, customer service | [pos] ... state-change and failure visibility |
| Audit | pos_sale_event table | §42 timeline; append-only, same-tx |
| Trace | correlation_id on sale, events, outbox payloads, payment attempt | One sale across every log line |
| Queue visibility | BullMQ job.returnvalue | Deterministic failures recorded as { success: false, retryable: false, errorCode } |
15. Testing and Validation
| Test Type | Files | Coverage |
|---|---|---|
| Unit | pos-totals.util.spec.ts | Pure total/line arithmetic |
| Integration | pos-sale.int.spec.ts | Draft mutations, completion, walk-in, error branches |
| Integration | shared/pos-customer-identity.int.spec.ts, shared/pos-sku-lookup.int.spec.ts | Identity resolution; SKU lookup rules |
| Integration | shared/pos-counter-return.int.spec.ts, order/shared/order-refund-method-guard.int.spec.ts | The counter return transaction, replay, refund method guard |
| Unit | shared/pos-counter-return.service.spec.ts, shared/pos-idempotency-key.guard.spec.ts | Pure return helpers; key guard |
| HTTP integration | admin/sale/pos-sale-*.http.int.spec.ts, admin/sale-support/pos-sale-support.http.int.spec.ts, harness shared/testing/pos-admin-http.test-fixture.ts | Route-level behavior through the real guards, pipes and filters. These files were being written while this page was updated; check their current state and results before relying on them |
| Constraint probe | .omc/plans/POS/probe-constraints.mjs | CHECK constraints both directions against real PostgreSQL (97/0) |
| Live HTTP | .omc/plans/POS/checks-pos.sh | 24/0 against a booted API |
Run one integration spec with pnpm --filter api test:int --testPathPatterns <name>.
Validation: pnpm check-types · pnpm check (Biome) · pnpm build · pnpm test (serial,
maxWorkers: 1) · pnpm rules — all passed in the feature's verification run.
16. Mandatory Backend Deep-Dive Pack
16.1 Submodule Coverage Matrix
| Unit | Type | Owns | Depends On | Called By | Calls | State Touched | Failure Modes |
|---|---|---|---|---|---|---|---|
PosSaleAdminService | service | orchestration + DTO mapping | draft, line, completion, query | controller | 4 shared services | — | Mapping misses |
PosSaleAccessService | service | locks + totals | DB | all mutators | — | pos_sale, lines | 404/409 codes |
PosSaleEventService | service | audit rows | DB | every mutation | insert | pos_sale_event | — |
PosSaleNumberService | service | sale numbers | DB sequence | draft | nextval | sequence | missing sequence |
PosCustomerService | service | walk-in accounts + tokens | VerificationTokenService | draft, worker | inserts | customers, account, verification | 409 email taken |
PosLookupService | service | bounded search | DB | lookup controller | select | — | 400 short term |
PosSaleDraftService | service | draft lifecycle | access, events, numbers, customer, mail | admin service | 5 services | pos_sale, addresses, outbox | 409/404 set |
PosSaleLineService | service | draft lines | access, events, totals | admin service | 3 services | pos_sale_item, totals | 400/404/409 |
PosSaleCompletionService | service | the one transaction | access, events, materializer, reservations, orders, handover, mail, cache | admin service | 8 collaborators | 7 tables + outbox | 409 set; rollback |
PosCheckoutMaterializerService | service | pipeline rows | config, payment events | completion | 3 inserts + event | cart, session, items, attempt | missing row errors |
PosSaleQueryService | service | admin reads | DB | admin service | selects | — | 404 |
PosMailQueueService | service | outbox rows | outbox | draft, completion | enqueue | outbox_events | — |
PosTotalsUtil | util | pure math | none | line, access | — | — | — |
PosCustomerIdentityService | service | contact ownership resolution | DB | draft, manual-order | selects, savepoint | customers | 409 contact codes |
PosCounterReturnService | service | the counter return transaction, returnable view | access, order return/inspection/settlement services, cache, config | return admin service, support service | 3 order services | return, refund, stock, pos_counter_returns | POS_COUNTER_RETURN_NOT_ALLOWED, replay conflict |
PosSaleSupportAdminService | service | receipt resend, addresses, returnable | access, mail, queries, address query, counter return | support controller | outbox | outbox_events | 409 receipt codes |
PosConfigAdminService | service | till config | customer service | config controller | one select | — | 503 |
PosReturnAdminService | service | return entry point and audit | counter return, activity, sale admin | return controller | activity record | Mongo activity | audit failure logged |
PosIdempotencyKeyGuard | guard | UUID check of the key | — | N5, N7 routes | — | — | 400 |
PosQueueProcessor | worker | dispatch | 3 handlers | BullMQ | handler record | jobs | deterministic vs retryable |
PosReceiptHandler | handler | receipt email | DB, bull, notifications | processor | enqueue | outbox-consumed | skip outcomes |
PosWalkInInviteHandler | handler | invite email | DB, bull, customer, config | processor | mint + enqueue | verification | skip outcomes |
PosDraftSweepHandler | handler | abandon sweep | DB, events | processor | cancel | pos_sale, events | per-row try/catch |
PosMaintenanceScheduler | scheduler | cron trigger | queue | cron | enqueue | jobs | batch-cap warning |
16.2 UML and Architecture Diagram Pack
- Component diagram: §3 composition graph.
- ER diagram: §5.3.
- Sequence diagrams: §7.1 completion, §7.2 walk-in invite.
- Activity diagram: §7.3 sweep + feature §6.1 till flow.
- State diagram: feature §7 sale lifecycle.
- Deployment/runtime diagram: §9 queue topology.
16.3 Code Flow Narrative
The completion method (PosSaleCompletionService.complete) is the module's critical path and
its full 15-step narrative is in §7.1. Walk-in creation in §7.2. The remaining mutation
methods share one shape: db.transaction → lockDraft → (validate/load) → write → event → recomputeTotals → commit, with applyToDraft guarding every UPDATE on status = 'draft'.
16.4 Data Layer Deep Dive
Field-level detail for all three tables is in §5.2. Index rationale:
| Index/Constraint | Columns | Type | Query/Invariant Supported | Tradeoff |
|---|---|---|---|---|
uq_pos_sale_{cart,session,payment,order}_id | each FK | partial unique | Replay-safe completion; one downstream row per sale | NULLs in draft rows (by design) |
idx_pos_sale_status_created_at | status, created_at | btree | §51 list default order + date filter | write overhead |
idx_pos_sale_payment_method_created_at | method, created_at | btree | §54 reconciliation by tender | write overhead |
idx_pos_sale_event_pos_sale_id_created_at | sale, created_at | btree | timeline read | write overhead |
idx_pos_sale_event_actor_admin_id_created_at | actor, created_at | btree | per-admin audit | write overhead |
uq_pos_sale_item_pos_sale_id_product_id | sale, product | unique | one line per product; upsert target | — |
| every FK index | FK column | btree | FK checks / join paths | — |
16.5 Business Logic and Invariant Catalog
| Invariant | Enforced By | Why It Exists | Failure Error | Tests |
|---|---|---|---|---|
| A completed sale holds every downstream key | chk_pos_sale_status_completion | No paid sale without an order | 23514 (probe-verified) | probe |
| Terminal status matches fulfilment | same | No delivery-ordered pickup | 23514 | probe |
| Pickup: no address, no shipping; delivery: address | chk_pos_sale_fulfilment_address | No money for a service not rendered | 23514 | probe |
| Reference only beside card/QR | DTO + chk_pos_sale_payment_reference_method | Cash has nothing to reference | 409 / 23514 | probe |
| Total follows from parts | chk_pos_sale_grand_total_matches | Unforgeable till total | 23514 | probe |
| Line amounts follow from price × qty | 3 line checks | Operator cannot mistype a price | 23514 | probe |
| One line per product | unique index + ON CONFLICT | Scanning twice = quantity, not duplicate | — | int spec |
| Cancellation carries a non-blank reason | DTO + chk_pos_sale_event_cancel_reason | Audit answers why | 400 / 23514 | probe |
| Walk-in account has no password | PosCustomerService | Credentials are the customer's alone | — | int spec |
| Price quoted is the price charged | assertPricesUnchanged | No silent re-pricing | POS_PRODUCT_PRICE_CHANGED | int spec |
| Reserves only at completion | sweep + constants | Drafts hold no stock | — | int spec |
| A counter return is atomic and idempotent | createInTx + uq_pos_counter_returns_sale_key | No return without its refund and restock, and no double refund on a retry | replay returns the stored result; different body is 409 | pos-counter-return.int.spec.ts |
Only delivered or partially_returned orders inside the 7-day window can be returned | createInTx | Goods must have left and the window must be open | POS_COUNTER_RETURN_NOT_ALLOWED | same |
Any refund method on any POS sale; card and QR reversals only on a pos order | resolveCounterRefundMethod, approveInTx | A reversal reverses a counter-terminal payment, which only a counter order has | ORDER_REFUND_METHOD_NOT_ALLOWED (non-pos order) | order-refund-method-guard.int.spec.ts |
| A receipt is resent at most 3 times per sale per 24 h | resendReceipt under the sale lock | Cost and abuse of email sends | POS_RECEIPT_RESEND_LIMIT | not verified here |
| A Counter Walk-in's typed address is never listed and is archived when the sale ends | archiveWalkInDeliveryAddress | One shared account must not accumulate other people's addresses | POS_WALK_IN_* codes | not verified here |
16.6 Tradeoffs, Alternatives, and ADR Notes
| Decision | Context | Chosen Option | Alternatives | Why Chosen | Tradeoffs | Revisit Trigger |
|---|---|---|---|---|---|---|
| Reuse the online pipeline | Counter sale = same commercial record | Materialise cart/session/attempt, call createFromCheckout | A parallel counter ledger | One order domain, one return/refund path | Materializer complexity; channel label | Order module diverges |
| Nullable+unique downstream keys | Draft has no order yet | Partial unique indexes + status CHECK | Placeholder rows | No phantom sessions/payments; replay-safe | NULLs to handle in queries | — |
| Cart/session born terminal | Live-cart uniques collide with a phone cart | Insert converted/completed | Narrow the partial index predicates | Predicate inference is exact (42P10 otherwise) | Unusual shape, documented | Cart module changes predicate |
No awaiting_payment | No gateway round trip at a till | 4 states only | Model the wait | A state no path can produce | — | — |
| Price freeze + loud refusal | Quoted price is agreed price | Refuse on drift | Charge old/new silently | The two people are both present | Mid-sale 409s | — |
| Never-expiring single-use invite | Walk-in may not read email for weeks | Far-future sentinel + consumed_at | 24h TTL | Owner policy; no support dead-end | Long-lived if stolen | Policy change → config |
| No OTP on the invite | 6-digit code that never expires is brute-forcible | createEmailVerification only | createPasswordReset | Search space | — | — |
| Token minted at send time | Outbox dead rows are never purged | Mint in the worker | Carry token in payload | A credential must not sit in an operator-facing table | Retry replaces token (fine) | — |
pos_sale_event.actor_admin_id SET NULL | Offboarding must not deadlock | SET NULL + attribution CHECK | RESTRICT like the sale | Trail survives; retention ≠ deadlock | Lost attribution | — |
| Own sequence for sale numbers | Two documents counted by two people | pos_sale_number_seq | Shared order_number_seq | Contiguous till roll | Gaps (expected) | — |
| Lookup is ILIKE, not trigram | Operator wants the exact row | ILIKE + escaping | Trigram similarity | Fuzzy match could sell the wrong SKU | >10k rows needs prefix index | Catalogue grows |
| Compose the order services for a counter return | A return, refund and restock must be one unit | Call *InTx methods of the order module in one transaction | A parallel POS return ledger | One return and refund state machine; reuse of restock | Waived separation of duties; a coupling to order internals | Order module changes its InTx signatures |
| Durable idempotency row | Redis keys expire; a replay after expiry must not refund twice | pos_counter_returns unique on (sale, key) | Redis only | The money record is the proof | One more table | — |
| Shared Counter Walk-in customer | A buyer who gives no contact still needs an account | One migrated row with no contact details | A customer per sale | No junk accounts; no PII | Delivery addresses are one-time and archived | Owner wants per-buyer records |
| Offset pagination | Till list is small for years | PaginationUtil offset | Keyset | Simplicity | 10k/100k-row cap | ~3 years at 100 sales/day |
| Cache invalidation after commit | Network call in a tx is forbidden | triggerForWrite post-commit | Inside the tx | Must not hold locks for an HTTP timeout | Brief staleness | — |
16.7 Operational Runbook
| Operation | How to Inspect | Healthy State | Failure Signal | Recovery |
|---|---|---|---|---|
| Queue | Bull Board / logs [start]/[success]/[failure]/[skip] | Jobs completing; skips are expected and logged | errorCode returns or rethrows | Retry via BullMQ for transient; deterministic failures need a code fix |
| Sweep | Logs examined N, cancelled M, failed K | M > 0 with due drafts | Batch-cap warning (filled its batch) | Next hourly tick picks up the rest |
| DB | pos_sale / pos_sale_event queries | Constraints satisfied; no 23514 in API logs | Deadlock 40P01 (rare) | Lock order is the mitigation; retry |
| Cache | inventory domain invalidation | Post-completion clear fires | No clear (silent) | triggerForWrite is fire-and-forget; re-trigger |
| Counter returns | pos_counter_returns joined to order_return and order_refund | One row per return, refund settled | A refund that is not settled (the service throws [pos] counter refund ... is not settled, a 500) | Investigate the order refund rows; the transaction is atomic so this indicates a code defect |
| Counter Walk-in | GET /api/admin/pos/config | 200 with the id | 503 POS_COUNTER_CUSTOMER_MISSING | Restore the row: live, active, not banned, email and phone NULL |
| Receipt resend | outbox_events where dedupe_key like '<sale>:resend:%' | Rows are dispatched to the queue | Rows that stay undispatched or dead | Replay from the outbox |
| Timeline | GET /sales/{id}/timeline | Events match the sale's history | Missing events | Events are same-tx; a gap means a bug |
16.8 Backend Risk Register
| Risk | Area | Impact | Current Mitigation | Remaining Gap |
|---|---|---|---|---|
| Two tills complete one sale | completion | Double charge | lockDraft + unique keys + guarded finalise | — |
| Counter and online checkout deadlock | completion | 40P01 | Ascending product lock order matching checkout | Distributed tx isolation not tested at load |
| Replayed completion | completion | Second order | Four partial unique indexes + WHERE status='draft' | — |
| Email outage | async | No receipt/invite | Outbox durability; queue retry | Provider blackhole (job retries) |
| Price drift | completion | Wrong price charged | Loud refusal at the till | None (by design) |
| Offboarded operator | reporting | Unattributed sales | RESTRICT FK on the sale; SET NULL on events | Sale blocks account removal |
| Two tills return the same sale | counter return | Double refund | Sale lock + unique (sale, key) + serialization retry | — |
| Tampered Counter Walk-in row | identity | A sale carries a person's contact details | assertCounterWalkInUsable returns 503 | Not a database constraint |
| Receipt resend abuse | async | Email spam | 3 per 24 h per sale, ADMIN_POS_RECEIPT | Cap is counted from outbox rows |
| Waived separation of duties | counter return | One cashier approves their own refund | Permission PosReturns_CREATE + every step called with the same admin id | By decision, no second approver |
| Catalogue growth | lookup | Slow fuzzy search | ILIKE + bounded pagination | Prefix index when >10k rows |
17. Zero-Omission Backend Checklist
- Every file in the module directory is represented or explicitly marked non-runtime (§4, §16.1).
- Every controller, service, provider, processor, scheduler, helper, mapper, DTO, enum, and schema is documented.
- Every method with business behavior has a code-flow narrative (§6, §7, §16.3).
- Every table/cache object/job payload has field-level detail (§5.2, §9).
- Every index, constraint, relation, and delete behavior has rationale (§5.2, §16.4).
- Every lifecycle/status transition has a state diagram and transition table (feature §7).
- Every read/write/action/job flow has sequence and activity diagrams (§7, §9).
- Every business invariant is cataloged (§16.5).
- Every cache key, invalidation path, queue job, realtime event, and external call is documented (§8, §9, §10).
- Every architectural tradeoff is documented with alternatives and revisit triggers (§16.6).
- Every operational failure mode has a runbook entry (§16.7).
18. Backend Completion Checklist
- Module boundaries are documented (§2).
- Every controller, service, DTO, schema file, job, cache key, and event is covered (§3–§11).
- Every database table has a field table and relationship diagram (§5).
- Every runtime flow has a diagram and branch notes (§7).
- API and features/flows docs are linked (See Also).
- No claim is made without a source file or documented source reference.
19. Serial Numbers
Per-unit serials are recorded into order_item_serial (schema owner packages/db/src/schema/order/order-item-serial.ts, migration 0073_order_item_serial_release). POS owns no new table.
| Unit | Path | Role |
|---|---|---|
order-item-serial.util.ts | apps/api/src/modules/order/shared/ | The one place every write to order_item_serial lives: normalizeSerialNumbers, assertSerialsFit, assertSerialsAvailable, insertOrderItemSerials, releaseSerialsOfShipment, releaseSerialsOfOrderItem, loadOrderSerials. Plain functions taking the caller's executor. |
pos-sale-serial.util.ts | apps/api/src/modules/pos/shared/ | resolvePosLineSerials: normalise, line lookup, hand-over rule, count and duplicate check, in that order. |
pos-counter-return-serial.util.ts | apps/api/src/modules/pos/shared/ | releaseCounterReturnSerials: validates picks, releases as counter_return. DB writes only, so it is safe under withSerializationRetry. |
PosSaleCompletionService.completeWithin | pos/shared/pos-sale-completion.service.ts | Resolves serials and runs assertSerialsAvailable before prices are checked or stock is reserved, then passes serialsByVariantId to OrderCounterHandoverService.handOver. |
OrderCounterHandoverService.handOver | order/shared/order-counter-handover.service.ts | Inserts the serial rows with the shipment line, keyed by variant id (unique per order and per sale). |
OrderDispatchService.dispatch | order/shared/order-dispatch.service.ts | Retail writer; same util, check and insert in the dispatch transaction. |
Invariants:
- Serials are never stored on the draft; they travel in the
completerequest. - Serial rows are never deleted; release sets
released_at,released_by_admin_idandrelease_reason. insertOrderItemSerialssorts rows by(productId, serialNumber)so concurrent writers take unique-index entries in the same order. A23505becomes409 ORDER_SERIAL_ALREADY_RECORDED.- Serial exceptions carry no
causeand the value only indetails, which the exception filter returns to the client and never logs. - A serial row's
variant_idisorder_item.variant_idfor both writers. PosSaleQueryService.findOneloads serials only when the sale has an order; drafts get[]with no query.
Release points (plan D5): OrderDeliveryService.fail (shipment_failed / shipment_returned_to_sender), OrderReturnInspectionService.inspectLine when the whole line is back (order_return), and PosCounterReturnService.createInTx through releaseCounterReturnSerials (counter_return).
Full behaviour, request shapes, error codes, deploy order and the mistyped-serial runbook: /docs/developer/pos/serials.
See Also
- API doc:
/docs/developer/pos/api - Features and flows doc:
/docs/developer/pos/feature - Serial numbers:
/docs/developer/pos/serials - TDD: not yet published