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
| Area | Files Inspected | What Was Verified |
|---|---|---|
| Controllers | apps/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.ts | Routes, methods, guards, permissions, rate limits |
| DTOs | admin/sale/dto/*.ts, admin/lookup/dto/*.ts, admin/sale-support/dto/*.ts, admin/config/dto/*.ts, admin/return/dto/*.ts | Request, query, response, validation |
| Services | shared/*.service.ts | Behavior, transactions, error codes |
| Schema | packages/db/src/schema/pos/*.ts, packages/db/src/schema/order/enums.ts (order_refund_method) | Tables, enums, constraints |
| Rate limits, errors, permissions | common/guards/ip-throttler.config.ts, common/types/error-codes.ts (POS section), packages/db/src/authorization/permission-catalog.ts | ADMIN_POS_* budgets, error codes, PosReturns module |
| Jobs/cache | packages/jobs/src/index.ts, cache-invalidation.tags.ts | Outbox jobs, inventory domain |
| Existing docs | consumer-handoff.md, Fumadocs formats | Frozen contract and format baseline |
2. Module Summary
| Field | Value |
|---|---|
| Module name | pos |
| Module slug | pos |
| Primary actors | admin (operator), system (sweep) |
| API surfaces | admin only — no customer-facing route exists |
| Base route prefixes | /api/admin/pos/sales, /api/admin/pos/lookup, /api/admin/pos/config |
| Auth model | JwtAuthGuard + RoleGuard + Pos_* permissions (counter returns also need PosReturns_CREATE) |
| Persistence | PostgreSQL (pos_sale, pos_sale_item, pos_sale_event, pos_counter_returns + the online pipeline rows) |
| Runtime source of truth | pos_sale row; the order is the Order module's |
| Sibling docs | Backend, Features and flows |
3. Concepts and Terminology
| Term | Meaning | Source File | Used By |
|---|---|---|---|
saleNumber | POS-2026-000042, the till-roll reference printed on the receipt | pos-sale-number.service.ts | Every response |
status | draft → picked_up/ordered or cancelled; no awaiting_payment | enums.ts | Every response |
fulfilment | pickup/delivery — the discriminator behind every branch | enums.ts | Fulfilment + complete |
customerCreated | §48 Customer Type — TRUE when this sale created the account | pos_sale.customer_created | Sale response |
paymentReference | The terminal/QR slip number; recorded, never validated | pos_sale.payment_reference | Complete |
channel | "pos" on the order/session; a label, never a branch | sales_channel enum | Read-only |
invitationQueued | The walk-in invite is queued; the token is never returned | PosWalkInCreatedDto | Walk-in response |
orderNumber | HS-2026-000042, printed on the receipt | Order module | Completion response |
| Counter Walk-in | The 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 /config | pos-counter-walk-in.ts, migration 0072 | Open sale, fulfilment, config |
resendKey | The Idempotency-Key of a receipt resend; becomes part of the notification jobId | PosSendReceiptPayload | Receipt resend |
| Counter return | One call that records the return, the refund and the stock restore in one transaction | pos-counter-return.service.ts | Returns |
unitNetMinor | Net (after discount) price of one unit in minor units; a display estimate only | PosReturnableLineDto | Returnable |
4. API Surface Map
| Surface | Method | Path | Actor | Auth/Guard | Permission | Controller | Purpose |
|---|---|---|---|---|---|---|---|
| Admin | GET | /api/admin/pos/lookup/customers | Operator | JWT + Role | Pos_READ | PosLookupAdminController | Find a customer by name/email/phone |
| Admin | GET | /api/admin/pos/lookup/products | Operator | JWT + Role | Pos_READ | PosLookupAdminController | Find a sellable product by name/SKU |
| Admin | POST | /api/admin/pos/sales | Operator | JWT + Role | Pos_CREATE | PosSaleAdminController | Open a draft (always pickup) |
| Admin | GET | /api/admin/pos/sales | Operator | JWT + Role | Pos_READ | PosSaleAdminController | List and filter sales |
| Admin | GET | /api/admin/pos/sales/{publicId} | Operator | JWT + Role | Pos_READ | PosSaleAdminController | One sale with its lines |
| Admin | GET | /api/admin/pos/sales/{publicId}/timeline | Operator | JWT + Role | Pos_READ | PosSaleAdminController | The audit trail |
| Admin | PATCH | /api/admin/pos/sales/{publicId}/customer | Operator | JWT + Role | Pos_UPDATE | PosSaleAdminController | Attach an existing customer |
| Admin | POST | /api/admin/pos/sales/{publicId}/customer | Operator | JWT + Role | Pos_CREATE | PosSaleAdminController | Create a walk-in customer |
| Admin | PUT | /api/admin/pos/sales/{publicId}/items/{productPublicId} | Operator | JWT + Role | Pos_UPDATE | PosSaleAdminController | Set a line's FINAL quantity |
| Admin | DELETE | /api/admin/pos/sales/{publicId}/items/{productPublicId} | Operator | JWT + Role | Pos_UPDATE | PosSaleAdminController | Remove a line |
| Admin | PATCH | /api/admin/pos/sales/{publicId}/fulfilment | Operator | JWT + Role | Pos_UPDATE | PosSaleAdminController | Pickup or delivery (+ address) |
| Admin | POST | /api/admin/pos/sales/{publicId}/complete | Operator | JWT + Role | Pos_CREATE | PosSaleAdminController | Take payment, create the order |
| Admin | POST | /api/admin/pos/sales/{publicId}/cancel | Operator | JWT + Role | Pos_DELETE | PosSaleAdminController | Abandon a draft |
| Admin | PATCH | /api/admin/pos/sales/{publicId}/payment-method | Operator | JWT + Role | Pos_UPDATE | PosSaleAdminController | Change the tender of a draft |
| Admin | GET | /api/admin/pos/lookup/products/by-sku | Operator | JWT + Role | Pos_READ | PosLookupAdminController | Resolve a scanned SKU to one configuration |
| Admin | POST | /api/admin/pos/sales/{publicId}/receipt-email | Operator | JWT + Role | Pos_UPDATE | PosSaleSupportAdminController | Re-send the receipt email |
| Admin | GET | /api/admin/pos/sales/{publicId}/customer/addresses | Operator | JWT + Role | Pos_UPDATE | PosSaleSupportAdminController | Saved addresses of the sale's customer |
| Admin | GET | /api/admin/pos/sales/{publicId}/returnable | Operator | JWT + Role | Pos_READ | PosSaleSupportAdminController | Returnable quantities and earlier counter returns |
| Admin | POST | /api/admin/pos/sales/{publicId}/returns | Operator | JWT + Role | Pos_UPDATE + PosReturns_CREATE | PosReturnAdminController | Atomic counter return |
| Admin | GET | /api/admin/pos/config | Operator | JWT + Role | Pos_READ | PosConfigAdminController | Till configuration |
5. Auth, Identity, and Permissions
| Surface | Guard/Decorator | Identity Shape | Permission | Guest Allowed | Notes |
|---|---|---|---|---|---|
| Admin | JwtAuthGuard, RoleGuard | req.user.id | Pos_CREATE/Pos_READ/Pos_UPDATE/Pos_DELETE; PosReturns_CREATE for counter returns | No | The permission module is spelled Pos, never POS; Pos_READ exposes customer lookup, so it is grantable separately from Users_READ |
ParseUUIDPipeon every:publicIdand: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}/returnslists two permissions, andRoleGuardrequires both (requiredPermissions.every):Pos_UPDATEANDPosReturns_CREATE.PosReturnsis its own permission module so a cashier can refund a counter sale without any authority over online returns and refunds. The rows exist afterpnpm --filter @nano-store/api permissions:sync.- A role that has
Pos_*but notPosReturns_CREATEgets403 PERMISSION_INSUFFICIENTon the returns route only.
| Rate-limit constant | Budget (per user) | Routes |
|---|---|---|
ADMIN_POS_WRITE | 180/min | open, customer (attach, walk-in), lines, fulfilment, payment-method, cancel |
ADMIN_POS_COMPLETE | 30/min | complete |
ADMIN_POS_READ | 120/min | sales list, customer addresses, returnable, config |
ADMIN_READ | 30/min | sale detail, timeline |
ADMIN_POS_SEARCH | 120/min | customer and product lookup |
ADMIN_POS_SCAN | 300/min | SKU lookup |
ADMIN_POS_RECEIPT | 10/min | receipt resend |
ADMIN_POS_RETURN | 20/min | counter return |
6. DTO and Model Reference
6.1 OpenPosSaleDto — POST /sales
| Field | Type | Required | Validation | Example |
|---|---|---|---|---|
paymentMethod | string | Yes | @IsIn(POS_PAYMENT_METHODS) — pos_cash/pos_card/pos_qr | "pos_cash" |
customerId | uuid | Yes | @IsUUID | 018f1e2a-...-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
| Field | Type | Required | Validation |
|---|---|---|---|
customerId | uuid | Yes | @IsUUID |
6.3 CreatePosWalkInDto — POST /sales/{publicId}/customer
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
name | string | Yes | ≤255, trimmed | — |
email | string | No | @IsEmail, ≤320, trimmed + lowercased; blank becomes absent | The account identifier and invite destination |
phone | string | No | string ≤20; blank becomes absent | Local 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
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
paymentMethod | string | Yes | @IsIn(POS_PAYMENT_METHODS) — pos_cash/pos_card/pos_qr | The new tender |
6.3b PosSkuLookupQueryDto — GET /lookup/products/by-sku
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
sku | string | Yes | trimmed, length 1–64, printable ASCII (^[\x20-\x7E]+$) | URL-encode it |
6.4 UpsertPosLineDto — PUT /sales/{publicId}/items/{productPublicId}
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
quantity | number | Yes | @IsInt, 1–99 | The FINAL quantity, not a delta. Scanning the same product twice sends 2, not two calls of 1 |
variantPublicId | uuid v7 | No | @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
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
fulfilment | string | Yes | pickup/delivery | — |
addressPublicId | uuid | No | @IsUUID | Mutually exclusive with address |
address | object | No | PosDeliveryAddressDto | Mutually exclusive with addressPublicId |
shippingAmount | number | No | @IsInt, 0 to 10,000,000 | Minor 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
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
paymentReference | string | No | ≤128, trimmed | Permitted for pos_card/pos_qr only — refused beside pos_cash. Recorded, never validated |
serials | array | No | ≤100 entries, unique linePublicId | Per-line serial numbers. Accepted only when the goods leave with the customer now (counter pickup). See Serial Numbers |
serials[].linePublicId | uuid v7 | Yes | @IsUUID("7"), lower-cased | The sale line's public id |
serials[].serialNumbers | string[] | 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
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
reason | string | Yes | @IsNotEmpty, ≤500, trimmed | Mandatory — an audit entry without a why answers nothing |
6.8 ListPosSalesQueryDto — GET /sales
| Field | Type | Default | Validation | Notes |
|---|---|---|---|---|
page | number | 1 | ≥1 | — |
size | number | 20 | 1–100 | — |
status | enum | — | draft/picked_up/ordered/cancelled | — |
fulfilment | enum | — | pickup/delivery | — |
paymentMethod | enum | — | any payment_method | §54 tender split |
customerId | uuid | — | — | — |
createdByAdminId | uuid | — | — | §51/§54 sales-by-administrator |
from | ISO date | — | @IsDateString | Inclusive lower bound on created_at |
to | ISO date | — | @IsDateString | Inclusive upper bound |
search | string | — | trimmed, length 2–40 | Case-insensitive substring match on sale_number or the linked order's order_number; % and _ are literal |
6.9 PosLookupQueryDto — both lookup routes
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
search | string | Yes | ≤100, trimmed; ≥2 chars (else 400 VALIDATION_FAILED) | Name/email/phone (customers), name/SKU (products) |
page | number | No | ≥1 | — |
size | number | No | 1–100 | — |
6.10 Response DTOs
| DTO | Shape | Notes |
|---|---|---|
PosSaleDto | publicId, 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 |
PosSaleListItemDto | publicId, saleNumber, status, fulfilment, paymentMethod, grandTotal, totalQuantity, customerName?, createdByAdminName?, orderNumber?, createdAt | List row |
PosSaleEventDto | publicId, eventType, fromStatus?, toStatus?, actorName? (null after offboarding), reason?, createdAt | Timeline row |
PosSaleCompletionDto | sale, orderNumber (print on the receipt), orderPublicId | Completion |
PosWalkInCreatedDto | sale, customerId, invitationQueued: boolean, phoneDropped: boolean | invitationQueued is true only when the stored customer has an email. Never a token — a credential does not belong in a response body |
PosCustomerMatchDto | customerId, name, email?, phone? | Lookup row — no addresses, no history |
PosProductMatchDto | productPublicId, 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 |
PosSkuMatchDto | product: PosProductMatchDto, matchedConfigurationPublicId | SKU lookup; send matchedConfigurationPublicId as variantPublicId on the line PUT |
PosReceiptEmailQueuedDto | queued: true | Receipt resend |
AddressResponseDto[] | the customer address book DTO from the address module, as a bare array (not { items }) | Customer addresses |
PosConfigDto | counterWalkInCustomerId (uuid), paymentMethods (pos_cash/pos_card/pos_qr), returnWindowDays (7), currency ("NPR") | Till config |
PosReturnableDto | orderStatus, 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 |
PosCounterReturnDto | returnPublicId, refund { publicId, amount, method, status: "settled", settlementReference } or null, lines[] { productPublicId, variantPublicId, productName, variantName, quantity, refundAmount }, sale: PosSaleDto | Counter return result |
6.11 CreatePosCounterReturnDto — POST /sales/{publicId}/returns
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
reason | string | Yes | @IsIn(orderReturnReasonEnum.enumValues) | The order module's return reason enum |
comment | string | No | trimmed, ≤1000 | — |
lines | array | Yes | 1–50 items, each validated | No money field — the server computes every amount from the order |
lines[].productPublicId | uuid | Yes | @IsUUID | — |
lines[].variantPublicId | uuid v7 | Yes | @IsUUID("7") | The configuration that was sold |
lines[].quantity | number | Yes | @IsInt, 1–99 | Units returned now |
lines[].serialNumbers | string[] | 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 |
refundMethod | string | No | cash / card_reversal / qr_reversal | Any method on any sale; defaults from the sale's tender when omitted (see §8.20) |
settlementReference | string | No | trimmed, length 1–120 | Terminal reversal reference |
7. Enum Reference
| Enum | Value | Meaning | Runtime Effect | Source |
|---|---|---|---|---|
pos_sale_status | draft | Being rung up; only editable state | Lines may change; cancel is free | enums.ts |
pos_sale_status | picked_up | Pickup sale, goods handed over | Terminal; order already delivered | |
pos_sale_status | ordered | Delivery sale, order at confirmed | Terminal for POS; Order owns the rest | |
pos_sale_status | cancelled | Abandoned before completion | Only reachable from draft | |
pos_fulfilment_type | pickup | Customer takes the goods | No address, no shipping | |
pos_fulfilment_type | delivery | Delivered to an address | Address + shipping required | |
pos_sale_event_type | created / customer_assigned / customer_created / item_added / item_quantity_changed / item_removed / fulfilment_set / payment_recorded / completed / cancelled | What happened | Timeline rows | |
sales_channel | online / pos | Where the order came from | Label only — never a branch, except the card/QR reversal guard on refund approval | checkout/enums.ts |
order_refund_method | cash / card_reversal / qr_reversal (POS subset) | How a counter refund goes back | card_reversal and qr_reversal were added by migration 0070; the order module refuses them on a non-pos order | order/enums.ts |
payment_method (POS subset) | pos_cash / pos_card / pos_qr | The counter tender | pos_card and pos_qr may carry a payment reference; pos_cash may not | payment/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
| Part | Required | Details |
|---|---|---|
| Query | Yes | search (≥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
| HTTP | Code | Condition |
|---|---|---|
| 400 | VALIDATION_FAILED | search 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
| Part | Required | Details |
|---|---|---|
| Query | Yes | search (≥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
| HTTP | Code | Condition |
|---|---|---|
| 400 | VALIDATION_FAILED | search 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
| HTTP | Code | Condition |
|---|---|---|
| 400 | validation | Bad method/customer |
| 404 | POS_SALE_NO_CUSTOMER | The customer does not exist or is deleted |
Edge Cases
paymentMethodis changeable until completion — the field is on the sale, not fixed at open.- Sending
fulfilmentis 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
| Part | Required | Details |
|---|---|---|
| Query | No | page, 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
| HTTP | Code | Condition |
|---|---|---|
| 404 | POS_SALE_NOT_FOUND | The 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
| HTTP | Code | Condition |
|---|---|---|
| 404 | POS_SALE_NOT_FOUND | The 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
| HTTP | Code | Condition |
|---|---|---|
| 404 | POS_SALE_NOT_FOUND / POS_SALE_NO_CUSTOMER | Missing sale / missing customer |
| 409 | POS_SALE_NOT_DRAFT | Cancelled |
| 409 | POS_SALE_ALREADY_COMPLETED | Money 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 }.
invitationQueuedistrueonly when the stored customer has an email. A phone-only customer gets noaccountrow and no invitation; OTP login on that phone is the claim.phoneDroppedistruewhen 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
customersrow, plus anaccountrow 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 andphoneDropped; 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
| HTTP | Code | Condition |
|---|---|---|
| 400 | POS_WALK_IN_CONTACT_REQUIRED | Neither email nor phone |
| 400 | POS_WALK_IN_PHONE_INVALID | The phone cannot be normalised to E.164 |
| 409 | POS_CUSTOMER_CONTACT_EXISTS | The email or phone belongs to an attachable customer. details: { customerId, name, matchedOn: "email" | "phone" } — attach that customer with PATCH /customer instead |
| 409 | POS_CUSTOMER_CONTACT_CONFLICT | The email and the phone belong to two different customers |
| 409 | POS_CUSTOMER_CONTACT_UNAVAILABLE | The 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 |
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETED | Not a draft |
Edge Cases
- A
23505on email or phone is caught in a savepoint and re-resolved once; a second collision answersPOS_CUSTOMER_CONTACT_UNAVAILABLE. POS_CUSTOMER_EMAIL_TAKENis 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
| HTTP | Code | Condition |
|---|---|---|
| 400 | POS_QUANTITY_OUT_OF_RANGE | Not a whole number in 1–99 |
| 404 | POS_PRODUCT_NOT_SELLABLE | Product missing, unpublished or deleted |
| 404 | POS_VARIANT_NOT_SELLABLE | variantPublicId was sent and that configuration is not available for the product |
| 409 | POS_PRODUCT_NOT_SELLABLE | Product priced above its MRP |
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETED | Not 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
| HTTP | Code | Condition |
|---|---|---|
| 404 | POS_LINE_NOT_FOUND | The product, or the named configuration, is not on this sale |
| 409 | POS_LINE_VARIANT_REQUIRED | The product is on the sale as more than one configuration and variantPublicId was not sent |
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETED | Not 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
shippingAmountto 0. - Delivery: resolves the saved address (scoped to THIS customer in the query) or inserts a new
customer_addressesrow withis_default: false— the POS transaction deliberately does not take the default-address advisory lock. grandTotalis recomputed in the same statement that writesshippingAmount, from the row's ownsubtotalanddiscountAmount.- Counter Walk-in sales use a one-time address. When the sale's customer is the shared Counter Walk-in, the typed
addressis inserted intocustomer_addressesfor 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.addressPublicIdis 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
| HTTP | Code | Condition |
|---|---|---|
| 409 | POS_DELIVERY_ADDRESS_REQUIRED | Delivery with no address — or both addressPublicId AND address (mutually exclusive) |
| 404 | POS_ADDRESS_NOT_FOUND | The address is not this customer's |
| 404 | POS_DISTRICT_NOT_FOUND | address.districtId matches no district |
| 400 | POS_RECIPIENT_PHONE_INVALID | recipientPhone passes the DTO pattern but normalizeToE164 returns null |
| 409 | POS_WALK_IN_SAVED_ADDRESS_NOT_ALLOWED | addressPublicId sent while the customer is the Counter Walk-in |
| 503 | POS_COUNTER_CUSTOMER_MISSING | Delivery for the Counter Walk-in, and that row is missing or altered |
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETED | Not 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
| HTTP | Code | Condition |
|---|---|---|
| 409 | POS_SALE_EMPTY | No lines |
| 409 | POS_SALE_NO_CUSTOMER | No customer attached |
| 409 | POS_DELIVERY_ADDRESS_REQUIRED | Delivery with no address |
| 409 | POS_PRODUCT_NOT_SELLABLE | A product is no longer published |
| 409 | POS_PRODUCT_PRICE_CHANGED | A price moved mid-sale — tell the operator to speak to the customer; remove and re-add to charge the new price |
| 409 | POS_INSUFFICIENT_STOCK | Someone else took the last one — show remaining stock, let the operator reduce the quantity |
| 409 | POS_PAYMENT_REFERENCE_NOT_ALLOWED | Reference sent with cash |
| 409 | POS_SALE_ALREADY_COMPLETED | The money was already taken — do not retry, show the existing order number |
| 409 | POS_ADDRESS_NOT_FOUND | The configured store district does not exist (pickup shipping resolve) |
| 409 | POS_SERIAL_LINE_NOT_FOUND | A serials[].linePublicId is not on the sale — re-fetch the sale |
| 409 | POS_SERIALS_NOT_ALLOWED | Serials sent on a sale that is not handed over now (delivery) — record them at dispatch |
| 409 | ORDER_SERIAL_COUNT_MISMATCH | More serials than units on a line |
| 409 | ORDER_SERIAL_ALREADY_RECORDED | A serial is already active for the same product, or repeated in the request; details.conflicts / details.duplicates name them |
| 400 | ORDER_SERIAL_INVALID | A 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 guardedWHERE status = 'draft'finalise make a retry a 409, never a second charge. - A delivery sale's order stays at
confirmedfor the normal lifecycle; a pickup's order is driven straight todelivered(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
| HTTP | Code | Condition |
|---|---|---|
| 400 | validation | Blank or missing reason |
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_SALE_NOT_DRAFT / POS_SALE_ALREADY_COMPLETED | Not 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, bumpsversionandupdated_at(which is the abandoned-draft sweep clock). Switching topos_cashclears anypayment_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
| HTTP | Code | Condition |
|---|---|---|
| 400 | VALIDATION_FAILED | Value is not pos_cash/pos_card/pos_qr |
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_SALE_ALREADY_COMPLETED | The sale is completed |
| 409 | POS_SALE_NOT_DRAFT | The 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
| HTTP | Code | Condition |
|---|---|---|
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_SALE_NOT_DRAFT | The sale is not a draft |
| 404 | POS_WALK_IN_NO_ADDRESS_BOOK | The 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
| Part | Required | Details |
|---|---|---|
| Query | Yes | sku, 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
| HTTP | Code | Condition |
|---|---|---|
| 400 | VALIDATION_FAILED | sku is empty, longer than 64 or not printable ASCII |
| 404 | POS_SKU_NOT_FOUND | No match, or several case-insensitive matches |
| 409 | POS_SKU_AMBIGUOUS | An exact match hits two different products or two variant rows. details.candidates lists them |
| 404 | POS_VARIANT_NOT_SELLABLE | The matched configuration is not sellable |
| 404 / 409 | POS_PRODUCT_NOT_SELLABLE | The 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_requestedwithdedupe_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
| HTTP | Code | Condition |
|---|---|---|
| 400 | POS_IDEMPOTENCY_KEY_INVALID | The header is present but not a UUID |
| 400 | IDEMPOTENCY_KEY_REQUIRED | The header is absent |
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_RECEIPT_NOT_AVAILABLE | The sale is not picked_up or ordered |
| 409 | POS_CUSTOMER_NO_EMAIL | The customer has no email (a phone-only walk-in, or the Counter Walk-in) |
| 409 | POS_RECEIPT_RESEND_LIMIT | 3 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
| HTTP | Code | Condition |
|---|---|---|
| 503 | POS_COUNTER_CUSTOMER_MISSING | The 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 returns200with everyreturnable: 0.unitNetMinor = floor(netAmount / quantity). The client's refund estimate isreturnable × unitNetMinor; the committed amount comes from the return route.counterReturnsis newest first.
Error Cases
| HTTP | Code | Condition |
|---|---|---|
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | POS_COUNTER_RETURN_NOT_ALLOWED | details.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_UPDATEandPosReturns_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:
- 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"). - If a refund was created, approve it with the refund method and settle it with the reference.
- Insert the
pos_counter_returnsrow (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
| HTTP | Code | Condition |
|---|---|---|
| 400 | POS_IDEMPOTENCY_KEY_INVALID | Header present but not a UUID |
| 400 | IDEMPOTENCY_KEY_REQUIRED | Header absent |
| 400 | VALIDATION_FAILED | Body fails the DTO (no lines, more than 50, bad uuid, quantity outside 1–99, unknown reason or refund method) |
| 403 | PERMISSION_INSUFFICIENT | Missing Pos_UPDATE or PosReturns_CREATE |
| 404 | POS_SALE_NOT_FOUND | Missing sale |
| 409 | IDEMPOTENCY_KEY_CONFLICT | Key reused with a different payload |
| 409 | IDEMPOTENCY_REQUEST_IN_PROGRESS | Same key still running |
| 409 | POS_COUNTER_RETURN_NOT_ALLOWED | See details.reason below |
POS_COUNTER_RETURN_NOT_ALLOWED carries details.reason:
reason | Meaning | Extra details |
|---|---|---|
not_completed | Draft, cancelled, or an order not yet delivered (including a delivery sale still in transit) | — |
window_closed | The 7-day return window has ended, or the order is completed | — |
fully_returned | The order status is returned | — |
line_not_in_sale | A (product, variant) pair is not on the order | productPublicId, variantPublicId |
quantity_exceeds_returnable | More units than deliveredQuantity - pending - returned | productPublicId, variantPublicId, returnable |
duplicate_line | The same (product, variant) appears twice (compared case-insensitively) | — |
serial_not_on_line | A picked serial is not an active serial of that line | productPublicId, variantPublicId |
serial_count_exceeds_quantity | More serials picked than units returned, or a serial picked twice | productPublicId, 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
23505onuq_pos_counter_returns_sale_keyre-runs the transaction once; the replay check then finds the row. - The order module also guards the refund itself: approving
card_reversalorqr_reversalon a non-posorder is409 ORDER_REFUND_METHOD_NOT_ALLOWED.
9. Flow Diagrams
9.1 Route Ownership
9.2 Request Sequence (complete)
9.3 Error Branch (completion)
10. Pagination, Sorting, Filtering, and Search
| Endpoint | Pagination Type | Default Size | Max Size | Sort Fields | Filters | Result Cap |
|---|---|---|---|---|---|---|
GET /api/admin/pos/sales | offset page/size | 20 | 100 | createdAt 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/customers | offset page/size | 20 | 100 | name ASC, id ASC (fixed) | search (≥2 chars, ILIKE) | — |
GET /api/admin/pos/lookup/products | offset page/size | 20 | 100 | name ASC, id ASC (fixed) | search (≥2 chars, ILIKE on name and on product and variant SKU) | — |
GET /api/admin/pos/sales/{publicId}/customer/addresses | none (full active list) | — | — | address book order | — | — |
11. Caching, Jobs, and External Integrations
| Integration | Used? | Details | Source |
|---|---|---|---|
| Redis cache | Yes (invalidation only) | inventory domain cleared after a completed sale (triggerForWrite, post-commit, fire-and-forget) | pos.constants.ts |
| BullMQ | Yes | QueueName.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 retried | pos-queue.processor.ts |
| External API | No | Payment references are recorded, never validated | — |
13. Mandatory Deep API Documentation Pack
13.1 Route-by-Route Completeness Matrix
| Route | Controller Method | DTOs | Service Method | Guards | Permissions | Cache | Jobs | DB Touches | Errors | Documented? |
|---|---|---|---|---|---|---|---|---|---|---|
GET /api/admin/pos/lookup/customers | searchCustomers | PosLookupQueryDto | PosLookupService.searchCustomers | JWT+Role+Throttle | Pos_READ | — | — | customers | 400 | Yes |
GET /api/admin/pos/lookup/products | searchProducts | PosLookupQueryDto | PosLookupService.searchProducts | JWT+Role+Throttle | Pos_READ | — | — | products | 400 | Yes |
POST /api/admin/pos/sales | open | OpenPosSaleDto | PosSaleDraftService.open | JWT+Role+Throttle | Pos_CREATE | — | — | pos_sale, event | 400/404 | Yes |
GET /api/admin/pos/sales | findAll | ListPosSalesQueryDto | PosSaleQueryService.findAll | JWT+Role+Throttle | Pos_READ | — | — | pos_sale + joins | — | Yes |
GET /api/admin/pos/sales/{publicId} | findOne | — | PosSaleQueryService.findOne | JWT+Role+Throttle | Pos_READ | — | — | pos_sale, items | 404 | Yes |
GET /api/admin/pos/sales/{publicId}/timeline | findTimeline | — | PosSaleQueryService.findTimeline | JWT+Role+Throttle | Pos_READ | — | — | events | 404 | Yes |
PATCH /api/admin/pos/sales/{publicId}/customer | attachCustomer | AttachPosCustomerDto | PosSaleDraftService.attachCustomer | JWT+Role+Throttle | Pos_UPDATE | — | — | pos_sale, event | 404/409 | Yes |
POST /api/admin/pos/sales/{publicId}/customer | createWalkIn | CreatePosWalkInDto | PosSaleDraftService.createWalkInCustomer | JWT+Role+Throttle | Pos_CREATE | — | outbox invite (email only) | customers, account, pos_sale, outbox, event | 400/404/409 | Yes |
PUT /api/admin/pos/sales/{publicId}/items/{productPublicId} | upsertLine | UpsertPosLineDto | PosSaleLineService.upsertLine | JWT+Role+Throttle | Pos_UPDATE | — | — | pos_sale_item, pos_sale, event | 400/404/409 | Yes |
DELETE /api/admin/pos/sales/{publicId}/items/{productPublicId} | removeLine | — | PosSaleLineService.removeLine | JWT+Role+Throttle | Pos_UPDATE | — | — | pos_sale_item, pos_sale, event | 404/409 | Yes |
PATCH /api/admin/pos/sales/{publicId}/fulfilment | setFulfilment | SetPosFulfilmentDto | PosSaleDraftService.setFulfilment | JWT+Role+Throttle | Pos_UPDATE | — | — | pos_sale, address, event | 404/409 | Yes |
POST /api/admin/pos/sales/{publicId}/complete | complete | CompletePosSaleDto | PosSaleCompletionService.complete | JWT+Role+Throttle | Pos_CREATE | inventory (after commit) | outbox receipt | 7 tables + events + outbox | 409 set | Yes |
POST /api/admin/pos/sales/{publicId}/cancel | cancel | CancelPosSaleDto | PosSaleDraftService.cancel | JWT+Role+Throttle | Pos_DELETE | — | — | pos_sale, event, customer_addresses (archive) | 400/404/409 | Yes |
PATCH /api/admin/pos/sales/{publicId}/payment-method | setPaymentMethod | UpdatePosPaymentMethodDto | PosSaleDraftService.setPaymentMethod | JWT+Role+Throttle | Pos_UPDATE | — | — | pos_sale | 400/404/409 | Yes |
GET /api/admin/pos/lookup/products/by-sku | findBySku | PosSkuLookupQueryDto | PosLookupService.findBySku | JWT+Role+Throttle | Pos_READ | — | — | products, product_variants | 400/404/409 | Yes |
POST /api/admin/pos/sales/{publicId}/receipt-email | resendReceipt | — (header) | PosSaleSupportAdminService.resendReceipt | JWT+Role+Throttle+Key guard+Idempotency | Pos_UPDATE | — | outbox receipt resend | pos_sale, customers, outbox_events | 400/404/409 | Yes |
GET /api/admin/pos/sales/{publicId}/customer/addresses | listCustomerAddresses | — | PosSaleSupportAdminService.listCustomerAddresses | JWT+Role+Throttle | Pos_UPDATE | — | — | customer_addresses | 404/409 | Yes |
GET /api/admin/pos/sales/{publicId}/returnable | getReturnable | — | PosCounterReturnService.getReturnable | JWT+Role+Throttle | Pos_READ | — | — | pos_sale, order_items, pos_counter_returns | 404/409 | Yes |
POST /api/admin/pos/sales/{publicId}/returns | create | CreatePosCounterReturnDto | PosCounterReturnService.createCounterReturn | JWT+Role+Throttle+Key guard+Idempotency | Pos_UPDATE + PosReturns_CREATE | POS domain (after commit) | order notifications | order_return*, order_refund*, inventory, pos_counter_returns | 400/403/404/409 | Yes |
GET /api/admin/pos/config | getConfig | — | PosConfigAdminService.getConfig | JWT+Role+Throttle | Pos_READ | — | — | customers | 503 | Yes |
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
| Consumer | Required Knowledge | Failure Handling | Contract Stability |
|---|---|---|---|
| Admin panel (till) | 20 routes, Pos_* permissions, final-quantity PUT, pickup-first drafts, recorded:false-style semantics for references | 409s → re-fetch the sale; POS_SALE_ALREADY_COMPLETED → show the order number, never retry | Stable |
| Admin panel (reports) | GET /sales filters, integer minor units, customerCreated, createdByAdminId | Offset cap at 10k rows | Stable |
| Admin panel (walk-in) | No password ever; invitationQueued and phoneDropped are the whole answer; never expect a token | 409 POS_CUSTOMER_CONTACT_EXISTS → attach details.customerId with PATCH /customer | Stable |
| Admin panel (counter return) | GET /returnable for quantities, then POST /returns with one Idempotency-Key per confirm dialog; estimate refund as returnable × unitNetMinor | POS_COUNTER_RETURN_NOT_ALLOWED → branch on details.reason; retry with the SAME key after a network failure | Stable |
| Admin panel (order rendering) | Refund method may now be card_reversal / qr_reversal — add labels | Degrades to a raw enum, never an error | Stable |
| Storefront frontend | Nothing 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 enum | Degrades to an ugly label, never an error | Stable |
| QA | Constraint invariants (status/key pairs, pickup no-shipping), one-transaction completion, replay safety | Reproduce via the exact codes | Stable |
13.5 API Tradeoffs and Rationale
| Decision | Chosen Behavior | Alternatives Considered | Why This Tradeoff | Risk | Mitigation |
|---|---|---|---|---|---|
No fulfilment on open | Drafts always open pickup | Accepting delivery | open() cannot supply an address; the old field was a guaranteed 23514 | One extra tap | Re-render fulfilment from responses |
PUT replaces quantity | Idempotent final quantity | POST increment | A till types a number | Double-scan confusion | Documented; ON CONFLICT |
customerId required at open | No customerless draft | Anonymous sales | Every sale belongs to an account | Extra step for new walk-ins | Walk-in endpoint first |
| Reference never validated | Recorded as entered | Provider check | §17 leaves verification with the operator | False "verified" impression | Documented, refused beside cash |
| Completion is one tx | All-or-nothing | Pipeline with compensation | The paid-without-order state is not cleanable | Long lock scope | Ascending lock order |
| Customer change resets to pickup | Address/fulfilment/shipping cleared | Partial clear | The old address is not this person's | Re-picking delivery | Explicit in docs |
| Walk-in invite never expires | Far-future sentinel, single use | 24h TTL | Owner policy; support dead-end | Long-lived if stolen | Single use, no OTP |
| New address not the default | is_default: false | Taking the default lock | POS tx must not race the address advisory lock | Minor UX | Customer promotes later |
13.6 API Change Impact
| Change | Affected Consumers | Backend Impact | Data Impact | Migration Needed? | Compatibility Plan |
|---|---|---|---|---|---|
order.channel / checkout_session.channel added | Storefront (ignores), reporting | Column + enum | None — defaults online | No | Additive; existing rows unaffected |
payment_method gains 3 values | Admin order renderer | Enum + gateway labels | None | No | Label the new values; storefront list unchanged |
order_refund_method gains card_reversal, qr_reversal | Admin order renderer, finance | Enum; guard in refund approval | None | Yes (0070, additive) | Label the new values |
pos_counter_returns table, Counter Walk-in row | Till | New table (0071), data row (0072) | New rows on each counter return | Yes | Additive |
districtId on PATCH /fulfilment becomes a uuid v7 | Till | DTO | None | No | Breaking for a client that sent the integer id; send the district publicId |
POST /customer body: email optional, phone accepted; status 201 | Till | DTO + service | None | No | Handle phoneDropped and the new 409 codes |
| Any future lookup change | Till | PosLookupService | None | No | Contract frozen in consumer-handoff |
| Future barcode column | Till | Product schema | Migration | Yes (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