Nano Store - Ecommerce Docs
Developer ResourcesPOS

POS API Reference

Complete API contracts for the POS module, including routes, auth, DTOs, responses, errors, examples, and integration notes.

POS - API Reference

Audience: Frontend engineers (admin panel), backend engineers, QA, and API consumers. Scope: The 20 admin-only counter routes under /api/admin/pos/ — sale drafting, completion, cancellation, customer/product/SKU lookup, receipt resend, till config and counter returns.

1. Documentation Evidence

AreaFiles InspectedWhat Was Verified
Controllersapps/api/src/modules/pos/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.tsRoutes, methods, guards, permissions, rate limits
DTOsadmin/sale/dto/*.ts, admin/lookup/dto/*.ts, admin/sale-support/dto/*.ts, admin/config/dto/*.ts, admin/return/dto/*.tsRequest, query, response, validation
Servicesshared/*.service.tsBehavior, transactions, error codes
Schemapackages/db/src/schema/pos/*.ts, packages/db/src/schema/order/enums.ts (order_refund_method)Tables, enums, constraints
Rate limits, errors, permissionscommon/guards/ip-throttler.config.ts, common/types/error-codes.ts (POS section), packages/db/src/authorization/permission-catalog.tsADMIN_POS_* budgets, error codes, PosReturns module
Jobs/cachepackages/jobs/src/index.ts, cache-invalidation.tags.tsOutbox jobs, inventory domain
Existing docsconsumer-handoff.md, Fumadocs formatsFrozen contract and format baseline

2. Module Summary

FieldValue
Module namepos
Module slugpos
Primary actorsadmin (operator), system (sweep)
API surfacesadmin only — no customer-facing route exists
Base route prefixes/api/admin/pos/sales, /api/admin/pos/lookup, /api/admin/pos/config
Auth modelJwtAuthGuard + RoleGuard + Pos_* permissions (counter returns also need PosReturns_CREATE)
PersistencePostgreSQL (pos_sale, pos_sale_item, pos_sale_event, pos_counter_returns + the online pipeline rows)
Runtime source of truthpos_sale row; the order is the Order module's
Sibling docsBackend, Features and flows

3. Concepts and Terminology

TermMeaningSource FileUsed By
saleNumberPOS-2026-000042, the till-roll reference printed on the receiptpos-sale-number.service.tsEvery response
statusdraft → picked_up/ordered or cancelled; no awaiting_paymentenums.tsEvery response
fulfilmentpickup/delivery — the discriminator behind every branchenums.tsFulfilment + complete
customerCreated§48 Customer Type — TRUE when this sale created the accountpos_sale.customer_createdSale response
paymentReferenceThe terminal/QR slip number; recorded, never validatedpos_sale.payment_referenceComplete
channel"pos" on the order/session; a label, never a branchsales_channel enumRead-only
invitationQueuedThe walk-in invite is queued; the token is never returnedPosWalkInCreatedDtoWalk-in response
orderNumberHS-2026-000042, printed on the receiptOrder moduleCompletion response
Counter Walk-inThe one shared customer (POS_COUNTER_WALK_IN_CUSTOMER_ID, no email, no phone) for a buyer who gives no contact; its id is returned by GET /configpos-counter-walk-in.ts, migration 0072Open sale, fulfilment, config
resendKeyThe Idempotency-Key of a receipt resend; becomes part of the notification jobIdPosSendReceiptPayloadReceipt resend
Counter returnOne call that records the return, the refund and the stock restore in one transactionpos-counter-return.service.tsReturns
unitNetMinorNet (after discount) price of one unit in minor units; a display estimate onlyPosReturnableLineDtoReturnable

4. API Surface Map

SurfaceMethodPathActorAuth/GuardPermissionControllerPurpose
AdminGET/api/admin/pos/lookup/customersOperatorJWT + RolePos_READPosLookupAdminControllerFind a customer by name/email/phone
AdminGET/api/admin/pos/lookup/productsOperatorJWT + RolePos_READPosLookupAdminControllerFind a sellable product by name/SKU
AdminPOST/api/admin/pos/salesOperatorJWT + RolePos_CREATEPosSaleAdminControllerOpen a draft (always pickup)
AdminGET/api/admin/pos/salesOperatorJWT + RolePos_READPosSaleAdminControllerList and filter sales
AdminGET/api/admin/pos/sales/{publicId}OperatorJWT + RolePos_READPosSaleAdminControllerOne sale with its lines
AdminGET/api/admin/pos/sales/{publicId}/timelineOperatorJWT + RolePos_READPosSaleAdminControllerThe audit trail
AdminPATCH/api/admin/pos/sales/{publicId}/customerOperatorJWT + RolePos_UPDATEPosSaleAdminControllerAttach an existing customer
AdminPOST/api/admin/pos/sales/{publicId}/customerOperatorJWT + RolePos_CREATEPosSaleAdminControllerCreate a walk-in customer
AdminPUT/api/admin/pos/sales/{publicId}/items/{productPublicId}OperatorJWT + RolePos_UPDATEPosSaleAdminControllerSet a line's FINAL quantity
AdminDELETE/api/admin/pos/sales/{publicId}/items/{productPublicId}OperatorJWT + RolePos_UPDATEPosSaleAdminControllerRemove a line
AdminPATCH/api/admin/pos/sales/{publicId}/fulfilmentOperatorJWT + RolePos_UPDATEPosSaleAdminControllerPickup or delivery (+ address)
AdminPOST/api/admin/pos/sales/{publicId}/completeOperatorJWT + RolePos_CREATEPosSaleAdminControllerTake payment, create the order
AdminPOST/api/admin/pos/sales/{publicId}/cancelOperatorJWT + RolePos_DELETEPosSaleAdminControllerAbandon a draft
AdminPATCH/api/admin/pos/sales/{publicId}/payment-methodOperatorJWT + RolePos_UPDATEPosSaleAdminControllerChange the tender of a draft
AdminGET/api/admin/pos/lookup/products/by-skuOperatorJWT + RolePos_READPosLookupAdminControllerResolve a scanned SKU to one configuration
AdminPOST/api/admin/pos/sales/{publicId}/receipt-emailOperatorJWT + RolePos_UPDATEPosSaleSupportAdminControllerRe-send the receipt email
AdminGET/api/admin/pos/sales/{publicId}/customer/addressesOperatorJWT + RolePos_UPDATEPosSaleSupportAdminControllerSaved addresses of the sale's customer
AdminGET/api/admin/pos/sales/{publicId}/returnableOperatorJWT + RolePos_READPosSaleSupportAdminControllerReturnable quantities and earlier counter returns
AdminPOST/api/admin/pos/sales/{publicId}/returnsOperatorJWT + RolePos_UPDATE + PosReturns_CREATEPosReturnAdminControllerAtomic counter return
AdminGET/api/admin/pos/configOperatorJWT + RolePos_READPosConfigAdminControllerTill configuration

5. Auth, Identity, and Permissions

SurfaceGuard/DecoratorIdentity ShapePermissionGuest AllowedNotes
AdminJwtAuthGuard, RoleGuardreq.user.idPos_CREATE/Pos_READ/Pos_UPDATE/Pos_DELETE; PosReturns_CREATE for counter returnsNoThe permission module is spelled Pos, never POS; Pos_READ exposes customer lookup, so it is grantable separately from Users_READ
  • ParseUUIDPipe on every :publicId and :productPublicId — a malformed id is a clean 400.
  • Rate limits key on the user, not the IP — every till in a shop shares one public address.
  • POST /sales/{publicId}/returns lists two permissions, and RoleGuard requires both (requiredPermissions.every): Pos_UPDATE AND PosReturns_CREATE. PosReturns is its own permission module so a cashier can refund a counter sale without any authority over online returns and refunds. The rows exist after pnpm --filter @nano-store/api permissions:sync.
  • A role that has Pos_* but not PosReturns_CREATE gets 403 PERMISSION_INSUFFICIENT on the returns route only.
Rate-limit constantBudget (per user)Routes
ADMIN_POS_WRITE180/minopen, customer (attach, walk-in), lines, fulfilment, payment-method, cancel
ADMIN_POS_COMPLETE30/mincomplete
ADMIN_POS_READ120/minsales list, customer addresses, returnable, config
ADMIN_READ30/minsale detail, timeline
ADMIN_POS_SEARCH120/mincustomer and product lookup
ADMIN_POS_SCAN300/minSKU lookup
ADMIN_POS_RECEIPT10/minreceipt resend
ADMIN_POS_RETURN20/mincounter return

6. DTO and Model Reference

6.1 OpenPosSaleDto — POST /sales

FieldTypeRequiredValidationExample
paymentMethodstringYes@IsIn(POS_PAYMENT_METHODS) — pos_cash/pos_card/pos_qr"pos_cash"
customerIduuidYes@IsUUID018f1e2a-...-000000000001

Deliberately no fulfilment field. Every sale opens as a pickup; delivery is chosen with PATCH /fulfilment, the only endpoint that can take an address in the same request. Sending fulfilment here is rejected by forbidNonWhitelisted.

6.2 AttachPosCustomerDto — PATCH /sales/{publicId}/customer

FieldTypeRequiredValidation
customerIduuidYes@IsUUID

6.3 CreatePosWalkInDto — POST /sales/{publicId}/customer

FieldTypeRequiredValidationNotes
namestringYes≤255, trimmed—
emailstringNo@IsEmail, ≤320, trimmed + lowercased; blank becomes absentThe account identifier and invite destination
phonestringNostring ≤20; blank becomes absentLocal or E.164. The service normalises it with normalizeToE164; a number that cannot be normalised is 400 POS_WALK_IN_PHONE_INVALID

Email or phone is required. Both absent is 400 POS_WALK_IN_CONTACT_REQUIRED (thrown by the service, not the DTO).

6.3a UpdatePosPaymentMethodDto — PATCH /sales/{publicId}/payment-method

FieldTypeRequiredValidationNotes
paymentMethodstringYes@IsIn(POS_PAYMENT_METHODS) — pos_cash/pos_card/pos_qrThe new tender

6.3b PosSkuLookupQueryDto — GET /lookup/products/by-sku

FieldTypeRequiredValidationNotes
skustringYestrimmed, length 1–64, printable ASCII (^[\x20-\x7E]+$)URL-encode it

6.4 UpsertPosLineDto — PUT /sales/{publicId}/items/{productPublicId}

FieldTypeRequiredValidationNotes
quantitynumberYes@IsInt, 1–99The FINAL quantity, not a delta. Scanning the same product twice sends 2, not two calls of 1
variantPublicIduuid v7No@IsOptional, @IsUUID("7")Which configuration of the product. Omit it for the product's default configuration. Naming one lets a single sale hold two configurations of the same product as two lines

RemovePosLineQueryDto — the query string of DELETE /sales/{publicId}/items/{productPublicId}: variantPublicId (uuid v7, optional). Omit it when the product is on the sale as exactly one line; name it when the product is on the sale as several.

6.5 SetPosFulfilmentDto — PATCH /sales/{publicId}/fulfilment

FieldTypeRequiredValidationNotes
fulfilmentstringYespickup/delivery—
addressPublicIduuidNo@IsUUIDMutually exclusive with address
addressobjectNoPosDeliveryAddressDtoMutually exclusive with addressPublicId
shippingAmountnumberNo@IsInt, 0 to 10,000,000Minor units; forced 0 for pickup

PosDeliveryAddressDto: districtId (uuid v7, the district publicId from GET /api/geo/districts — no longer an integer), municipalityName (≤120), ward (int 1–40), recipientName (≤120), recipientPhone (E.164 ^\+[1-9][0-9]{7,14}$), street (≤200), landmark (optional ≤200), postalCode (optional, five digits).

6.6 CompletePosSaleDto — POST /sales/{publicId}/complete

FieldTypeRequiredValidationNotes
paymentReferencestringNo≤128, trimmedPermitted for pos_card/pos_qr only — refused beside pos_cash. Recorded, never validated
serialsarrayNo≤100 entries, unique linePublicIdPer-line serial numbers. Accepted only when the goods leave with the customer now (counter pickup). See Serial Numbers
serials[].linePublicIduuid v7Yes@IsUUID("7"), lower-casedThe sale line's public id
serials[].serialNumbersstring[]Yes≤99 items, each ≤128 raw characters matching ^ *[\x21-\x7E]* *$Trimmed, blanks dropped, then 1-120 printable ASCII with no internal space

6.7 CancelPosSaleDto — POST /sales/{publicId}/cancel

FieldTypeRequiredValidationNotes
reasonstringYes@IsNotEmpty, ≤500, trimmedMandatory — an audit entry without a why answers nothing

6.8 ListPosSalesQueryDto — GET /sales

FieldTypeDefaultValidationNotes
pagenumber1≥1—
sizenumber201–100—
statusenum—draft/picked_up/ordered/cancelled—
fulfilmentenum—pickup/delivery—
paymentMethodenum—any payment_method§54 tender split
customerIduuid———
createdByAdminIduuid——§51/§54 sales-by-administrator
fromISO date—@IsDateStringInclusive lower bound on created_at
toISO date—@IsDateStringInclusive upper bound
searchstring—trimmed, length 2–40Case-insensitive substring match on sale_number or the linked order's order_number; % and _ are literal

6.9 PosLookupQueryDto — both lookup routes

FieldTypeRequiredValidationNotes
searchstringYes≤100, trimmed; ≥2 chars (else 400 VALIDATION_FAILED)Name/email/phone (customers), name/SKU (products)
pagenumberNo≥1—
sizenumberNo1–100—

6.10 Response DTOs

DTOShapeNotes
PosSaleDtopublicId, saleNumber, status, fulfilment, currency, customer { customerId, name, email, createdByThisSale }, payment { method, reference }, totals { subtotal, discountAmount, shippingAmount, grandTotal, totalQuantity, lineCount }, items[] { publicId, productPublicId, productName, variantPublicId, variantName, sku, quantity, unitPrice, mrp, lineTotal, discountAmount, netAmount, serialNumbers, releasedSerialNumbers }, orderNumber?, orderPublicId?, createdByAdminName?, createdAt, completedAt?, cancelledAt?Grouped by §47 business objects, not table rows; no integer PKs anywhere
PosSaleListItemDtopublicId, saleNumber, status, fulfilment, paymentMethod, grandTotal, totalQuantity, customerName?, createdByAdminName?, orderNumber?, createdAtList row
PosSaleEventDtopublicId, eventType, fromStatus?, toStatus?, actorName? (null after offboarding), reason?, createdAtTimeline row
PosSaleCompletionDtosale, orderNumber (print on the receipt), orderPublicIdCompletion
PosWalkInCreatedDtosale, customerId, invitationQueued: boolean, phoneDropped: booleaninvitationQueued is true only when the stored customer has an email. Never a token — a credential does not belong in a response body
PosCustomerMatchDtocustomerId, name, email?, phone?Lookup row — no addresses, no history
PosProductMatchDtoproductPublicId, name, sku, mrp, sellingPrice, effectivePrice, variantName, variantCount, maxSellingPrice, configurations[]Lookup row; mrp/sellingPrice are the default configuration's list prices, effectivePrice carries any live campaign
PosSkuMatchDtoproduct: PosProductMatchDto, matchedConfigurationPublicIdSKU lookup; send matchedConfigurationPublicId as variantPublicId on the line PUT
PosReceiptEmailQueuedDtoqueued: trueReceipt resend
AddressResponseDto[]the customer address book DTO from the address module, as a bare array (not { items })Customer addresses
PosConfigDtocounterWalkInCustomerId (uuid), paymentMethods (pos_cash/pos_card/pos_qr), returnWindowDays (7), currency ("NPR")Till config
PosReturnableDtoorderStatus, returnWindowEndsAt (ISO or null), lines[] { productPublicId, variantPublicId, productName, variantName, sold, returned, pending, returnable, unitNetMinor, serialNumbers }, counterReturns[] { returnPublicId, createdAt, createdByAdminName, reason, refund { publicId, amount, method, status, settlementReference } or null, lines[] { productPublicId, variantPublicId, quantity, refundAmount } }Returnable
PosCounterReturnDtoreturnPublicId, refund { publicId, amount, method, status: "settled", settlementReference } or null, lines[] { productPublicId, variantPublicId, productName, variantName, quantity, refundAmount }, sale: PosSaleDtoCounter return result

6.11 CreatePosCounterReturnDto — POST /sales/{publicId}/returns

FieldTypeRequiredValidationNotes
reasonstringYes@IsIn(orderReturnReasonEnum.enumValues)The order module's return reason enum
commentstringNotrimmed, ≤1000—
linesarrayYes1–50 items, each validatedNo money field — the server computes every amount from the order
lines[].productPublicIduuidYes@IsUUID—
lines[].variantPublicIduuid v7Yes@IsUUID("7")The configuration that was sold
lines[].quantitynumberYes@IsInt, 1–99Units returned now
lines[].serialNumbersstring[]No≤99 items, each ≤128 raw characters matching ^ *[\x21-\x7E]* *$Active serials of that line coming back; each is released as counter_return. A line returned in full releases the rest by itself. Part of the idempotency hash
refundMethodstringNocash / card_reversal / qr_reversalAny method on any sale; defaults from the sale's tender when omitted (see §8.20)
settlementReferencestringNotrimmed, length 1–120Terminal reversal reference

7. Enum Reference

EnumValueMeaningRuntime EffectSource
pos_sale_statusdraftBeing rung up; only editable stateLines may change; cancel is freeenums.ts
pos_sale_statuspicked_upPickup sale, goods handed overTerminal; order already delivered
pos_sale_statusorderedDelivery sale, order at confirmedTerminal for POS; Order owns the rest
pos_sale_statuscancelledAbandoned before completionOnly reachable from draft
pos_fulfilment_typepickupCustomer takes the goodsNo address, no shipping
pos_fulfilment_typedeliveryDelivered to an addressAddress + shipping required
pos_sale_event_typecreated / customer_assigned / customer_created / item_added / item_quantity_changed / item_removed / fulfilment_set / payment_recorded / completed / cancelledWhat happenedTimeline rows
sales_channelonline / posWhere the order came fromLabel only — never a branch, except the card/QR reversal guard on refund approvalcheckout/enums.ts
order_refund_methodcash / card_reversal / qr_reversal (POS subset)How a counter refund goes backcard_reversal and qr_reversal were added by migration 0070; the order module refuses them on a non-pos orderorder/enums.ts
payment_method (POS subset)pos_cash / pos_card / pos_qrThe counter tenderpos_card and pos_qr may carry a payment reference; pos_cash may notpayment/enums.ts

8. Endpoint Reference

8.1 GET /api/admin/pos/lookup/customers?search=

Purpose

Find a returning customer at the till by name, email or phone. Bounded and paginated: two characters minimum, and it returns identity fields only — never addresses or purchase history, which belong on the customer's own detail endpoint.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard
  • Permission: Pos_READ
  • Rate limit: ADMIN_POS_SEARCH (120/min per user)

Request

PartRequiredDetails
QueryYessearch (≥2 chars), page?, size? (≤100)

Response

200 — { items: [{ customerId, name, email?, phone? }] }. Only status = 'active', not soft-deleted, customers match.

Side Effects

None — a read over customers.

Error Cases

HTTPCodeCondition
400VALIDATION_FAILEDsearch shorter than 2 characters

8.2 GET /api/admin/pos/lookup/products?search=

Purpose

Find a sellable product by name or SKU. Only published, non-deleted products with selling_price <= mrp match — a counter must not become the way unpublished stock leaves the building.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_READ · Rate limit: ADMIN_POS_SEARCH (120/min per user)

Request

PartRequiredDetails
QueryYessearch (≥2 chars), page?, size?

Response

200 — { items: [PosProductMatchDto] } (shape in §6.10). Search also matches product_variants.sku. All money in minor units.

Side Effects

None.

Error Cases

HTTPCodeCondition
400VALIDATION_FAILEDsearch shorter than 2 characters

8.3 POST /api/admin/pos/sales

Purpose

Open a new draft. customerId is required — a sale cannot exist without a customer, so an unknown walk-in is created via POST /sales/{id}/customer first. Always opens as a pickup; delivery is chosen later with PATCH /fulfilment.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_CREATE · Rate limit: ADMIN_POS_WRITE

Request

{ "paymentMethod": "pos_cash", "customerId": "018f1e2a-0000-7000-8000-000000000001" }

Response

201 — the PosSaleDto with empty items, status: "draft", fulfilment: "pickup".

Side Effects

pos_sale row + created audit event, same transaction.

Error Cases

HTTPCodeCondition
400validationBad method/customer
404POS_SALE_NO_CUSTOMERThe customer does not exist or is deleted

Edge Cases

  • paymentMethod is changeable until completion — the field is on the sale, not fixed at open.
  • Sending fulfilment is rejected outright (forbidNonWhitelisted).

8.4 GET /api/admin/pos/sales

Purpose

The reconciliation list (§51). Filters: status, fulfilment, payment method, customer, administrator, a from/to date range on created_at, and search by sale number or order number.

from and to are read in Nepal time, and a date-only value means the whole local day.

@IsDateString() accepts a bare 2026-08-31, and new Date("2026-08-31") is midnight UTC — 05:45 in Kathmandu. As an inclusive upper bound that dropped everything sold after 05:45 on the last day asked for: a month-end reconciliation missed roughly three quarters of the 31st and read as a quiet day rather than a broken query. Nothing errored, and the total was plausible.

parseReportBoundary now expands from to the first instant of that day in Asia/Kathmandu and to to its last millisecond, so the two are contiguous — one day's end and the next day's start are 1ms apart, with no gap and no overlap.

A full timestamp is passed through untouched. A caller who sent an instant meant it, and widening that to a whole day is the mirror-image defect.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_READ · Rate limit: ADMIN_POS_READ (120/min per user)

Request

PartRequiredDetails
QueryNopage, size (≤100), status, fulfilment, paymentMethod, customerId, createdByAdminId, from, to, search (2–40 chars)

search is a case-insensitive substring match (ILIKE %term%, escaped with escapeLikePattern(normalizeSearchTerm())) on the sale number or on the linked order's number. The page count uses the same filter. A draft has no order, so it matches by sale number only.

Response

200 — { items: [PosSaleListItemDto], metadata: { count, page, size } }, newest first.

Side Effects

None. Page and total come from one transaction so they cannot disagree.

8.5 GET /api/admin/pos/sales/{publicId}

Purpose

One sale with its lines, for the detail view and the receipt.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_READ · Rate limit: ADMIN_READ

Response

200 — the full PosSaleDto. orderNumber/orderPublicId are NULL until completion.

Error Cases

HTTPCodeCondition
404POS_SALE_NOT_FOUNDThe sale id does not resolve

8.6 GET /api/admin/pos/sales/{publicId}/timeline

Purpose

The §42 audit trail, oldest first — who did what to this sale, in the order it happened.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_READ · Rate limit: ADMIN_READ

Response

200 — { events: [{ publicId, eventType, fromStatus?, toStatus?, actorName?, reason?, createdAt }] }. actorName is NULL for sweep cancellations and for offboarded administrators.

Error Cases

HTTPCodeCondition
404POS_SALE_NOT_FOUNDThe sale id does not resolve

8.7 PATCH /api/admin/pos/sales/{publicId}/customer

Purpose

Point the draft at a customer who already has an account (e.g. after correcting a mistaken walk-in creation).

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_UPDATE · Rate limit: ADMIN_POS_WRITE

Request

{ "customerId": "018f1e2a-0000-7000-8000-000000000001" }

Response

200 — the refreshed PosSaleDto.

Side Effects

Changing the customer resets the sale to a pickup: the saved address belonged to one person, so fulfilment, deliveryAddressId and shippingAmount are cleared together (CLEAR_DELIVERY_ON_CUSTOMER_CHANGE). The operator must re-choose delivery for the new customer — re-render the fulfilment step from the response, never assume it survived. customerCreated is reset to false.

This applies to POST /customer (create a walk-in) exactly as it does to PATCH /customer. Until 2026-08-17 it did not: creating a walk-in customer cleared only the address, leaving fulfilment = 'delivery' beside a NULL delivery_address_id, which chk_pos_sale_fulfilment_address refuses. The ordinary sequence — choose delivery, type the address, then discover the customer has no account — produced a 23514 at the till, and because the account, its account row and the outbox invite all rolled back with it, retrying hit the same error indefinitely. The reset had been applied to one of the two call sites.

Error Cases

HTTPCodeCondition
404POS_SALE_NOT_FOUND / POS_SALE_NO_CUSTOMERMissing sale / missing customer
409POS_SALE_NOT_DRAFTCancelled
409POS_SALE_ALREADY_COMPLETEDMoney already taken

8.8 POST /api/admin/pos/sales/{publicId}/customer

Purpose

Create a walk-in account and attach it to the sale — account, invitation and sale update are ONE transaction. Email or phone is required; the other is optional.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_CREATE · Rate limit: ADMIN_POS_WRITE

Request

{ "name": "Sita Sharma", "email": "sita.sharma@example.com", "phone": "9812345678" }

Phone-only:

{ "name": "Sita Sharma", "phone": "+9779812345678" }

Response

201 — { sale, customerId, invitationQueued, phoneDropped }.

  • invitationQueued is true only when the stored customer has an email. A phone-only customer gets no account row and no invitation; OTP login on that phone is the claim.
  • phoneDropped is true when the phone could not be saved: the phone belongs to a customer that cannot be attached (closed or unverified) and a free email was given, so the account is created with the email only. Show the cashier "Phone couldn't be saved for this customer".

Side Effects

  • customers row, plus an account row only when an email is stored (email verified FALSE — the operator typed it, nobody proved it; setting a password through the link is what proves it).
  • The sale is reset to a pickup (same reset as PATCH /customer), and a one-time walk-in delivery address on the previous customer is archived (§8.11).
  • Outbox row pos.walk_in_created, only when an email is stored (invite queued at creation, not completion).
  • Audit event customer_created (with the email and phoneDropped; never the token).

The account is created with NO password. The customer receives an emailed set-password link that never expires but is single-use. There is nothing for a client to display, copy or resend. Never suggest a password is emailed.

Error Cases

HTTPCodeCondition
400POS_WALK_IN_CONTACT_REQUIREDNeither email nor phone
400POS_WALK_IN_PHONE_INVALIDThe phone cannot be normalised to E.164
409POS_CUSTOMER_CONTACT_EXISTSThe email or phone belongs to an attachable customer. details: { customerId, name, matchedOn: "email" | "phone" } — attach that customer with PATCH /customer instead
409POS_CUSTOMER_CONTACT_CONFLICTThe email and the phone belong to two different customers
409POS_CUSTOMER_CONTACT_UNAVAILABLEThe owner is closed, deleted, banned or unverified, a phone-only request hits a phone that is not attachable, or two tills raced for the same contact. No details
404POS_SALE_NOT_FOUNDMissing sale
409POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETEDNot a draft

Edge Cases

  • A 23505 on email or phone is caught in a savepoint and re-resolved once; a second collision answers POS_CUSTOMER_CONTACT_UNAVAILABLE.
  • POS_CUSTOMER_EMAIL_TAKEN is no longer thrown by this route.

8.9 PUT /api/admin/pos/sales/{publicId}/items/{productPublicId}

Purpose

Set the quantity of one product on the draft. The body is the FINAL quantity, not a delta — scanning the same barcode twice sends quantity: 2, not two calls of 1. Idempotent: sending the same quantity twice changes nothing.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_UPDATE · Rate limit: ADMIN_POS_WRITE

Request

{ "quantity": 2, "variantPublicId": "019ff58f-0956-722f-80c9-b5d7fc484b08" }

variantPublicId is optional. Without it the product's default configuration is used.

Response

200 — the refreshed PosSaleDto with recomputed totals. The line freezes the product's current sellingPrice (and mrp) — a counter line is a price snapshot, unlike a cart line.

Side Effects

pos_sale_item upsert (ON CONFLICT (pos_sale_id, variant_id) DO UPDATE), totals recomputed from the persisted lines, audit event item_added/item_quantity_changed.

Error Cases

HTTPCodeCondition
400POS_QUANTITY_OUT_OF_RANGENot a whole number in 1–99
404POS_PRODUCT_NOT_SELLABLEProduct missing, unpublished or deleted
404POS_VARIANT_NOT_SELLABLEvariantPublicId was sent and that configuration is not available for the product
409POS_PRODUCT_NOT_SELLABLEProduct priced above its MRP
404POS_SALE_NOT_FOUNDMissing sale
409POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETEDNot a draft

8.10 DELETE /api/admin/pos/sales/{publicId}/items/{productPublicId}

Purpose

Take an item back off the counter before payment. The line is hard-deleted — the record of what the customer actually bought is checkout_session_item and then order_item.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_UPDATE · Rate limit: ADMIN_POS_WRITE

Request

Query string: variantPublicId (uuid v7, optional). Omit it when the product is on the sale as exactly one line.

Response

200 — the refreshed PosSaleDto with recomputed totals.

Error Cases

HTTPCodeCondition
404POS_LINE_NOT_FOUNDThe product, or the named configuration, is not on this sale
409POS_LINE_VARIANT_REQUIREDThe product is on the sale as more than one configuration and variantPublicId was not sent
404POS_SALE_NOT_FOUNDMissing sale
409POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETEDNot a draft

8.11 PATCH /api/admin/pos/sales/{publicId}/fulfilment

Purpose

Choose how the goods leave the shop. The only endpoint that can take an address in the same request — either a saved one (addressPublicId) or a new one (address), which is saved to the customer's own address book.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_UPDATE · Rate limit: ADMIN_POS_WRITE

Request

Pickup:

{ "fulfilment": "pickup" }

Delivery with a new address:

{
  "fulfilment": "delivery",
  "shippingAmount": 15000,
  "address": {
    "districtId": "019a1b2c-3d4e-7f00-8a00-000000000027", "municipalityName": "Lalitpur Metropolitan City", "ward": 5,
    "recipientName": "Sita Sharma", "recipientPhone": "+9779812345678",
    "street": "Jhamsikhel, Ward 5", "landmark": "Opposite the community school",
    "postalCode": "44700"
  }
}

Delivery with a saved address:

{ "fulfilment": "delivery", "addressPublicId": "018f1e2a-0000-7000-8000-000000000009" }

districtId is the district publicId (uuid v7). The service resolves it to the integer id before the shared fulfilment code runs. recipientPhone must match ^\+[1-9][0-9]{7,14}$ at the DTO; the service then runs normalizeToE164 on it.

Response

200 — the refreshed PosSaleDto.

Side Effects

  • Pickup: clears the address and forces shippingAmount to 0.
  • Delivery: resolves the saved address (scoped to THIS customer in the query) or inserts a new customer_addresses row with is_default: false — the POS transaction deliberately does not take the default-address advisory lock.
  • grandTotal is recomputed in the same statement that writes shippingAmount, from the row's own subtotal and discountAmount.
  • Counter Walk-in sales use a one-time address. When the sale's customer is the shared Counter Walk-in, the typed address is inserted into customer_addresses for that customer and archived (deleted_at) when the sale completes, is cancelled or is swept, when the address is replaced, when the fulfilment goes back to pickup, and when the customer changes. It is never listed (§8.15). The order keeps its own shipping snapshot; completion reads the address before it is archived, in the same transaction. addressPublicId is refused for the walk-in.

That last point is not an optimisation. chk_pos_sale_grand_total_matches asserts grand_total = subtotal − discount_amount + shipping_amount, and the constraint is not deferrable — PostgreSQL evaluates it at the end of the statement, not at commit.

Writing shipping_amount alone and repairing the total on the next line therefore cannot work: the first statement is already rejected and the whole transaction aborts, taking the newly-inserted address row with it. That was the behaviour until 2026-08-17, which meant no non-zero delivery charge could ever be saved — every attempt was a bare 23514 at the till.

It survived type-check, lint, build, five rule gates and the full integration suite because every delivery fixture used shippingAmount: 0, where the identity holds trivially. When adding a fixture for a money path, give it a non-zero value.

Error Cases

HTTPCodeCondition
409POS_DELIVERY_ADDRESS_REQUIREDDelivery with no address — or both addressPublicId AND address (mutually exclusive)
404POS_ADDRESS_NOT_FOUNDThe address is not this customer's
404POS_DISTRICT_NOT_FOUNDaddress.districtId matches no district
400POS_RECIPIENT_PHONE_INVALIDrecipientPhone passes the DTO pattern but normalizeToE164 returns null
409POS_WALK_IN_SAVED_ADDRESS_NOT_ALLOWEDaddressPublicId sent while the customer is the Counter Walk-in
503POS_COUNTER_CUSTOMER_MISSINGDelivery for the Counter Walk-in, and that row is missing or altered
404POS_SALE_NOT_FOUNDMissing sale
409POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETEDNot a draft

8.12 POST /api/admin/pos/sales/{publicId}/complete

Purpose

Take the money and produce the order — ONE transaction: stock moves, the payment is recorded, the order is created, and for a pickup the goods are handed over. There is no state in which a customer has paid and no order exists. Returns the order number for the receipt.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_CREATE · Rate limit: ADMIN_POS_COMPLETE (30/min — each call takes money)

Request

{
  "paymentReference": "TXN-88213",
  "serials": [
    {
      "linePublicId": "019ff590-0000-7000-8000-000000000131",
      "serialNumbers": ["356938035643809", "356938035643817"]
    }
  ]
}

serials is optional and {} stays valid. It is refused with POS_SERIALS_NOT_ALLOWED on a delivery sale. The checks run before stock is reserved or an order number is taken, so a refused serial rolls the whole completion back. Full rules: Serial Numbers.

paymentReference is optional and permitted only for pos_card and pos_qr. Sending one with pos_cash is rejected. It is recorded, never validated — the platform does not check it against any provider, and a client must not present it as verified.

Response

200 — { sale (status picked_uporordered), orderNumber, orderPublicId }.

Side Effects

Cart (born converted), checkout session (born completed, channel: "pos"), frozen checkout_session_items, settled payment_attempt (born succeeded, gateway_transaction_id = POS-{saleNumber}), reservation finalize, order (createFromCheckout with executor: tx), pickup hand-over to delivered, outbox pos.sale_completed, events payment_recorded + completed, and post-commit invalidation of the inventory cache domain.

Error Cases

HTTPCodeCondition
409POS_SALE_EMPTYNo lines
409POS_SALE_NO_CUSTOMERNo customer attached
409POS_DELIVERY_ADDRESS_REQUIREDDelivery with no address
409POS_PRODUCT_NOT_SELLABLEA product is no longer published
409POS_PRODUCT_PRICE_CHANGEDA price moved mid-sale — tell the operator to speak to the customer; remove and re-add to charge the new price
409POS_INSUFFICIENT_STOCKSomeone else took the last one — show remaining stock, let the operator reduce the quantity
409POS_PAYMENT_REFERENCE_NOT_ALLOWEDReference sent with cash
409POS_SALE_ALREADY_COMPLETEDThe money was already taken — do not retry, show the existing order number
409POS_ADDRESS_NOT_FOUNDThe configured store district does not exist (pickup shipping resolve)
409POS_SERIAL_LINE_NOT_FOUNDA serials[].linePublicId is not on the sale — re-fetch the sale
409POS_SERIALS_NOT_ALLOWEDSerials sent on a sale that is not handed over now (delivery) — record them at dispatch
409ORDER_SERIAL_COUNT_MISMATCHMore serials than units on a line
409ORDER_SERIAL_ALREADY_RECORDEDA serial is already active for the same product, or repeated in the request; details.conflicts / details.duplicates name them
400ORDER_SERIAL_INVALIDA serial is not 1-120 printable ASCII without spaces; details.index is its position

POS_PRODUCT_PRICE_CHANGED and POS_INSUFFICIENT_STOCK mean nothing was charged and nothing was reserved — the whole completion rolled back, so the sale is still a live draft.

Edge Cases

  • Stock: completion is the only POS step that touches stock. It reserves and finalizes in the same transaction. Drafts, cancel and the abandoned-draft sweep touch none; only a counter return restores it (§8.20).
  • Replayed completion: the four partial unique indexes (uq_pos_sale_{cart,checkout_session,payment_attempt,order}_id) plus the guarded WHERE status = 'draft' finalise make a retry a 409, never a second charge.
  • A delivery sale's order stays at confirmed for the normal lifecycle; a pickup's order is driven straight to delivered (return window starts, purchase reviewable).

8.13 POST /api/admin/pos/sales/{publicId}/cancel

Purpose

Abandon a draft before any money has moved. Only reachable from draft — once completed, the correction is an order cancellation and refund, owned by the Order module.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_DELETE · Rate limit: ADMIN_POS_WRITE

Request

{ "reason": "Customer changed their mind" }

Response

200 — the PosSaleDto with status: "cancelled".

Error Cases

HTTPCodeCondition
400validationBlank or missing reason
404POS_SALE_NOT_FOUNDMissing sale
409POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETEDNot a draft

8.14 PATCH /api/admin/pos/sales/{publicId}/payment-method

Purpose

Change the tender of a draft (cash, card or QR) without reopening the sale.

Source Evidence

pos-sale-admin.controller.ts (setPaymentMethod), pos-sale-draft.service.ts (setPaymentMethod).

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_UPDATE · Rate limit: ADMIN_POS_WRITE

Request

{ "paymentMethod": "pos_card" }

Response

200 — the refreshed PosSaleDto.

Side Effects

  • Updates payment_method, bumps version and updated_at (which is the abandoned-draft sweep clock). Switching to pos_cash clears any payment_reference.
  • No timeline event is written (the event enum would need a migration). The change is logged at INFO with the admin id.
  • Idempotent by value: sending the current method succeeds.

Error Cases

HTTPCodeCondition
400VALIDATION_FAILEDValue is not pos_cash/pos_card/pos_qr
404POS_SALE_NOT_FOUNDMissing sale
409POS_SALE_ALREADY_COMPLETEDThe sale is completed
409POS_SALE_NOT_DRAFTThe sale is cancelled

8.15 GET /api/admin/pos/sales/{publicId}/customer/addresses

Purpose

List the saved addresses of the sale's customer so the till can offer them for a delivery.

Source Evidence

pos-sale-support-admin.controller.ts (listCustomerAddresses), pos-sale-support-admin.service.ts.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_UPDATE · Rate limit: ADMIN_POS_READ

Response

200 — AddressResponseDto[], a bare array. Only status: "active" addresses (archived ones, including the one-time walk-in address, are excluded), unpaginated.

Error Cases

HTTPCodeCondition
404POS_SALE_NOT_FOUNDMissing sale
409POS_SALE_NOT_DRAFTThe sale is not a draft
404POS_WALK_IN_NO_ADDRESS_BOOKThe customer is the Counter Walk-in; type the address into PATCH /fulfilment instead

8.16 GET /api/admin/pos/lookup/products/by-sku?sku=

Purpose

Resolve a scanned SKU to one sellable configuration. Use it for barcode-scanner input that emits the SKU.

Source Evidence

pos-lookup-admin.controller.ts (findBySku), pos-sale-line.service.ts (resolveSellableBySku), pos-lookup.service.ts (findBySku).

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_READ · Rate limit: ADMIN_POS_SCAN (300/min per user)

Request

PartRequiredDetails
QueryYessku, 1–64 printable ASCII characters, trimmed, URL-encoded by the client

Response

200 — { product: PosProductMatchDto, matchedConfigurationPublicId }.

Edge Cases

  • Matching is an equality on btrim(sku) over the variant table and the product table together.
  • A product-table hit resolves to the product's default configuration.
  • If nothing matches exactly, the lookup retries case-insensitively and succeeds only when exactly one product and at most one variant row match. Several case-insensitive matches are a 404, never a guess.
  • Sellability reuses the line rules (published, priced, not deleted).

Error Cases

HTTPCodeCondition
400VALIDATION_FAILEDsku is empty, longer than 64 or not printable ASCII
404POS_SKU_NOT_FOUNDNo match, or several case-insensitive matches
409POS_SKU_AMBIGUOUSAn exact match hits two different products or two variant rows. details.candidates lists them
404POS_VARIANT_NOT_SELLABLEThe matched configuration is not sellable
404 / 409POS_PRODUCT_NOT_SELLABLEThe product is missing or not published (404 when missing, 409 when its status blocks sale)

8.17 POST /api/admin/pos/sales/{publicId}/receipt-email

Purpose

Re-send the receipt email of a completed sale to the sale's customer.

Source Evidence

pos-sale-support-admin.controller.ts (resendReceipt), pos-sale-support-admin.service.ts, pos-mail-queue.service.ts (queueReceiptResend), pos-email.processor.ts, pos-idempotency-key.guard.ts.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_UPDATE · Rate limit: ADMIN_POS_RECEIPT (10/min per user)
  • Header Idempotency-Key: <uuid> is required. Send a new key per resend.

Request

No body.

Response

201 — { "queued": true }.

Side Effects

  • One outbox row pos.receipt_resend_requested with dedupe_key = "<salePublicId>:resend:<Idempotency-Key>", written in the same transaction as the cap check, under the sale lock.
  • The worker sends the receipt with jobId = pos-receipt-<salePublicId>-<resendKey>. The key is in the id because BullMQ drops a job whose id already exists, which silently lost the second resend.
  • Logged at INFO with the admin id.

Error Cases

HTTPCodeCondition
400POS_IDEMPOTENCY_KEY_INVALIDThe header is present but not a UUID
400IDEMPOTENCY_KEY_REQUIREDThe header is absent
404POS_SALE_NOT_FOUNDMissing sale
409POS_RECEIPT_NOT_AVAILABLEThe sale is not picked_up or ordered
409POS_CUSTOMER_NO_EMAILThe customer has no email (a phone-only walk-in, or the Counter Walk-in)
409POS_RECEIPT_RESEND_LIMIT3 resends already queued for this sale in the last 24 hours (counted from outbox rows)

8.18 GET /api/admin/pos/config

Purpose

Give the till the values it needs at startup.

Source Evidence

pos-config-admin.controller.ts, pos-config-admin.service.ts.

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_READ · Rate limit: ADMIN_POS_READ

Response

200 — PosConfigDto:

{
  "counterWalkInCustomerId": "01a2076e-fe59-73dc-9d64-ee3ce2edb086",
  "paymentMethods": ["pos_cash", "pos_card", "pos_qr"],
  "returnWindowDays": 7,
  "currency": "NPR"
}

Pass counterWalkInCustomerId as customerId to POST /sales when the buyer gives no contact. returnWindowDays is the order module's ORDER_RETURN_WINDOW_DAYS.

Error Cases

HTTPCodeCondition
503POS_COUNTER_CUSTOMER_MISSINGThe Counter Walk-in row is soft-deleted, not active, banned, or has an email or phone

8.19 GET /api/admin/pos/sales/{publicId}/returnable

Purpose

Show what can still be returned on a completed sale, and the counter returns already made.

Source Evidence

pos-sale-support-admin.controller.ts (getReturnable), pos-counter-return.service.ts (getReturnable).

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permission: Pos_READ · Rate limit: ADMIN_POS_READ

Response

200 — PosReturnableDto (shape in §6.10).

  • returnable = max(deliveredQuantity - pending - returned, 0). A delivery order that is not yet delivered returns 200 with every returnable: 0.
  • unitNetMinor = floor(netAmount / quantity). The client's refund estimate is returnable × unitNetMinor; the committed amount comes from the return route.
  • counterReturns is newest first.

Error Cases

HTTPCodeCondition
404POS_SALE_NOT_FOUNDMissing sale
409POS_COUNTER_RETURN_NOT_ALLOWEDdetails.reason = "not_completed": the sale is a draft or cancelled

8.20 POST /api/admin/pos/sales/{publicId}/returns

Purpose

Take goods back at the counter: the return, the refund and the stock restore are ONE transaction.

Source Evidence

pos-return-admin.controller.ts, pos-return-admin.service.ts, pos-counter-return.service.ts (createCounterReturn, createInTx), pos-counter-return.util.ts, order-refund-settlement.service.ts (approveInTx).

Auth and Permissions

  • Auth: JwtAuthGuard + RoleGuard · Permissions: Pos_UPDATE and PosReturns_CREATE · Rate limit: ADMIN_POS_RETURN (20/min per user)
  • Header Idempotency-Key: <uuid> is required. Generate it once per confirm dialog so a retry replays instead of returning twice.

Request

{
  "reason": "changed_mind",
  "comment": "Box unopened",
  "lines": [
    { "productPublicId": "018f1e2a-0000-7000-8000-000000000012", "variantPublicId": "019ff58f-0956-722f-80c9-b5d7fc484b08", "quantity": 1 }
  ],
  "refundMethod": "cash",
  "settlementReference": "TXN-REV-88213"
}

refundMethod and settlementReference are optional.

Response

201 — PosCounterReturnDto: { returnPublicId, refund, lines, sale }. refund is null when nothing on the returned lines was refundable. refund.status is always settled.

Side Effects

In one transaction, under the sale lock, with withSerializationRetry:

  1. Open the return on the customer's behalf, approve it, receive it and inspect it with every line accepted. Inspection restocks each accepted unit through InventoryWriteService.adjustStock (source: "return").
  2. If a refund was created, approve it with the refund method and settle it with the reference.
  3. Insert the pos_counter_returns row (the durable idempotency record).

Waivers for counter returns only: the order module's separation of duties (inspector must differ from approver) is not applied, so one admin performs every step; each step is still called with that admin id. RETURN_REQUESTED (and its admin notification) and RETURN_DECIDED are suppressed; REFUND_SETTLED is still sent.

After commit, and only for a fresh return: the POS cache domain is invalidated and an activity record pos.counter_return.created (module PosReturns) is written. A failure of that audit write is logged and never fails the return.

Refund method. Any of cash, card_reversal and qr_reversal is allowed on any POS sale, whatever tender paid for it. When refundMethod is omitted it defaults from the sale's tender: pos_cash gives cash, pos_card gives card_reversal, pos_qr gives qr_reversal. A card or QR reversal still requires the order's channel to be pos.

Settlement reference. When absent, the server records POS <saleNumber> RET <last 12 chars of returnPublicId> (no terminal ref). This is what makes a cash refund (which has no terminal) settle without input.

Replay. The same Idempotency-Key on the same sale with the same body returns the stored result with no second return, refund or stock movement, even when the Redis idempotency record has expired, because pos_counter_returns is unique on (pos_sale_id, idempotency_key). The same key with a different body answers 409 IDEMPOTENCY_KEY_CONFLICT. The sale in a replay is read fresh.

Error Cases

HTTPCodeCondition
400POS_IDEMPOTENCY_KEY_INVALIDHeader present but not a UUID
400IDEMPOTENCY_KEY_REQUIREDHeader absent
400VALIDATION_FAILEDBody fails the DTO (no lines, more than 50, bad uuid, quantity outside 1–99, unknown reason or refund method)
403PERMISSION_INSUFFICIENTMissing Pos_UPDATE or PosReturns_CREATE
404POS_SALE_NOT_FOUNDMissing sale
409IDEMPOTENCY_KEY_CONFLICTKey reused with a different payload
409IDEMPOTENCY_REQUEST_IN_PROGRESSSame key still running
409POS_COUNTER_RETURN_NOT_ALLOWEDSee details.reason below

POS_COUNTER_RETURN_NOT_ALLOWED carries details.reason:

reasonMeaningExtra details
not_completedDraft, cancelled, or an order not yet delivered (including a delivery sale still in transit)—
window_closedThe 7-day return window has ended, or the order is completed—
fully_returnedThe order status is returned—
line_not_in_saleA (product, variant) pair is not on the orderproductPublicId, variantPublicId
quantity_exceeds_returnableMore units than deliveredQuantity - pending - returnedproductPublicId, variantPublicId, returnable
duplicate_lineThe same (product, variant) appears twice (compared case-insensitively)—
serial_not_on_lineA picked serial is not an active serial of that lineproductPublicId, variantPublicId
serial_count_exceeds_quantityMore serials picked than units returned, or a serial picked twiceproductPublicId, variantPublicId

The message is fixed copy per reason, never a composed service's text.

Edge Cases

  • Two tills returning the same sale serialise on the sale lock. A 23505 on uq_pos_counter_returns_sale_key re-runs the transaction once; the replay check then finds the row.
  • The order module also guards the refund itself: approving card_reversal or qr_reversal on a non-pos order is 409 ORDER_REFUND_METHOD_NOT_ALLOWED.

9. Flow Diagrams

9.1 Route Ownership

9.2 Request Sequence (complete)

9.3 Error Branch (completion)

EndpointPagination TypeDefault SizeMax SizeSort FieldsFiltersResult Cap
GET /api/admin/pos/salesoffset page/size20100createdAt DESC, id DESC (fixed)status, fulfilment, paymentMethod, customerId, createdByAdminId, from, to, search (2–40 chars, sale or order number)10k/100k rows (offset cap, ~3 years at 100 sales/day)
GET /api/admin/pos/lookup/customersoffset page/size20100name ASC, id ASC (fixed)search (≥2 chars, ILIKE)—
GET /api/admin/pos/lookup/productsoffset page/size20100name ASC, id ASC (fixed)search (≥2 chars, ILIKE on name and on product and variant SKU)—
GET /api/admin/pos/sales/{publicId}/customer/addressesnone (full active list)——address book order——

11. Caching, Jobs, and External Integrations

IntegrationUsed?DetailsSource
Redis cacheYes (invalidation only)inventory domain cleared after a completed sale (triggerForWrite, post-commit, fire-and-forget)pos.constants.ts
BullMQYesQueueName.POS — pos.send_receipt (completion, and resends with resendKey), pos.send_walk_in_invite (outbox, same tx), pos.sweep_abandoned_drafts (hourly cron, direct). One @Processor (concurrency 3) dispatches via an exhaustive record; HttpException = deterministic failure, never retriedpos-queue.processor.ts
External APINoPayment references are recorded, never validated—

13. Mandatory Deep API Documentation Pack

13.1 Route-by-Route Completeness Matrix

RouteController MethodDTOsService MethodGuardsPermissionsCacheJobsDB TouchesErrorsDocumented?
GET /api/admin/pos/lookup/customerssearchCustomersPosLookupQueryDtoPosLookupService.searchCustomersJWT+Role+ThrottlePos_READ——customers400Yes
GET /api/admin/pos/lookup/productssearchProductsPosLookupQueryDtoPosLookupService.searchProductsJWT+Role+ThrottlePos_READ——products400Yes
POST /api/admin/pos/salesopenOpenPosSaleDtoPosSaleDraftService.openJWT+Role+ThrottlePos_CREATE——pos_sale, event400/404Yes
GET /api/admin/pos/salesfindAllListPosSalesQueryDtoPosSaleQueryService.findAllJWT+Role+ThrottlePos_READ——pos_sale + joins—Yes
GET /api/admin/pos/sales/{publicId}findOne—PosSaleQueryService.findOneJWT+Role+ThrottlePos_READ——pos_sale, items404Yes
GET /api/admin/pos/sales/{publicId}/timelinefindTimeline—PosSaleQueryService.findTimelineJWT+Role+ThrottlePos_READ——events404Yes
PATCH /api/admin/pos/sales/{publicId}/customerattachCustomerAttachPosCustomerDtoPosSaleDraftService.attachCustomerJWT+Role+ThrottlePos_UPDATE——pos_sale, event404/409Yes
POST /api/admin/pos/sales/{publicId}/customercreateWalkInCreatePosWalkInDtoPosSaleDraftService.createWalkInCustomerJWT+Role+ThrottlePos_CREATE—outbox invite (email only)customers, account, pos_sale, outbox, event400/404/409Yes
PUT /api/admin/pos/sales/{publicId}/items/{productPublicId}upsertLineUpsertPosLineDtoPosSaleLineService.upsertLineJWT+Role+ThrottlePos_UPDATE——pos_sale_item, pos_sale, event400/404/409Yes
DELETE /api/admin/pos/sales/{publicId}/items/{productPublicId}removeLine—PosSaleLineService.removeLineJWT+Role+ThrottlePos_UPDATE——pos_sale_item, pos_sale, event404/409Yes
PATCH /api/admin/pos/sales/{publicId}/fulfilmentsetFulfilmentSetPosFulfilmentDtoPosSaleDraftService.setFulfilmentJWT+Role+ThrottlePos_UPDATE——pos_sale, address, event404/409Yes
POST /api/admin/pos/sales/{publicId}/completecompleteCompletePosSaleDtoPosSaleCompletionService.completeJWT+Role+ThrottlePos_CREATEinventory (after commit)outbox receipt7 tables + events + outbox409 setYes
POST /api/admin/pos/sales/{publicId}/cancelcancelCancelPosSaleDtoPosSaleDraftService.cancelJWT+Role+ThrottlePos_DELETE——pos_sale, event, customer_addresses (archive)400/404/409Yes
PATCH /api/admin/pos/sales/{publicId}/payment-methodsetPaymentMethodUpdatePosPaymentMethodDtoPosSaleDraftService.setPaymentMethodJWT+Role+ThrottlePos_UPDATE——pos_sale400/404/409Yes
GET /api/admin/pos/lookup/products/by-skufindBySkuPosSkuLookupQueryDtoPosLookupService.findBySkuJWT+Role+ThrottlePos_READ——products, product_variants400/404/409Yes
POST /api/admin/pos/sales/{publicId}/receipt-emailresendReceipt— (header)PosSaleSupportAdminService.resendReceiptJWT+Role+Throttle+Key guard+IdempotencyPos_UPDATE—outbox receipt resendpos_sale, customers, outbox_events400/404/409Yes
GET /api/admin/pos/sales/{publicId}/customer/addresseslistCustomerAddresses—PosSaleSupportAdminService.listCustomerAddressesJWT+Role+ThrottlePos_UPDATE——customer_addresses404/409Yes
GET /api/admin/pos/sales/{publicId}/returnablegetReturnable—PosCounterReturnService.getReturnableJWT+Role+ThrottlePos_READ——pos_sale, order_items, pos_counter_returns404/409Yes
POST /api/admin/pos/sales/{publicId}/returnscreateCreatePosCounterReturnDtoPosCounterReturnService.createCounterReturnJWT+Role+Throttle+Key guard+IdempotencyPos_UPDATE + PosReturns_CREATEPOS domain (after commit)order notificationsorder_return*, order_refund*, inventory, pos_counter_returns400/403/404/409Yes
GET /api/admin/pos/configgetConfig—PosConfigAdminService.getConfigJWT+Role+ThrottlePos_READ——customers503Yes

13.2 Request/Response Exhaustiveness

Covered in §8: minimal and full payloads for every body endpoint (§6, §8.3/8.8/8.11/8.12), the final-quantity semantics of PUT (§8.9), the mutually-exclusive address fields (§8.11), the pickup-reset on customer change (§8.7), the never-expiring single-use invite (§8.8), the full PosSaleDto shape (§6.10), every nullable field, and per-endpoint error tables with the exact codes and the "nothing was charged" meaning of the two completion conflicts (§8.12).

13.3 API Diagram Pack

Route ownership (§9.1), completion sequence (§9.2), completion error tree (§9.3), plus the activity/till flow and queue topology in the feature and backend docs.

13.4 Consumer Integration Notes

ConsumerRequired KnowledgeFailure HandlingContract Stability
Admin panel (till)20 routes, Pos_* permissions, final-quantity PUT, pickup-first drafts, recorded:false-style semantics for references409s → re-fetch the sale; POS_SALE_ALREADY_COMPLETED → show the order number, never retryStable
Admin panel (reports)GET /sales filters, integer minor units, customerCreated, createdByAdminIdOffset cap at 10k rowsStable
Admin panel (walk-in)No password ever; invitationQueued and phoneDropped are the whole answer; never expect a token409 POS_CUSTOMER_CONTACT_EXISTS → attach details.customerId with PATCH /customerStable
Admin panel (counter return)GET /returnable for quantities, then POST /returns with one Idempotency-Key per confirm dialog; estimate refund as returnable × unitNetMinorPOS_COUNTER_RETURN_NOT_ALLOWED → branch on details.reason; retry with the SAME key after a network failureStable
Admin panel (order rendering)Refund method may now be card_reversal / qr_reversal — add labelsDegrades to a raw enum, never an errorStable
Storefront frontendNothing changes. order.channel is "online" for every customer-placed order; the new payment methods never appear in the customer-selectable list—Stable
Admin panel (order rendering)order.payment_method may now be pos_cash/pos_card/pos_qr — add labels or it shows a raw enumDegrades to an ugly label, never an errorStable
QAConstraint invariants (status/key pairs, pickup no-shipping), one-transaction completion, replay safetyReproduce via the exact codesStable

13.5 API Tradeoffs and Rationale

DecisionChosen BehaviorAlternatives ConsideredWhy This TradeoffRiskMitigation
No fulfilment on openDrafts always open pickupAccepting deliveryopen() cannot supply an address; the old field was a guaranteed 23514One extra tapRe-render fulfilment from responses
PUT replaces quantityIdempotent final quantityPOST incrementA till types a numberDouble-scan confusionDocumented; ON CONFLICT
customerId required at openNo customerless draftAnonymous salesEvery sale belongs to an accountExtra step for new walk-insWalk-in endpoint first
Reference never validatedRecorded as enteredProvider check§17 leaves verification with the operatorFalse "verified" impressionDocumented, refused beside cash
Completion is one txAll-or-nothingPipeline with compensationThe paid-without-order state is not cleanableLong lock scopeAscending lock order
Customer change resets to pickupAddress/fulfilment/shipping clearedPartial clearThe old address is not this person'sRe-picking deliveryExplicit in docs
Walk-in invite never expiresFar-future sentinel, single use24h TTLOwner policy; support dead-endLong-lived if stolenSingle use, no OTP
New address not the defaultis_default: falseTaking the default lockPOS tx must not race the address advisory lockMinor UXCustomer promotes later

13.6 API Change Impact

ChangeAffected ConsumersBackend ImpactData ImpactMigration Needed?Compatibility Plan
order.channel / checkout_session.channel addedStorefront (ignores), reportingColumn + enumNone — defaults onlineNoAdditive; existing rows unaffected
payment_method gains 3 valuesAdmin order rendererEnum + gateway labelsNoneNoLabel the new values; storefront list unchanged
order_refund_method gains card_reversal, qr_reversalAdmin order renderer, financeEnum; guard in refund approvalNoneYes (0070, additive)Label the new values
pos_counter_returns table, Counter Walk-in rowTillNew table (0071), data row (0072)New rows on each counter returnYesAdditive
districtId on PATCH /fulfilment becomes a uuid v7TillDTONoneNoBreaking for a client that sent the integer id; send the district publicId
POST /customer body: email optional, phone accepted; status 201TillDTO + serviceNoneNoHandle phoneDropped and the new 409 codes
Any future lookup changeTillPosLookupServiceNoneNoContract frozen in consumer-handoff
Future barcode columnTillProduct schemaMigrationYes (backend change, not made)Scanner emits SKU today

14. Zero-Omission API Checklist

  • Every controller route is documented (§4, §8, §13.1).
  • Every parent route prefix and runtime URL is documented (§2, §4).
  • Every DTO field, nested field, enum, default, transform, and validator is documented (§6, §7).
  • Every response field, nullable field, generated field, and omitted raw entity field is documented (§6.10, §8).
  • Every auth, guard, permission, role, public decorator, and guest identity branch is documented (§5) — there is no public/guest surface by design.
  • Every success, validation, auth, permission, not-found, conflict, rate-limit, and server-error branch is documented (§8).
  • Every database read/write, cache invalidation, queue job, notification, and audit event is documented (§8 side effects, §11).
  • Every route has examples for minimal request, full request, success response, and representative failures (§8).
  • Every endpoint family has route, sequence, and error diagrams (§9).
  • Every tradeoff and compatibility risk is documented (§13.5, §13.6).
  • The API doc links to backend and features/flows (See Also).

15. Integration Checklist

  • Every route from controllers is documented.
  • Every DTO field is documented.
  • Every enum value is documented.
  • Every response envelope is documented.
  • Every error code is documented.
  • Every auth guard and permission is documented.
  • Every cache key, queue job, and external call is documented.
  • Every diagram matches the current code.
  • The API doc links to backend and features/flows.

See Also

  • Backend doc: /docs/developer/pos/backend
  • Features and flows doc: /docs/developer/pos/feature
  • Serial numbers: /docs/developer/pos/serials
  • TDD: not yet published

On this page

POS - API Reference1. Documentation Evidence2. Module Summary3. Concepts and Terminology4. API Surface Map5. Auth, Identity, and Permissions6. DTO and Model Reference6.1 OpenPosSaleDto — POST /sales6.2 AttachPosCustomerDto — PATCH /sales/{publicId}/customer6.3 CreatePosWalkInDto — POST /sales/{publicId}/customer6.3a UpdatePosPaymentMethodDto — PATCH /sales/{publicId}/payment-method6.3b PosSkuLookupQueryDto — GET /lookup/products/by-sku6.4 UpsertPosLineDto — PUT /sales/{publicId}/items/{productPublicId}6.5 SetPosFulfilmentDto — PATCH /sales/{publicId}/fulfilment6.6 CompletePosSaleDto — POST /sales/{publicId}/complete6.7 CancelPosSaleDto — POST /sales/{publicId}/cancel6.8 ListPosSalesQueryDto — GET /sales6.9 PosLookupQueryDto — both lookup routes6.10 Response DTOs6.11 CreatePosCounterReturnDto — POST /sales/{publicId}/returns7. Enum Reference8. Endpoint Reference8.1 GET /api/admin/pos/lookup/customers?search=PurposeAuth and PermissionsRequestResponseSide EffectsError Cases8.2 GET /api/admin/pos/lookup/products?search=PurposeAuth and PermissionsRequestResponseSide EffectsError Cases8.3 POST /api/admin/pos/salesPurposeAuth and PermissionsRequestResponseSide EffectsError CasesEdge Cases8.4 GET /api/admin/pos/salesPurposeAuth and PermissionsRequestResponseSide Effects8.5 GET /api/admin/pos/sales/{publicId}PurposeAuth and PermissionsResponseError Cases8.6 GET /api/admin/pos/sales/{publicId}/timelinePurposeAuth and PermissionsResponseError Cases8.7 PATCH /api/admin/pos/sales/{publicId}/customerPurposeAuth and PermissionsRequestResponseSide EffectsError Cases8.8 POST /api/admin/pos/sales/{publicId}/customerPurposeAuth and PermissionsRequestResponseSide EffectsError CasesEdge Cases8.9 PUT /api/admin/pos/sales/{publicId}/items/{productPublicId}PurposeAuth and PermissionsRequestResponseSide EffectsError Cases8.10 DELETE /api/admin/pos/sales/{publicId}/items/{productPublicId}PurposeAuth and PermissionsRequestResponseError Cases8.11 PATCH /api/admin/pos/sales/{publicId}/fulfilmentPurposeAuth and PermissionsRequestResponseSide EffectsError Cases8.12 POST /api/admin/pos/sales/{publicId}/completePurposeAuth and PermissionsRequestResponseSide EffectsError CasesEdge Cases8.13 POST /api/admin/pos/sales/{publicId}/cancelPurposeAuth and PermissionsRequestResponseError Cases8.14 PATCH /api/admin/pos/sales/{publicId}/payment-methodPurposeSource EvidenceAuth and PermissionsRequestResponseSide EffectsError Cases8.15 GET /api/admin/pos/sales/{publicId}/customer/addressesPurposeSource EvidenceAuth and PermissionsResponseError Cases8.16 GET /api/admin/pos/lookup/products/by-sku?sku=PurposeSource EvidenceAuth and PermissionsRequestResponseEdge CasesError Cases8.17 POST /api/admin/pos/sales/{publicId}/receipt-emailPurposeSource EvidenceAuth and PermissionsRequestResponseSide EffectsError Cases8.18 GET /api/admin/pos/configPurposeSource EvidenceAuth and PermissionsResponseError Cases8.19 GET /api/admin/pos/sales/{publicId}/returnablePurposeSource EvidenceAuth and PermissionsResponseError Cases8.20 POST /api/admin/pos/sales/{publicId}/returnsPurposeSource EvidenceAuth and PermissionsRequestResponseSide EffectsError CasesEdge Cases9. Flow Diagrams9.1 Route Ownership9.2 Request Sequence (complete)9.3 Error Branch (completion)10. Pagination, Sorting, Filtering, and Search11. Caching, Jobs, and External Integrations13. Mandatory Deep API Documentation Pack13.1 Route-by-Route Completeness Matrix13.2 Request/Response Exhaustiveness13.3 API Diagram Pack13.4 Consumer Integration Notes13.5 API Tradeoffs and Rationale13.6 API Change Impact14. Zero-Omission API Checklist15. Integration ChecklistSee Also