Nano Store - Ecommerce Docs
Developer ResourcesPOS

POS Backend Documentation

Backend architecture, data model, services, cache, queues, runtime rules, and operational behavior for POS.

POS - Backend Documentation

1. Documentation Evidence

AreaFiles InspectedVerified Details
Module wiringapps/api/src/modules/pos/*.module.tsAggregate + two admin leaves + worker; imports of Auth, Inventory, Order, Outbox, Payment shared modules
Controllersadmin/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.ts20 routes, guards, permissions, rate limits, ParseUUIDPipe on every id
Servicesshared/*.service.ts, pos-totals.util.ts, pos-counter-return.util.tsOne-transaction completion, lock order, outbox mails, lookup semantics, identity resolution, the counter return transaction
DTOsadmin/sale/dto/*.ts, admin/lookup/dto/*.tsRequest, query, response validation and shapes
Schemapackages/db/src/schema/pos/*.ts, schema/order/enums.ts, migrations 0070-0072pos_sale, pos_sale_item, pos_sale_event, pos_counter_returns; enums; CHECK constraints; the Counter Walk-in constant
Jobspackages/jobs/src/index.tsQueueName.POS, PosJob, payloads (PosSendReceiptPayload.resendKey); the token is not in the payload
Cachecache-invalidation.tags.ts, pos.constants.tsproduct_review-style domain: inventory cleared after completion
Infraenv.validation.tsPOS_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_sale audit timeline.
  • The hourly abandoned-draft sweep.
  • The channel label on orders and checkout sessions (defaults online).
  • The pos_cash / pos_card / pos_qr payment methods and their counter gateway.
  • Counter returns: the single transaction that composes the order module's return and refund steps (PosCounterReturnService), and the pos_counter_returns idempotency 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 after confirmed).
  • Payment gateway logic (a payment_attempt row 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 *InTx methods.
  • Barcode search (does not exist — product has sku, no barcode column). A scanner that emits the SKU uses GET /lookup/products/by-sku.
  • Receipt/invitation sending (delegated to the Notifications queue).

Source of Truth

ConcernSource of TruthNotes
Sale statepos_sale rowStatus + fulfilment + downstream keys, guarded by chk_pos_sale_status_completion
What was soldpos_sale_item (draft) → checkout_session_item → order_itemFrozen at the till, copied not converted
Money takenpayment_attemptSame shape as online payments; the sale number is in gateway_transaction_id
OrderorderThe Order module owns it; POS references it
Auditpos_sale_eventAppend-only, same transaction as the change
Counter return idempotencypos_counter_returnsUnique on (sale, key); survives Redis expiry
Counter Walk-incustomers row POS_COUNTER_WALK_IN_CUSTOMER_IDInserted by migration 0072; valid only while live, active, unbanned, no email, no phone

3. Module Composition

ModuleTypePathControllersProvidersExportsResponsibility
PosModuleAggregateapps/api/src/modules/pos/pos.module.tsNone—PosAdminAggregateModuleComposes the admin leaves with shared services
PosAdminAggregateModuleAggregate.../admin/pos-admin-aggregate.module.tsNone—Sale, Lookup, ManualOrder, Config, Return, SaleSupport leavesNo controllers of its own
PosSaleAdminModuleLeaf.../admin/sale/pos-sale-admin.module.tsPosSaleAdminControllerPosSaleAdminService—The till routes
PosLookupAdminModuleLeaf.../admin/lookup/pos-lookup-admin.module.tsPosLookupAdminController——Customer, product and SKU lookup
PosConfigAdminModuleLeaf.../admin/config/pos-config-admin.module.tsPosConfigAdminControllerPosConfigAdminService—GET /config
PosSaleSupportAdminModuleLeaf.../admin/sale-support/pos-sale-support-admin.module.tsPosSaleSupportAdminControllerPosSaleSupportAdminService—Receipt resend, customer addresses, returnable
PosReturnAdminModuleLeaf.../admin/return/pos-return-admin.module.tsPosReturnAdminControllerPosReturnAdminService—Counter return. Imports PosSharedModule, RoleModule, IdempotencyModule
PosSharedModuleShared.../pos-shared.module.tsNoneIncludes PosCustomerIdentityService, PosCounterReturnServiceIncludes bothEvery decision in the module
PosWorkerModuleWorker.../pos-worker.module.tsNoneProcessor + 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
FilePurposeKey ExportsNotes
pos.constants.tsFixed valuesPOS_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.tsWalk-in provisioning + token minting, Counter Walk-in checksprovisionWalkIn, issueInvite, assertCounterWalkInUsable, archiveWalkInDeliveryAddressNo password; createEmailVerification, never createPasswordReset (no OTP); nullable email means no account row
pos-customer-identity.service.tsWho owns an email or phoneresolve, withIdentityRaceRetry, toWalkInRefusal, isBanned, masksShared with manual orders; the banned rule is applied in the POS mapping only
pos-counter-return.service.tsCounter return and returnable viewcreateCounterReturn, getReturnableOne transaction under withSerializationRetry
pos-counter-return.util.tsPure helpers and shapes for the returnresolveCounterRefundMethod, isReturnWindowClosed, counterLineKey, isCounterReturnKeyRace, COUNTER_RETURN_NOT_ALLOWED_COPYSplit out of the service by the size gate
pos-idempotency-key.guard.tsUUID check of Idempotency-KeyPosIdempotencyKeyGuardRuns before the interceptor reserves the key; an absent key is left to the interceptor
pos-lookup.service.tsBounded ILIKE searches + SKU scansearchCustomers, searchProducts, findBySku2-char minimum; escapeLikePattern; active customers only; product search also matches variant SKU
pos-mail-queue.service.tsOutbox enqueuesqueueReceipt, queueReceiptResend, queueWalkInInviteSame transaction as the sale; dedupe on sale/customer id; a resend dedupes on <sale>:resend:<key>
pos-sale-access.service.tsLocks + totalslockSale, lockDraft, loadLines, recomputeTotalsFOR UPDATE; totals recomputed, never incremental
pos-sale-completion.service.tsThe one transactioncompleteLock order sale → products asc → cart → session → payment → order
pos-sale-draft.service.tsDraft mutationsopen, attachCustomer, createWalkInCustomer, setPaymentMethod, setFulfilment, cancelCustomer change resets to pickup; cancel reason mandatory; archives a Counter Walk-in's one-time address
pos-sale-event.service.tsAppend-only auditrecordNo update path anywhere
pos-sale-line.service.tsLines on the draftupsertLine, removeLinePUT replaces the quantity; ON CONFLICT DO UPDATE
pos-sale-number.service.tsPOS-2026-000042issueOwn sequence, DB clock in Asia/Kathmandu, gaps expected
pos-sale-query.service.tsAdmin readsfindAll, findOne, findTimelinePage + total in one transaction; offset pagination (10k-row cap noted)
pos-totals.util.tsPure total mathcomputePosSaleTotals, computePosLineAmountsInteger minor units; subtotal = Σ lineTotal, not netAmount
pos-checkout-materializer.service.tsPipeline rowsresolveShipping, materializeCart 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.ts

Also 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/FieldTypeNullableDefaultIndex/ConstraintRelationNotes
idserialNogeneratedPKN/AInternal
public_iduuidNouuid7uniqueN/AExternal handle
sale_numbervarchar(32)No—uniqueN/APOS-2026-000042; WA-2026-000001 for a WhatsApp sale
channelsales_channel enumNoposchk_pos_sale_channel, chk_pos_sale_number_prefixN/Apos (the counter) or whatsapp; never online. Added by 0055
statusenumNodraft—N/Adraft/picked_up/ordered/cancelled
fulfilmentenumNonone—N/Apickup/delivery; unset is unrepresentable
customer_iduuidNo—index + FK RESTRICTcustomersEvery sale belongs to an account
customer_createdbooleanNofalse—N/A§48 Customer Type, stored not derived
created_by_admin_iduuidNo—index + FK RESTRICTadminUsersSales-by-administrator must not drift
cart_idintegerYes (draft)NULLpartial uniquecarts (RESTRICT)Born converted
checkout_session_idintegerYes (draft)NULLpartial uniquecheckoutSessions (RESTRICT)Born completed
payment_attempt_idintegerYes (draft)NULLpartial uniquepaymentAttempts (RESTRICT)Born succeeded
order_idintegerYes (draft)NULLpartial uniqueorders (RESTRICT)Set at completion
delivery_address_idintegerYesNULLindex + FK RESTRICTcustomerAddressesNULL for pickup
payment_methodenumNo——N/ACounter: pos_cash/pos_card/pos_qr. WhatsApp: cod/pos_card/pos_qr. Never esewa, and cod never on a pos sale (see constraints)
payment_referencevarchar(128)YesNULL—N/ARecorded, never validated; refused beside cash
currencyvarchar(3)NoNPR—N/AUppercased, length 3
subtotal/discount_amount/shipping_amount/grand_totalbigintNo0—N/AInteger minor units
total_quantity/line_countintegerNo0—N/ADerived
correlation_iduuidNouuid7—N/ATies logs/events/outbox
versionintegerNo1—N/ABumped on every change
completed_at/cancelled_attimestamp tzYesNULL—N/ATerminal stamps
created_at/updated_attimestamp tzNonow—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_up only with pickup and channel = 'pos' (only the counter hands over at completion); ordered with delivery, or — new in 0055 — with pickup when channel = 'whatsapp' (the goods wait for the order's own ready-for-pickup and collect steps; a counter pickup at ordered is still refused); cancelled has no order.
  • chk_pos_sale_channel — channel is pos or whatsapp (compared ::text).
  • chk_pos_sale_number_prefix — WA-… numbers belong to whatsapp and to nothing else; pos numbers never start WA-.
  • 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 three pos_* methods; this is the database backstop, so a violation would surface as a bare 23514. Enforced on pos_sale only: order and checkout_session stay 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 is pos_card/pos_qr (compared ::text because 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/FieldTypeNullableDefaultIndex/ConstraintRelationNotes
id / public_idserial / uuidNouuid7PK / uniqueN/A—
pos_sale_idintegerNo—FK CASCADE + indexposSalesDeleting a sale deletes its lines
product_idintegerNo—FK RESTRICT + indexproductsA counter line is money that changed hands
product_public_iduuidNo——N/ADenormalised
product_namevarchar(255)No——N/ASnapshot; survives rename/delist
skuvarchar(64)YesNULL—N/ASnapshot
unit_price/mrp/line_total/discount_amount/net_amountbigintNo——N/APrice snapshot, unlike the cart
quantityintegerNo——N/A1–99 (chk_pos_sale_item_quantity_range)
  • uq_pos_sale_item_pos_sale_id_product_id — one line per product; the upsert is ON 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/FieldTypeNullableDefaultIndex/ConstraintRelationNotes
id / public_idserial / uuidNouuid7PK / uniqueN/A—
pos_sale_idintegerNo—FK CASCADE + composite indexposSalesTimeline read
event_typeenumNo——N/A10 values from created to cancelled
from_status/to_statusenumYesNULL—N/ABoth or neither
actor_admin_iduuidYesNULLFK SET NULL + composite indexadminUsersAudit survives offboarding; differs from RESTRICT on the sale
reasontextYesNULL—N/AMandatory non-blank for cancelled
metadatajsonbYesNULL—N/AProduct/quantity/old-new values; never the invite token
correlation_iduuidNo——N/A—
created_attimestamp tzNonow—N/ANo updated_at — append-only
  • chk_pos_sale_event_transition_pair, chk_pos_sale_event_transition_moves, chk_pos_sale_event_cancel_reason (the IS NOT NULL arm is load-bearing — the original constraint passed on NULL reason, fixed by migration 0015), chk_pos_sale_event_reason_not_blank (~ '[^[:space:]]', not btrim).

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/FieldTypeNullableDefaultIndex/ConstraintRelationNotes
idserialNogeneratedPKN/AInternal only
public_iduuidNouuid7()UNIQUEN/ANot exposed by any response; the API returns the order return's public id
pos_sale_idintegerNo—FK RESTRICT; leads two indexespos_sale—
order_return_idintegerNo—FK RESTRICT; uq_pos_counter_returns_order_return_id UNIQUEorder_returnOne counter-return row per return
order_refund_idintegerYesNULLFK RESTRICT; idx_pos_counter_returns_order_refund_idorder_refundNULL when nothing was refundable (inspection creates no refund)
idempotency_keyuuidNo—uq_pos_counter_returns_sale_key UNIQUE with pos_sale_idN/AThe client's Idempotency-Key
request_hashchar(64)No——N/ASHA-256 of the canonical request (RequestHashUtil); a replay with a different hash is IDEMPOTENCY_KEY_CONFLICT
created_by_admin_iduuidNo—FK RESTRICT; idx_pos_counter_returns_created_by_admin_idadmin_usersThe cashier
created_attimestamptzNonowidx_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_method gains card_reversal and qr_reversal (migration 0070, appended with IF NOT EXISTS; there is no DROP VALUE, so the labels remain after a down migration). The application, not the type, restricts them to channel = 'pos' orders.
  • Migration 0072 inserts the shared Counter Walk-in customers row (name Counter Walk-in, no email, no phone, active, not banned). Its id is POS_COUNTER_WALK_IN_CUSTOMER_ID (01a2076e-fe59-73dc-9d64-ee3ce2edb086) exported from @nano-store/db; customers has no public_id, so customers.id is the exposed id.
  • PosReturns is 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.

MigrationUpDown
0054_sales_channel_whatsappALTER 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 42710No-op (SELECT 1); the labels stay, so up, down, up is a fixpoint
0055_pos_sale_channelSET 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_completionRefuses (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_backfillData 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 addressNo-op: the forward left no marker separating corrected rows from rows written correctly since
0057_pos_sale_pos_not_codSET LOCAL lock_timeout = '5s'; a guard that raises, naming the count, if any pos_sale is pos with cod; chk_pos_sale_pos_not_codDROP 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, count

The 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

MethodCalled ByReadsWritesSide EffectsErrors
lockSaleAll mutationspos_sale FOR UPDATE, filtered channel = 'pos'——404 POS_SALE_NOT_FOUND (also for a WhatsApp sale)
lockDraftAll draft mutationspos_sale——409 POS_SALE_ALREADY_COMPLETED / POS_SALE_NOT_DRAFT
loadLinescompletion, totalspos_sale_item———
recomputeTotalsline mutations, fulfilmentlinespos_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

MethodReadsWritesNotes
provisionWalkIncustomers (email check)customers, accountpassword: null; email_verified: false; same rows as registration, minus the password
issueInvite—verification tokencreateEmailVerification (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

MethodTransactionBehavior
openownInserts draft + pickup; customerId required; event created
attachCustomerownLocks, validates customer, applies patch + CLEAR_DELIVERY_ON_CUSTOMER_CHANGE (fulfilment: pickup, address NULL, shipping 0), event customer_assigned
createWalkInCustomerownNormalises 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
setPaymentMethodownLocks 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
setFulfilmentownRefuses 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
cancelownLocks, 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, event item_added/item_quantity_changed, recomputes totals.
  • removeLine: locks, hard deletes by (pos_sale_id, product_public_id) plus the optional variantPublicId query param, event item_removed, recomputes totals. Omitting variantPublicId works only when the product is on the sale as one configuration; several is 409 POS_LINE_VARIANT_REQUIRED. 404 POS_LINE_NOT_FOUND if absent.

6.8 PosSaleCompletionService

complete — one transaction:

  1. lockDraft (first lock, the start of the global order).
  2. applyPaymentReference — trims, refuses beside pos_cash.
  3. assertCompletable — lines, customer, delivery address.
  4. assertPricesUnchanged — current sellingPrice vs frozen unitPrice; refuse loudly.
  5. reserveAll — ascending product id; insufficient stock translated to POS_INSUFFICIENT_STOCK (narrowed on the code, never the class); nothing queried after a failed statement (25P02).
  6. resolveShipping + materialize — cart born converted, session born completed (channel and fulfilmentType copied from the sale — pos for a counter sale), frozen checkout_session_items, payment_attempt born succeeded with gateway_transaction_id = POS-{saleNumber} and a real random callback token hash.
  7. reservations.finalize per line — holds become deductions.
  8. orders.createFromCheckout(..., { executor: tx, suppressOpeningEmail: pickup }) — the order inside the sale's transaction.
  9. handover.handOver for pickup — drives the order to delivered.
  10. finalise — status picked_up/ordered, all keys, version + 1, guarded WHERE status = 'draft' (replay → POS_SALE_ALREADY_COMPLETED).
  11. mail.queueReceipt — outbox row in the same transaction.
  12. 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).
  • search is an ILIKE %term% on sale_number OR an EXISTS over the linked order's order_number, escaped with escapeLikePattern(normalizeSearchTerm(term)); the count query uses the same filter.
  • findOne: sale + lines + customer/admin names + order refs; 404 POS_SALE_NOT_FOUND.
  • findTimeline: events oldest first, actor name left-joined.

6.10a PosSaleSupportAdminService, PosConfigAdminService, PosReturnAdminService

ServiceMethodCalled ByReadsWritesSide EffectsErrors
PosSaleSupportAdminServiceresendReceiptPOST /receipt-emailsale (locked), customers.email, outbox_events (last 24 h)one outbox_events rowOutbox job pos.send_receipt with resendKeyPOS_RECEIPT_NOT_AVAILABLE, POS_CUSTOMER_NO_EMAIL, POS_RECEIPT_RESEND_LIMIT
PosSaleSupportAdminServicelistCustomerAddressesGET /customer/addressessale, active addresses——POS_SALE_NOT_DRAFT, POS_WALK_IN_NO_ADDRESS_BOOK
PosSaleSupportAdminServicegetReturnableGET /returnabledelegates to PosCounterReturnService——POS_SALE_NOT_FOUND, POS_COUNTER_RETURN_NOT_ALLOWED
PosConfigAdminServicegetConfigGET /configCounter Walk-in row——POS_COUNTER_CUSTOMER_MISSING (503)
PosReturnAdminServicecreatePOST /returnsvia PosCounterReturnService—After a fresh commit: activity record pos.counter_return.created; the audit write is in a try/catch and a failure is loggedsee §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

MethodCalled ByReadsWritesSide EffectsErrors
createCounterReturn(req)PosReturnAdminService.createpos_sale (locked), pos_counter_returns, orders, order_itemsorder_return*, order_refund*, inventory (restock), pos_counter_returnsAfter 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)PosSaleSupportAdminServicepos_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):

StepCode LocationWhat HappensWhy It HappensFailure/Edge Case
1access.lockSaleFOR UPDATE on the saleSerialises two tills; lock order is sale then order then return/refund404 POS_SALE_NOT_FOUND
2replay checkLooks up (pos_sale_id, idempotency_key) in pos_counter_returnsDurable idempotency that does not depend on RedisSame hash returns replayed: true with no writes; different hash is 409 IDEMPOTENCY_KEY_CONFLICT
3completedOrderOfThe sale must be picked_up or ordered with an orderDraft and cancelled sales have nothing to returnnot_completed
4order status and windowreturned 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_closedSame comparison as OrderReturnService.assertEligible409
5line checksDuplicate (product, variant) keys, a key not on the order, a quantity above deliveredQuantity - returnPending - returnedServer-side limits; the client cannot over-returnduplicate_line, line_not_in_sale, quantity_exceeds_returnable
6resolveCounterRefundMethodUses 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 saleNone; the method is never refused here
7order servicesrequestOnBehalfInTx, decideInTx (approve), receiveInTx, inspectInTx (every line accepted; restocks via InventoryWriteService.adjustStock)Reuses the order module's rules and events instead of copying themComposed ORDER_* codes are mapped to one POS_COUNTER_RETURN_NOT_ALLOWED reason
8refundIf inspection created a refund: approveInTx with the method, then settleInTx with the referenceCash 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)
9insertpos_counter_returns rowThe unique (sale, key) index closes a race between two identical requestsA 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

StepCode PathBehaviorFailure Case
1lockDraftSerialises on the sale404/409 on missing/terminal
2assertCompletableEmpty/uncustomered/addressless refused409 POS_SALE_EMPTY / POS_SALE_NO_CUSTOMER / POS_DELIVERY_ADDRESS_REQUIRED
3assertPricesUnchangedFrozen price vs live price409 POS_PRODUCT_PRICE_CHANGED — nothing charged
4reserveAllStock held, ascending ids409 POS_INSUFFICIENT_STOCK — nothing charged
5createFromCheckoutOrder inside the txRollback of the whole sale
6handOverPickup → delivered via recomputeRollback
7finaliseTerminal status + keys409 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 PatternBuilderValueTTLInvalidationCaller
inventory:* (existing)existing inventory keys—existingtriggerForWrite({ 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

QueueJobProducerProcessorPayloadRetry/BackoffIdempotency
QueueName.POSpos.send_receiptoutbox (sale tx, or receipt-email resend)PosReceiptHandler{ correlationId, posSalePublicId, resendKey? }BullMQ policy; HttpException = not retriedoutbox dedupe on sale id; a resend on <sale>:resend:<key>; notification jobId pos-receipt-<sale> or pos-receipt-<sale>-<resendKey>
QueueName.POSpos.send_walk_in_inviteoutbox (sale tx)PosWalkInInviteHandler{ correlationId, posSalePublicId, customerId } — no tokensameoutbox dedupe on customer id
QueueName.POSpos.sweep_abandoned_draftscron (direct)PosDraftSweepHandler{ correlationId, batchSize }samejobId 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

EventProducerRoom/TargetPayloadConsumerReliability Notes
pos.sale_completed (outbox)PosMailQueueServiceQueueName.POS{ correlationId, posSalePublicId }PosReceiptHandler → NOTIFICATIONSRow in the sale's transaction
pos.walk_in_created (outbox)PosMailQueueServiceQueueName.POS{ correlationId, posSalePublicId, customerId }PosWalkInInviteHandler → NOTIFICATIONSDeduped on customer
pos.receipt_resend_requested (outbox)PosMailQueueService.queueReceiptResendQueueName.POS{ correlationId, posSalePublicId, resendKey }PosReceiptHandler → NOTIFICATIONSRow in the resend transaction; capped at 3 per sale per 24 h
pos_sale_event rowsevery mutation servicepos_sale_event tabletype + statuses + actor + metadatatimeline endpoint, auditsSame transaction as the change

No WebSocket/realtime surface exists in this module.

11. Security, Auth, and Abuse Controls

  • Guards: JwtAuthGuard + RoleGuard on both controllers; IpThrottlerGuard per route.
  • Permissions: Pos_CREATE / Pos_READ / Pos_UPDATE / Pos_DELETE, from the Pos permission module — spell it Pos, never POS. The counter return route requires Pos_UPDATE and PosReturns_CREATE together (RoleGuard uses every); PosReturns is its own module so a cashier can refund a counter sale without authority over online returns and refunds. Run permissions:sync so the rows exist. Pos_READ also exposes customer lookup, so it is grantable separately from Users_READ.
  • Identity: @CurrentUser() user.id is the operator; every mutation records them on the event. The sweep records actor_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_WRITE 180/min (every draft mutation — 10/min ADMIN_WRITE would throttle a 15-item basket mid-sale), ADMIN_POS_COMPLETE 30/min, ADMIN_POS_READ 120/min (sales list, customer addresses, returnable, config), ADMIN_POS_SEARCH 120/min (customer and product lookup, re-keyed from PUBLIC_SEARCH), ADMIN_POS_SCAN 300/min (SKU lookup), ADMIN_POS_RECEIPT 10/min and ADMIN_POS_RETURN 20/min. Sale detail and timeline still use ADMIN_READ (30/min).
  • Idempotency: receipt-email and returns require an Idempotency-Key UUID. PosIdempotencyKeyGuard rejects a malformed key (400 POS_IDEMPOTENCY_KEY_INVALID) before IdempotencyInterceptor reserves it in Redis; an absent key is answered by the interceptor (IDEMPOTENCY_KEY_REQUIRED). The return additionally has the durable pos_counter_returns record.
  • 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_EXISTS returns only customerId, name and matchedOn. phoneDropped discloses 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_id in the query — another customer's address returns 404, never 403.
  • IDOR/leak hygiene: ParseUUIDPipe on every id (its absence caused 500s in Reviews); responses expose only public_ids, never integer PKs; a malformed id is a clean 400.
  • Fail-closed: the transaction aborts on any guard; finalise is guarded on status = 'draft'; a completed sale cannot be re-priced or re-charged.
  • Audit: every mutation writes pos_sale_event in the same transaction; the event table is append-only with no updated_at.

13. Error Handling

Error CodeHTTP StatusThrown ByConditionClient Action
POS_SALE_NOT_FOUND404access/query/email handlersSale id does not resolveReturn to the sales list
POS_SALE_NOT_DRAFT409lockDraft, applyToDraftCancelled (or otherwise not draft)Start a new sale
POS_SALE_ALREADY_COMPLETED409lockDraft, finaliseMoney already takenDo not retry — show the order number
POS_SALE_EMPTY409assertCompletableNo linesBlock complete until a line exists
POS_SALE_NO_CUSTOMER409 / 404assertCompletable / assertCustomerExistsNo customer attached / customer missingSend the operator to lookup
POS_DELIVERY_ADDRESS_REQUIRED409draft + completionDelivery without an address, or both address formsOpen the address form
POS_ADDRESS_NOT_FOUND404draft / completionAddress not this customer's / store district missingRe-fetch addresses / fix POS_STORE_DISTRICT_ID
POS_PRODUCT_NOT_SELLABLE404 / 409line + completionUnpublished, deleted or mispricedRemove the line, name the product
POS_PRODUCT_PRICE_CHANGED409assertPricesUnchangedPrice moved mid-saleTell the operator; remove and re-add
POS_INSUFFICIENT_STOCK409reserveAllSomeone else took the last oneShow remaining; reduce quantity
POS_PAYMENT_REFERENCE_NOT_ALLOWED409applyPaymentReferenceReference sent with cashClear the field or change method
POS_CUSTOMER_EMAIL_TAKEN409PosCustomerServiceEmail already has an account (incl. closed). No longer thrown by POST /customer, which uses the three POS_CUSTOMER_CONTACT_* codesn/a for the till walk-in
POS_WALK_IN_CONTACT_REQUIRED400createWalkInCustomerNeither email nor phoneAsk for one
POS_WALK_IN_PHONE_INVALID400createWalkInCustomerPhone cannot be normalised to E.164Fix the number
POS_RECIPIENT_PHONE_INVALID400setFulfilmentRecipient phone fails normalizeToE164Fix the number
POS_CUSTOMER_CONTACT_EXISTS409toWalkInRefusalContact owned by an attachable customer; details { customerId, name, matchedOn }Attach that customer
POS_CUSTOMER_CONTACT_CONFLICT409toWalkInRefusalEmail and phone belong to two customersCorrect one, or search
POS_CUSTOMER_CONTACT_UNAVAILABLE409toWalkInRefusal, race retryOwner closed, deleted, banned or unverified; phone-only on a non-attachable phone; second race lossUse other contact details
POS_SKU_NOT_FOUND404resolveSellableBySkuNo match, or several case-insensitive matchesRe-scan or search by name
POS_SKU_AMBIGUOUS409pickSkuCandidateExact SKU on two products or two variant rows; details.candidatesPick one by hand
POS_VARIANT_NOT_SELLABLE404loadSellableThe configuration is not sellableChoose another
POS_DISTRICT_NOT_FOUND404setFulfilmentdistrictId matches no districtRe-pick the district
POS_WALK_IN_SAVED_ADDRESS_NOT_ALLOWED409setFulfilmentaddressPublicId with the Counter Walk-inType the address
POS_WALK_IN_NO_ADDRESS_BOOK404listCustomerAddressesCustomer is the Counter Walk-inType the address
POS_COUNTER_CUSTOMER_MISSING503assertCounterWalkInUsableCounter Walk-in row missing or alteredRestore the row (an operations fix)
POS_RECEIPT_NOT_AVAILABLE409resendReceiptSale is not picked_up or orderedComplete the sale first
POS_CUSTOMER_NO_EMAIL409resendReceiptCustomer has no emailOffer a printout
POS_RECEIPT_RESEND_LIMIT409resendReceipt3 resends in 24 hWait
POS_IDEMPOTENCY_KEY_INVALID400PosIdempotencyKeyGuardHeader is not a UUIDSend a UUID
POS_COUNTER_RETURN_NOT_ALLOWED409PosCounterReturnServicedetails.reason is one of not_completed, window_closed, fully_returned, line_not_in_sale, quantity_exceeds_returnable, duplicate_lineBranch on the reason (see the API reference)
IDEMPOTENCY_KEY_CONFLICT409createInTxSame key, different bodyGenerate a new key for a new return
ORDER_REFUND_METHOD_NOT_ALLOWED409OrderRefundSettlementService.approveInTxCard or QR reversal on a non-pos orderPick another method (not reachable from the till)
POS_LINE_NOT_FOUND404removeLineRemoving a line that is not thereRe-fetch the sale
POS_QUANTITY_OUT_OF_RANGE400assertQuantityNot a whole number in 1–99Clamp 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

SignalLocationPurpose
LogLogger in completion, sweep, queue processor, customer service[pos] ... state-change and failure visibility
Auditpos_sale_event table§42 timeline; append-only, same-tx
Tracecorrelation_id on sale, events, outbox payloads, payment attemptOne sale across every log line
Queue visibilityBullMQ job.returnvalueDeterministic failures recorded as { success: false, retryable: false, errorCode }

15. Testing and Validation

Test TypeFilesCoverage
Unitpos-totals.util.spec.tsPure total/line arithmetic
Integrationpos-sale.int.spec.tsDraft mutations, completion, walk-in, error branches
Integrationshared/pos-customer-identity.int.spec.ts, shared/pos-sku-lookup.int.spec.tsIdentity resolution; SKU lookup rules
Integrationshared/pos-counter-return.int.spec.ts, order/shared/order-refund-method-guard.int.spec.tsThe counter return transaction, replay, refund method guard
Unitshared/pos-counter-return.service.spec.ts, shared/pos-idempotency-key.guard.spec.tsPure return helpers; key guard
HTTP integrationadmin/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.tsRoute-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.mjsCHECK constraints both directions against real PostgreSQL (97/0)
Live HTTP.omc/plans/POS/checks-pos.sh24/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

UnitTypeOwnsDepends OnCalled ByCallsState TouchedFailure Modes
PosSaleAdminServiceserviceorchestration + DTO mappingdraft, line, completion, querycontroller4 shared services—Mapping misses
PosSaleAccessServiceservicelocks + totalsDBall mutators—pos_sale, lines404/409 codes
PosSaleEventServiceserviceaudit rowsDBevery mutationinsertpos_sale_event—
PosSaleNumberServiceservicesale numbersDB sequencedraftnextvalsequencemissing sequence
PosCustomerServiceservicewalk-in accounts + tokensVerificationTokenServicedraft, workerinsertscustomers, account, verification409 email taken
PosLookupServiceservicebounded searchDBlookup controllerselect—400 short term
PosSaleDraftServiceservicedraft lifecycleaccess, events, numbers, customer, mailadmin service5 servicespos_sale, addresses, outbox409/404 set
PosSaleLineServiceservicedraft linesaccess, events, totalsadmin service3 servicespos_sale_item, totals400/404/409
PosSaleCompletionServiceservicethe one transactionaccess, events, materializer, reservations, orders, handover, mail, cacheadmin service8 collaborators7 tables + outbox409 set; rollback
PosCheckoutMaterializerServiceservicepipeline rowsconfig, payment eventscompletion3 inserts + eventcart, session, items, attemptmissing row errors
PosSaleQueryServiceserviceadmin readsDBadmin serviceselects—404
PosMailQueueServiceserviceoutbox rowsoutboxdraft, completionenqueueoutbox_events—
PosTotalsUtilutilpure mathnoneline, access———
PosCustomerIdentityServiceservicecontact ownership resolutionDBdraft, manual-orderselects, savepointcustomers409 contact codes
PosCounterReturnServiceservicethe counter return transaction, returnable viewaccess, order return/inspection/settlement services, cache, configreturn admin service, support service3 order servicesreturn, refund, stock, pos_counter_returnsPOS_COUNTER_RETURN_NOT_ALLOWED, replay conflict
PosSaleSupportAdminServiceservicereceipt resend, addresses, returnableaccess, mail, queries, address query, counter returnsupport controlleroutboxoutbox_events409 receipt codes
PosConfigAdminServiceservicetill configcustomer serviceconfig controllerone select—503
PosReturnAdminServiceservicereturn entry point and auditcounter return, activity, sale adminreturn controlleractivity recordMongo activityaudit failure logged
PosIdempotencyKeyGuardguardUUID check of the key—N5, N7 routes——400
PosQueueProcessorworkerdispatch3 handlersBullMQhandler recordjobsdeterministic vs retryable
PosReceiptHandlerhandlerreceipt emailDB, bull, notificationsprocessorenqueueoutbox-consumedskip outcomes
PosWalkInInviteHandlerhandlerinvite emailDB, bull, customer, configprocessormint + enqueueverificationskip outcomes
PosDraftSweepHandlerhandlerabandon sweepDB, eventsprocessorcancelpos_sale, eventsper-row try/catch
PosMaintenanceSchedulerschedulercron triggerqueuecronenqueuejobsbatch-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/ConstraintColumnsTypeQuery/Invariant SupportedTradeoff
uq_pos_sale_{cart,session,payment,order}_ideach FKpartial uniqueReplay-safe completion; one downstream row per saleNULLs in draft rows (by design)
idx_pos_sale_status_created_atstatus, created_atbtree§51 list default order + date filterwrite overhead
idx_pos_sale_payment_method_created_atmethod, created_atbtree§54 reconciliation by tenderwrite overhead
idx_pos_sale_event_pos_sale_id_created_atsale, created_atbtreetimeline readwrite overhead
idx_pos_sale_event_actor_admin_id_created_atactor, created_atbtreeper-admin auditwrite overhead
uq_pos_sale_item_pos_sale_id_product_idsale, productuniqueone line per product; upsert target—
every FK indexFK columnbtreeFK checks / join paths—

16.5 Business Logic and Invariant Catalog

InvariantEnforced ByWhy It ExistsFailure ErrorTests
A completed sale holds every downstream keychk_pos_sale_status_completionNo paid sale without an order23514 (probe-verified)probe
Terminal status matches fulfilmentsameNo delivery-ordered pickup23514probe
Pickup: no address, no shipping; delivery: addresschk_pos_sale_fulfilment_addressNo money for a service not rendered23514probe
Reference only beside card/QRDTO + chk_pos_sale_payment_reference_methodCash has nothing to reference409 / 23514probe
Total follows from partschk_pos_sale_grand_total_matchesUnforgeable till total23514probe
Line amounts follow from price × qty3 line checksOperator cannot mistype a price23514probe
One line per productunique index + ON CONFLICTScanning twice = quantity, not duplicate—int spec
Cancellation carries a non-blank reasonDTO + chk_pos_sale_event_cancel_reasonAudit answers why400 / 23514probe
Walk-in account has no passwordPosCustomerServiceCredentials are the customer's alone—int spec
Price quoted is the price chargedassertPricesUnchangedNo silent re-pricingPOS_PRODUCT_PRICE_CHANGEDint spec
Reserves only at completionsweep + constantsDrafts hold no stock—int spec
A counter return is atomic and idempotentcreateInTx + uq_pos_counter_returns_sale_keyNo return without its refund and restock, and no double refund on a retryreplay returns the stored result; different body is 409pos-counter-return.int.spec.ts
Only delivered or partially_returned orders inside the 7-day window can be returnedcreateInTxGoods must have left and the window must be openPOS_COUNTER_RETURN_NOT_ALLOWEDsame
Any refund method on any POS sale; card and QR reversals only on a pos orderresolveCounterRefundMethod, approveInTxA reversal reverses a counter-terminal payment, which only a counter order hasORDER_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 hresendReceipt under the sale lockCost and abuse of email sendsPOS_RECEIPT_RESEND_LIMITnot verified here
A Counter Walk-in's typed address is never listed and is archived when the sale endsarchiveWalkInDeliveryAddressOne shared account must not accumulate other people's addressesPOS_WALK_IN_* codesnot verified here

16.6 Tradeoffs, Alternatives, and ADR Notes

DecisionContextChosen OptionAlternativesWhy ChosenTradeoffsRevisit Trigger
Reuse the online pipelineCounter sale = same commercial recordMaterialise cart/session/attempt, call createFromCheckoutA parallel counter ledgerOne order domain, one return/refund pathMaterializer complexity; channel labelOrder module diverges
Nullable+unique downstream keysDraft has no order yetPartial unique indexes + status CHECKPlaceholder rowsNo phantom sessions/payments; replay-safeNULLs to handle in queries—
Cart/session born terminalLive-cart uniques collide with a phone cartInsert converted/completedNarrow the partial index predicatesPredicate inference is exact (42P10 otherwise)Unusual shape, documentedCart module changes predicate
No awaiting_paymentNo gateway round trip at a till4 states onlyModel the waitA state no path can produce——
Price freeze + loud refusalQuoted price is agreed priceRefuse on driftCharge old/new silentlyThe two people are both presentMid-sale 409s—
Never-expiring single-use inviteWalk-in may not read email for weeksFar-future sentinel + consumed_at24h TTLOwner policy; no support dead-endLong-lived if stolenPolicy change → config
No OTP on the invite6-digit code that never expires is brute-forciblecreateEmailVerification onlycreatePasswordResetSearch space——
Token minted at send timeOutbox dead rows are never purgedMint in the workerCarry token in payloadA credential must not sit in an operator-facing tableRetry replaces token (fine)—
pos_sale_event.actor_admin_id SET NULLOffboarding must not deadlockSET NULL + attribution CHECKRESTRICT like the saleTrail survives; retention ≠ deadlockLost attribution—
Own sequence for sale numbersTwo documents counted by two peoplepos_sale_number_seqShared order_number_seqContiguous till rollGaps (expected)—
Lookup is ILIKE, not trigramOperator wants the exact rowILIKE + escapingTrigram similarityFuzzy match could sell the wrong SKU>10k rows needs prefix indexCatalogue grows
Compose the order services for a counter returnA return, refund and restock must be one unitCall *InTx methods of the order module in one transactionA parallel POS return ledgerOne return and refund state machine; reuse of restockWaived separation of duties; a coupling to order internalsOrder module changes its InTx signatures
Durable idempotency rowRedis keys expire; a replay after expiry must not refund twicepos_counter_returns unique on (sale, key)Redis onlyThe money record is the proofOne more table—
Shared Counter Walk-in customerA buyer who gives no contact still needs an accountOne migrated row with no contact detailsA customer per saleNo junk accounts; no PIIDelivery addresses are one-time and archivedOwner wants per-buyer records
Offset paginationTill list is small for yearsPaginationUtil offsetKeysetSimplicity10k/100k-row cap~3 years at 100 sales/day
Cache invalidation after commitNetwork call in a tx is forbiddentriggerForWrite post-commitInside the txMust not hold locks for an HTTP timeoutBrief staleness—

16.7 Operational Runbook

OperationHow to InspectHealthy StateFailure SignalRecovery
QueueBull Board / logs [start]/[success]/[failure]/[skip]Jobs completing; skips are expected and loggederrorCode returns or rethrowsRetry via BullMQ for transient; deterministic failures need a code fix
SweepLogs examined N, cancelled M, failed KM > 0 with due draftsBatch-cap warning (filled its batch)Next hourly tick picks up the rest
DBpos_sale / pos_sale_event queriesConstraints satisfied; no 23514 in API logsDeadlock 40P01 (rare)Lock order is the mitigation; retry
Cacheinventory domain invalidationPost-completion clear firesNo clear (silent)triggerForWrite is fire-and-forget; re-trigger
Counter returnspos_counter_returns joined to order_return and order_refundOne row per return, refund settledA 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-inGET /api/admin/pos/config200 with the id503 POS_COUNTER_CUSTOMER_MISSINGRestore the row: live, active, not banned, email and phone NULL
Receipt resendoutbox_events where dedupe_key like '<sale>:resend:%'Rows are dispatched to the queueRows that stay undispatched or deadReplay from the outbox
TimelineGET /sales/{id}/timelineEvents match the sale's historyMissing eventsEvents are same-tx; a gap means a bug

16.8 Backend Risk Register

RiskAreaImpactCurrent MitigationRemaining Gap
Two tills complete one salecompletionDouble chargelockDraft + unique keys + guarded finalise—
Counter and online checkout deadlockcompletion40P01Ascending product lock order matching checkoutDistributed tx isolation not tested at load
Replayed completioncompletionSecond orderFour partial unique indexes + WHERE status='draft'—
Email outageasyncNo receipt/inviteOutbox durability; queue retryProvider blackhole (job retries)
Price driftcompletionWrong price chargedLoud refusal at the tillNone (by design)
Offboarded operatorreportingUnattributed salesRESTRICT FK on the sale; SET NULL on eventsSale blocks account removal
Two tills return the same salecounter returnDouble refundSale lock + unique (sale, key) + serialization retry—
Tampered Counter Walk-in rowidentityA sale carries a person's contact detailsassertCounterWalkInUsable returns 503Not a database constraint
Receipt resend abuseasyncEmail spam3 per 24 h per sale, ADMIN_POS_RECEIPTCap is counted from outbox rows
Waived separation of dutiescounter returnOne cashier approves their own refundPermission PosReturns_CREATE + every step called with the same admin idBy decision, no second approver
Catalogue growthlookupSlow fuzzy searchILIKE + bounded paginationPrefix 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.

UnitPathRole
order-item-serial.util.tsapps/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.tsapps/api/src/modules/pos/shared/resolvePosLineSerials: normalise, line lookup, hand-over rule, count and duplicate check, in that order.
pos-counter-return-serial.util.tsapps/api/src/modules/pos/shared/releaseCounterReturnSerials: validates picks, releases as counter_return. DB writes only, so it is safe under withSerializationRetry.
PosSaleCompletionService.completeWithinpos/shared/pos-sale-completion.service.tsResolves serials and runs assertSerialsAvailable before prices are checked or stock is reserved, then passes serialsByVariantId to OrderCounterHandoverService.handOver.
OrderCounterHandoverService.handOverorder/shared/order-counter-handover.service.tsInserts the serial rows with the shipment line, keyed by variant id (unique per order and per sale).
OrderDispatchService.dispatchorder/shared/order-dispatch.service.tsRetail writer; same util, check and insert in the dispatch transaction.

Invariants:

  • Serials are never stored on the draft; they travel in the complete request.
  • Serial rows are never deleted; release sets released_at, released_by_admin_id and release_reason.
  • insertOrderItemSerials sorts rows by (productId, serialNumber) so concurrent writers take unique-index entries in the same order. A 23505 becomes 409 ORDER_SERIAL_ALREADY_RECORDED.
  • Serial exceptions carry no cause and the value only in details, which the exception filter returns to the client and never logs.
  • A serial row's variant_id is order_item.variant_id for both writers.
  • PosSaleQueryService.findOne loads 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

On this page

POS - Backend Documentation1. Documentation Evidence2. Backend Scope and BoundariesOwnsDoes Not OwnSource of Truth3. Module Composition4. File and Directory Map5. Data Model5.1 Schema Source5.2 Tables and Collectionspos_salepos_sale_itempos_sale_eventpos_counter_returnsOther schema changes5.3 Relationship Diagram5.4 Migrations 0054 to 0057 (the whatsapp channel)6. Services and Responsibilities6.1 PosSaleAccessService6.2 PosSaleEventService6.3 PosSaleNumberService6.4 PosCustomerService6.4a PosCustomerIdentityService6.5 PosLookupService6.6 PosSaleDraftService6.7 PosSaleLineService6.8 PosSaleCompletionService6.9 PosCheckoutMaterializerService6.10 PosSaleQueryService6.10a PosSaleSupportAdminService, PosConfigAdminService, PosReturnAdminService6.11 PosMailQueueService6.11a What a receipt line says6.11b Receipt content6.12 PosTotalsUtil6.13 PosCounterReturnService7. Runtime Flows7.1 Completion — the one transaction7.2 The walk-in creation + invitation7.2a The one-time walk-in address7.2b The counter return7.3 The abandoned-draft sweep8. Caching9. BullMQ, Schedulers, and Async Work9.1 The cron entry point catches its own enqueue10. Realtime and Events11. Security, Auth, and Abuse Controls13. Error Handling14. Observability15. Testing and Validation16. Mandatory Backend Deep-Dive Pack16.1 Submodule Coverage Matrix16.2 UML and Architecture Diagram Pack16.3 Code Flow Narrative16.4 Data Layer Deep Dive16.5 Business Logic and Invariant Catalog16.6 Tradeoffs, Alternatives, and ADR Notes16.7 Operational Runbook16.8 Backend Risk Register17. Zero-Omission Backend Checklist18. Backend Completion Checklist19. Serial NumbersSee Also