Order API Reference
Complete API contracts for the Order module, including routes, auth, DTOs, responses, errors, examples, and integration notes.
Order - API Reference
Audience: Frontend engineers, mobile engineers, backend engineers, QA, and API consumers.
Scope: The customer, order admin, cash collection admin, return admin and refund admin routes (the original count of 30 grew by one: POST /api/order-returns). The 3 manual (WhatsApp) order routes under /api/orders/manual have their own page: Manual orders.
1. Documentation Evidence
| Area | Files Inspected | What Was Verified |
|---|---|---|
| Controllers | apps/api/src/modules/order/customer/order-customer.controller.ts, admin/{order,return,refund,cod}/*.controller.ts | Routes, methods, guards, permissions |
| DTOs | dto/*.ts | Validation |
| Services | customer/admin/return/refund services | Behavior, transitions |
| Schema | packages/db/src/schema/order/*.ts | 12 tables, CHECKs |
| Error registry | apps/api/src/common/types/error-codes.ts (// ORDER) | ORDER_* codes |
2. Module Summary
| Field | Value |
|---|---|
| Module name | order |
| Module slug | order |
| Primary actors | customer, admin (orders/returns/refunds), worker |
| API surfaces | mobile (customer), admin |
| Base route prefixes | /api/mobile/orders, /api/orders, /api/order-returns, /api/order-refunds |
| Auth model | JwtAuthGuard (customer); JwtAuthGuard + RoleGuard (admin) |
| Persistence | PostgreSQL (12 tables); no cache |
| Runtime source of truth | Order rows (snapshots) + live inventory for restock |
| Sibling docs | Backend, Features and flows |
3. Concepts and Terminology
| Term | Meaning | Source File | Used By |
|---|---|---|---|
status | One of eleven order statuses, including returned and partially_returned; there is no refunded status | schema | All routes |
Per-line label | Derived display label; quantities are the truth | response builder | Order responses |
unavailableQuantity | A short order — paid for, not coming | schema | Short orders |
codCollectedAt | COD money actually changed hands | schema | COD flows |
returnPendingQuantity | Units in a return in flight | schema | Returns |
pollAfterSeconds | Server-set poll interval | status endpoint | Polling |
refundedAmount | Denormalised counter, CHECK-bounded | schema | Refunds |
4. API Surface Map
4.1 Customer — /api/mobile/orders
| Method | Path | Purpose |
|---|---|---|
GET | / | My orders |
GET | /:id | One order |
GET | /:id/status | Small poll payload |
GET | /:id/invoice.pdf | Receipt PDF |
POST | /:id/cancel | Cancel before dispatch |
POST | /:id/returns | Request a return |
GET | /:id/returns | My returns on this order |
POST | /:id/returns/:returnId/cancel | Cancel a pending return |
4.2 Admin — orders, /api/orders
| Method | Path | Permission | Purpose |
|---|---|---|---|
GET | / | Orders_READ | List (filter by channel, see below) |
GET | /:id | Orders_READ | Detail |
POST | /:id/confirm | Orders_UPDATE | Confirm |
POST | /:id/processing | Orders_UPDATE | Processing |
POST | /:id/cancel | Orders_UPDATE | Cancel |
POST | /:id/notes | Orders_UPDATE | Add note |
POST | /:id/shipments | Orders_UPDATE | Dispatch (with serials) |
POST | /:id/shipments/:shipmentId/deliver | Orders_UPDATE | Deliver parcel |
POST | /:id/shipments/:shipmentId/fail | Orders_UPDATE | Fail parcel |
POST | /:id/refunds | Refunds_UPDATE | Create refund |
POST | /:id/ready-for-pickup | Orders_UPDATE | Tell the customer a pickup order is waiting |
POST | /:id/collect | Orders_UPDATE | Hand a pickup order over — drives it to delivered |
channel. Every admin order object — each list item and the detail — carries channel: online
(storefront), pos (the counter) or whatsapp (entered by an administrator from a chat). The list
route accepts channel=online|pos|whatsapp to filter on it; any other value is a 400, and the count
query shares the filter so pagination stays correct. Orders entered by hand are created through
POST /api/orders/manual — see Manual orders.
The last two rows above (ready-for-pickup, collect) are the pickup lifecycle, and they sit on the same /api/orders prefix as the rest
even though they live in their own controller: readiness and collection are one lifecycle, share
two error codes, and neither means anything for a delivery order. Both refuse a delivery order
with ORDER_NOT_PICKUP.
/collect is the pickup counterpart of /:id/shipments and the only thing that moves a pickup
order to delivered — until it runs, the customer cannot review an item or open a return, because
the return window opens on delivery. It is deliberately not idempotent (ORDER_NOT_COLLECTABLE
on a second press): at a counter, pressing twice is far more likely a double-tap than a retry.
/ready-for-pickup is the opposite — pressing it again re-enters the same state, and the outbox
dedupe key collapses the repeats into one email.
Two operators pressing "ready" at once no longer 409s. The endpoint moves a confirmed order to
processing first, and the second request lost that race: it hit ORDER_TRANSITION_NOT_ALLOWED
and showed the operator a failure for an order that was, at that moment, exactly as ready as they
had asked for. Two people at one counter is the normal case for this route, not an edge case.
It now tolerates precisely that code from the transition — and only that code — then re-reads the order and continues. Any other failure still propagates. The order still ends in the state the caller asked for, which is the test an idempotent endpoint has to pass; a transition genuinely refused (already collected, cancelled) is a different state and still refuses.
4.2a Admin — cash collection, /api/orders (own leaf, OrderCodAdminController)
| Method | Path | Permission | Purpose |
|---|---|---|---|
POST | /:id/cod-collection | Orders_UPDATE | Record cash collected at the door |
PATCH | /:id/cod-collection | OrderCash_UPDATE | Correct a recorded cash amount |
POST | /:id/cod-collection/reversal | OrderCash_DELETE | Undo a collection recorded against the wrong order |
Its own leaf rather than three more rows on OrderAdminController: cash collection has its own
lifecycle, its own error codes and its own audit trail, and adding it to the eleven-route controller
would push it over the 300-source-line gate for no cohesion gain. This module is on the admin Swagger
allowlist — a route here can be live and invisible in the admin docs if that listing is missed.
POST records the cash — omitting amount records the order's own grandTotal, which is the
ordinary case. PATCH corrects a figure that has already been recorded; it never touches
cod_collected_at or the operator who originally counted the money, so the order does not re-enter
the outstanding-cash queue for cash that has, in fact, been counted. POST .../reversal is for cash
recorded against the wrong order: it returns the order to the outstanding-cash queue. It is a POST
sub-resource rather than a DELETE with a body — the reason is required, and a DELETE body is legal
HTTP a proxy is free to drop; this deployment sits behind Nginx.
4.3 Admin — returns, /api/order-returns
| Method | Path | Permission | Purpose |
|---|---|---|---|
GET | / | Returns_READ | List |
GET | /:id | Returns_READ | Detail |
POST | / | Returns_UPDATE | Open a return on a customer's behalf (Idempotency-Key required) |
POST | /:id/decide | Returns_UPDATE | Approve/reject |
POST | /:id/receive | Returns_UPDATE | Goods back |
POST | /:id/inspect | Returns_UPDATE | Inspect (quantities + reason) |
4.4 Admin — refunds, /api/order-refunds
| Method | Path | Permission | Purpose |
|---|---|---|---|
GET | / | Refunds_READ | List |
POST | /:id/approve | Refunds_UPDATE | Approve (choose method) |
POST | /:id/reject | Refunds_UPDATE | Reject (pending only) |
POST | /:id/settle | Refunds_UPDATE | Settle (reference required) |
Every refund read — the list and the row returned by approve / reject / settle — carries four order cash-context fields. They are display context for the approve screen, not a guard; nothing on this surface refuses a refund because of them.
| Field | Type | Meaning |
|---|---|---|
orderPaymentMethod | string | Lets a non-COD order be skipped entirely |
orderDeliveredAt | date | null | NULL until delivery. Required to read the next field correctly |
orderCodCollectedAmount | number | null | Minor units. Cash actually collected |
orderAttributedRefundAmount | number | Minor units. Everything attributed to the ORDER across all non-rejected refunds |
Why they exist: a COD order may be legally under-collected, while chk_order_paid_amount_matches
pins paid_amount to grand_total. The refund ceiling therefore compares against the full total
and cannot see the shortfall — a full refund on an order where a third of the cash arrived passes
every guard.
Three things a consumer must get right:
orderAttributedRefundAmountalready includes the refund being viewed. Compare it directly againstorderCodCollectedAmount; adding the row's ownamountdouble-counts.orderDeliveredAtis the discriminator, not a null amount.chk_order_cod_collectionrequiresdelivered_at IS NOT NULLbefore a collection can exist, so every undelivered COD order has a NULL collection by construction — that is the ordinary state, not a discrepancy.- A NULL collection on a delivered order does not say why. The constraint forces all three COD columns to NULL together and bars a zero marker, so a reversed collection is indistinguishable from one never entered. Copy must not assert a cause.
5. Auth, Identity, and Permissions
| Surface | Guard/Decorator | Identity Shape | Permission | Guest Allowed | Notes |
|---|---|---|---|---|---|
| Customer | JwtAuthGuard | req.user.id | — | No | Ownership-scoped: another customer's order is 404 |
| Admin | JwtAuthGuard, RoleGuard | req.user | Orders_* / Returns_* / Refunds_* | No | Three separate permission modules — money-back is never a side effect of dispatch rights; run permissions:sync on deploy |
6. DTO and Model Reference
6.1 Create refund — POST /api/orders/:id/refunds
The caller sends lines and quantities — the server computes the money. No amount field.
{ "items": [ { "orderItemId": "…", "quantity": 1 } ] }6.2 Approve refund
{ "method": "bank_transfer" }The method is chosen at approval — the row has no method before this. Values: esewa_reversal / bank_transfer / cash / card_reversal / qr_reversal.
card_reversal and qr_reversal reverse a payment taken on a counter terminal. They are accepted only for an order whose channel is pos; on any other order approval answers 409 ORDER_REFUND_METHOD_NOT_ALLOWED (order-refund-settlement.service.ts, approveInTx). On a pos order every method is allowed, whatever tender paid for the sale. The POS counter return (POST /api/admin/pos/sales/{publicId}/returns) is the normal producer of these two values; see the POS API reference.
6.3 Settle refund
{ "settlementReference": "BRN-12345" }Required by constraint — 400 ORDER_REFUND_SETTLEMENT_REFERENCE_REQUIRED without it.
6.4 Return DTOs
Decide: approval state (+ reason when rejecting). Inspect: per-item quantities and, when rejecting, a reason (ORDER_RETURN_INSPECTION_INVALID names which).
Request a return — customer POST /api/mobile/orders/:id/returns (RequestReturnDto):
| Field | Type | Required | Validation |
|---|---|---|---|
reason | enum | Yes | wrong_item, damaged_in_transit, defective, missing_parts, incorrect_size, no_longer_needed, changed_mind, not_as_described, other |
comment | string | No | Max 1000. Stored as the customer's comment |
lines | array of ReturnLineDto | Yes | 1 to 50 entries (MAX_RETURN_LINES); over 50 is a standard 400 VALIDATION_FAILED on lines. Swagger declares maxItems: 50 |
ReturnLineDto: orderItemPublicId (uuid v7, the order line's public id) and quantity (integer 1 to 99, further bounded by what is delivered and not already claimed).
Each orderItemPublicId may appear only once in lines. A repeat is rejected, never merged or summed, with 422 ORDER_RETURN_DUPLICATE_LINE ("Each item can appear only once in a return request."). Ids are compared case-insensitively, and the check runs before the order is read, so it reveals nothing about any order.
Open a return on a customer's behalf — admin POST /api/order-returns (AdminOpenReturnDto):
| Field | Type | Required | Validation |
|---|---|---|---|
orderPublicId | uuid v7 | Yes | The order's public id |
reason | enum | Yes | Same values as the customer route |
comment | string | No | Max 1000. The operator's note: kept in the order event's detail (adminComment), not in the customer's comment field, and not exposed on the customer timeline |
lines | array of ReturnLineDto | Yes | 1 to 50 entries, same shape and same duplicate rule as the customer route |
The admin route deliberately shares the customer contract: both run the same service body, so they cannot accept different sizes. Requires Returns_UPDATE and an Idempotency-Key header.
6.5 Query DTOs
Order list and return/refund lists follow the standard QueryDto paging with filters (status, date range, customer, etc.); the refund list is the finance queue. The order list also takes channel (online / pos / whatsapp, validated against the sales_channel enum).
6.6a Cash collection DTOs
RecordCodCollectionAdminDto — POST /:id/cod-collection:
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
amount | integer, minor units | No | @IsInt, @Min(1) | Omit to record the order's full total — the ordinary case. Below grandTotal is permitted and recorded; above it is refused. An explicit null is rejected. |
CorrectCodCollectionAdminDto — PATCH /:id/cod-collection:
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
amount | integer, minor units | Yes | @IsInt, @Min(1) | The corrected figure |
expectedCurrentAmount | integer, minor units | Yes | @IsInt, @Min(1) | The figure the operator was looking at. Refused if it no longer matches what is recorded. |
reason | string | Yes | 3–500 chars | Why the recorded amount is changing — required, not optional, on a money path |
ReverseCodCollectionAdminDto — POST /:id/cod-collection/reversal:
| Field | Type | Required | Validation | Notes |
|---|---|---|---|---|
reason | string | Yes | 3–500 chars | Why the collection is being undone |
6.6 Order line item — the frozen configuration
Every order line was frozen from a checkout line that names a product_variant, not only a
product. Both the customer and admin order-item response DTOs expose which configuration was
bought — added because order_item had carried the columns since migration 0028 with no surface
exposing either, so a customer's order history showed "iPhone 17 Pro" with no way to tell the
256GB they bought from the 1TB they did not.
| Surface | DTO | Identity field | Notes |
|---|---|---|---|
Customer (GET /:id, list) | OrderItemResponseDto | variantPublicId (uuid, not nullable) | product_variant.public_id, frozen at purchase |
Admin (GET /api/orders/:id, list) | OrderItemAdminDto | variantId (uuid, not nullable) | Same value, different field name — the admin DTO names it variantId even though it carries the variant's PUBLIC id, not the integer PK |
Both DTOs also carry variantName: string \| null. variantName is null exactly when the
variant was the product's sole configuration and carried no label of its own — render the
product name alone in that case, never the word "null", and never a label re-derived from the
variant's CURRENT name, which would rewrite what was actually bought. Both DTOs additionally
carry productPublicId/productId, productName, sku, unitPrice, mrp, quantity,
lineTotal and discountAmount — all in integer minor units.
7. Enum Reference
| Enum | Value | Meaning | Runtime Effect | Source |
|---|---|---|---|---|
order_status | created / confirmed / processing / partially_shipped / shipped / partially_delivered / delivered / completed / cancelled / returned / partially_returned | The order | Eleven values. returned and partially_returned come last in the enum and are derived from order_item.returned_quantity by deriveOrderStatus. There is no refunded | enums.ts |
order_refund_method | esewa_reversal / bank_transfer / cash / card_reversal / qr_reversal | How money goes back | Chosen at approval. The last two are valid only on a channel = 'pos' order (409 ORDER_REFUND_METHOD_NOT_ALLOWED otherwise) | enums.ts, migration 0070 |
| per-line label (derived) | unavailable / cancelled / delivered / partially_delivered / shipped / partially_shipped / processing | Display | Quantities are the truth | response builder |
8. Endpoint Reference
8.1 GET /api/mobile/orders
My purchase history. ORDER_NOT_FOUND semantics apply per row (no existence oracle).
8.2 GET /api/mobile/orders/:id
Full order: status, per-line quantities + derived label, the frozen variantPublicId/variantName per line (§6.6), pricing (minor units), shipment/return/refund summaries, the customer-visible timeline.
8.3 GET /api/mobile/orders/:id/status
Small payload for polling: order status, per-line labels, the latest customer-visible timeline entry, pollAfterSeconds. Honour pollAfterSeconds — it can be lengthened server-side under load without shipping a frontend. Reads recorded state only; cheap.
8.4 GET /api/mobile/orders/:id/invoice.pdf
Streams a receipt PDF, generated on demand, carrying verbatim and prominently: "This is a sales receipt for your records. It is NOT an official taxable invoice — no VAT or PAN registration is claimed." Never label it "Tax Invoice".
8.5 POST /api/mobile/orders/:id/cancel
Cancel before dispatch. Restock happens in the same transaction; a restock refusal rolls the cancellation back (ORDER_RESTOCK_REFUSED, 500, nothing changed). COD without codCollectedAt refunds nothing — the cancellation email says so.
Error Cases
| HTTP | Code | Condition |
|---|---|---|
| 404 | ORDER_NOT_FOUND | Unknown or another customer's |
| 409 | ORDER_TRANSITION_NOT_ALLOWED | Order moved |
| 409 | ORDER_NOT_CANCELLABLE | Already dispatched or delivered — offer a return (message says which) |
| 500 | ORDER_RESTOCK_REFUSED | Inventory declined; rolled back |
8.6 POST /api/mobile/orders/:id/returns (+ GET, + cancel)
Request a return on delivered lines within the window. Cancel releases the budget. The request body is RequestReturnDto (§6.4): at most 50 lines (MAX_RETURN_LINES; more is a 400 VALIDATION_FAILED on lines) and each item at most once.
| HTTP | Code | Condition |
|---|---|---|
| 400 | VALIDATION_FAILED | Over 50 lines, no lines, a malformed uuid, or a quantity outside 1 to 99 |
| 404 | ORDER_NOT_FOUND | Unknown order, another customer's order, or a line id that is not on the order |
| 409 | ORDER_RETURN_NOT_ELIGIBLE | Not delivered, or past the window (date in message) |
| 409 | ORDER_RETURN_QUANTITY_UNAVAILABLE | A double-tap — units already in a return, or more than is left to return; refresh |
| 422 | ORDER_RETURN_DUPLICATE_LINE | The same orderItemPublicId appears more than once in lines (case-insensitive). Rejected, never merged |
An uncollected cash-on-delivery order can be returned. The customer route and the admin route
no longer refuse a COD order whose cash has not been recorded (ORDER_RETURN_COD_UNCOLLECTED was
removed): the goods can come back whether or not the cash did. The collection check now happens
where every refund path meets — when the refund is approved (§8.10), with
ORDER_REFUND_COD_UNCOLLECTED. A return on such an order can therefore be opened, approved,
received and inspected, but its refund cannot be approved until a collection is recorded.
8.6a POST /api/order-returns (admin, open on behalf)
For a customer who asked off-platform (a phone call or a WhatsApp message). Returns_UPDATE,
throttled ADMIN_WRITE (10/min), Idempotency-Key required (scope order-return-on-behalf;
missing key is 400 IDEMPOTENCY_KEY_REQUIRED, reuse with a different payload is 409
IDEMPOTENCY_KEY_CONFLICT). Body: AdminOpenReturnDto (§6.4). Success is 201 with the same
OrderReturnAdminDetailDto the detail route returns.
It runs the customer route's service body, so the eligibility, window, budget and duplicate-line rules are identical. It differs only in who is recorded:
| Customer route | Admin route | |
|---|---|---|
| Ownership check | The order must belong to the caller | None — any order |
customerComment on the return | The customer's comment | null |
| Order event | actor: customer, reason = the comment | actor: admin, actorAdminId, reason: null, detail.openedOnBehalf: true and detail.adminComment |
| Activity log | — | order_return.opened_on_behalf (orderId, lineCount) |
The customer is still emailed the acknowledgement and the event is customer-visible; the operator's
comment is not shown to them (the customer timeline exposes reason, not detail).
Errors: the table in §8.6, except 404 ORDER_NOT_FOUND now means the order or a line does not exist
(there is no ownership to fail).
8.7 Admin order routes — POST /api/orders/:id/{confirm,processing,notes,shipments,shipments/:shipmentId/{deliver,fail}}
Transitions guarded by ORDER_TRANSITION_NOT_ALLOWED. Shipments take quantities + serial numbers — ORDER_SERIAL_COUNT_MISMATCH (more serials than units), ORDER_SERIAL_ALREADY_RECORDED (duplicate device — operator check). Deliver/fail close a parcel (ORDER_SHIPMENT_NOT_OPEN if already closed).
8.7b Serial numbers on dispatch, and release
Applies to POST /api/orders/:id/shipments (permission Orders_UPDATE). Serial rules (shared by retail dispatch and the POS counter; one implementation in apps/api/src/modules/order/shared/order-item-serial.util.ts):
| Rule | Behaviour |
|---|---|
| Normalisation | Each serial is trimmed and blanks are dropped. Each survivor must match ^[\x21-\x7E]{1,120}$ (printable ASCII, no internal space), else 400 ORDER_SERIAL_INVALID with details.index. |
| Request limits | lines[].serialNumbers is optional, at most 99 per line, each at most 128 raw characters (so surrounding spaces are tolerated). A serial with an internal space or non-ASCII character is 400. |
| Count | At most one serial per unit: 409 ORDER_SERIAL_COUNT_MISMATCH. |
| Duplicates | Checked across every line of the request and per product, case-sensitively: 409 ORDER_SERIAL_ALREADY_RECORDED with details.duplicates. |
| Active uniqueness | Unique per (product_id, serial_number) among rows with released_at IS NULL. An already-active serial is refused before the shipment exists, with details.conflicts. A race lost at the unique index returns the same code with details.conflicts: []. |
| Branch on | errorCode, not message. Serial values appear only in details. |
Release (a released serial stays as history and can be recorded again; rows are never deleted):
| Event | Releases | Reason |
|---|---|---|
POST /api/orders/{id}/shipments/{shipmentId}/fail, failed parcel | Every active serial of that shipment | shipment_failed |
| Same route, returned to sender | Every active serial of that shipment | shipment_returned_to_sender |
POST /api/order-returns/{id}/inspect, line accepted so that returnedQuantity + accepted >= deliveredQuantity | Every active serial of that order line | order_return |
| POS counter return | The picked serials; the remainder of a fully returned line | counter_return / order_return |
A partial return releases nothing: the inspect route takes no serial picks, so the system cannot know which unit came back. The shipment, order and customer views list released serials too, with no released flag. POS counter behaviour, deploy order (migration 0073, backend, POS app) and the mistyped-serial runbook: /docs/developer/pos/serials.
{
"courier": "Nepal Can Move",
"trackingNumber": "NCM-448812",
"lines": [
{
"orderItemId": "019ff58f-0956-722f-80c9-b5d7fc484b08",
"quantity": 2,
"serialNumbers": ["356938035643809", " 356938035643817 "]
}
]
}The second serial is trimmed and accepted.
8.7a Admin cash collection — POST /:id/cod-collection, PATCH /:id/cod-collection, POST /:id/cod-collection/reversal
A fulfilment fact, not a payment transition — the COD payment already succeeded at checkout; this
records what physically came back. Own leaf, own error codes (§7 above elides — see the table
below), own audit trail (order.cod_cash_collected, order.cod_cash_collection_corrected,
order.cod_cash_collection_reversed).
| HTTP | Code | Route | Condition |
|---|---|---|---|
| 404 | ORDER_NOT_FOUND | all three | Unknown order |
| 409 | ORDER_COD_COLLECTION_NOT_APPLICABLE | record | Not COD, not delivered, already counted, or the effective amount is zero (a zero-total order has no cash to collect) |
| 409 | ORDER_COD_COLLECTION_EXCEEDS_TOTAL | record, correct | Amount would exceed grandTotal |
| 409 | ORDER_COD_COLLECTION_NOT_RECORDED | correct, reverse | Nothing recorded yet to correct or undo |
| 409 | ORDER_COD_COLLECTION_STALE | correct | expectedCurrentAmount no longer matches what is recorded — refresh and retry |
| 409 | ORDER_COD_COLLECTION_BELOW_REFUNDED | record, correct | The amount would put the collected cash below the refunds already approved (committed) on the order |
| 409 | ORDER_COD_COLLECTION_REFUND_COMMITTED | reverse | A refund on the order is already awaiting_settlement or settled |
Refund interplay (refund approval requires recorded cash). Refund approval on a COD order is capped at the cash actually collected (§8.10), so the cash figure may no longer move out from under an approved refund:
- Correct refuses an
amountbeloworder.refundedAmount(the sum of refunds that are approved or settled). An amount equal to it is allowed. - Record refuses an effective amount below
order.refundedAmountonly on an order that has no collection yet. That is reachable solely for an order whose refunds were approved before approval required a collection, and without it the figure could start below the refunds and every later downward correction would be refused. A non-COD or already-collected order still getsORDER_COD_COLLECTION_NOT_APPLICABLE. - Reverse refuses while any refund on the order is
awaiting_settlementorsettled. A refund that is onlyrequestedorrejecteddoes not block it — approval re-checks the collection. The recoverable path is to correct the amount instead.
All three checks run under the same order row lock refund approval takes, so an approval and a reversal racing on one order serialise: the order ends up with exactly one of "refund approved" or "collection reversed", never both. Messages are written for operators and safe to show verbatim.
Recording is single-fire (cod_collected_at IS NULL in the write's WHERE clause) — a replay is
reported as ORDER_COD_COLLECTION_NOT_APPLICABLE rather than overwriting the figure. Correcting
under-collection stays legal and warns rather than refusing: a courier handing back less than
expected is a real event, recorded on the order's timeline.
8.8 POST /api/orders/:id/refunds
Create a refund from order lines — server computes the money from the net ceilings. ORDER_REFUND_EXCEEDS_PAID (409) if it would exceed what is left to give back — reachable with no operator fault (two people approving at once); say the figure changed and refresh.
8.9 Return admin — /api/order-returns/:id/{decide,receive,inspect}
ORDER_RETURN_TRANSITION_NOT_ALLOWED on wrong-state steps; ORDER_RETURN_INSPECTION_INVALID names which quantities or the missing rejection reason. Opening a return on a customer's behalf (POST /api/order-returns) is §8.6a.
8.10 Refund admin — /api/order-refunds/:id/{approve,reject,settle}
-
approve — choose the method (DTO per §6.2). Refusals, all 409:
Code Condition ORDER_REFUND_TRANSITION_NOT_ALLOWEDThe refund is no longer requested(checked first, so a stale double-click hears that the refund moved on, not a COD message)ORDER_REFUND_COD_UNCOLLECTEDCOD order with no recorded cash collection. Record the collection if the cash was received; otherwise reject the refund ORDER_REFUND_EXCEEDS_COD_COLLECTEDorder.refundedAmount + this refund's amountis greater than the cash collected. The cap iscodCollectedAmount, notpaidAmount(which for COD is the checkout total whether or not the courier handed it all back). Equal to the cash collected is allowedORDER_REFUND_EXCEEDS_PAIDA database ceiling lost a race between two approvals (see §8.8) order.refundedAmountcounts refunds that are already approved or settled, so a refund that is onlyrequesteddoes not count against the cap until it is approved. Every refund path — an operator draft, a return inspection, a cancellation — reaches money through approve, so the COD guard lives here and nowhere else. The checks read the order under the same row lock COD record, correct and reversal take. Refunds approved before this guard shipped are not re-checked at settle:settlehas no COD check, so anawaiting_settlementrefund on an uncollected COD order still settles. Count them before deploying:awaiting_settlementrefunds joined to COD orders withcod_collected_at IS NULL. Once a refund is approved, the collection behind it can no longer be reversed (§8.7a). -
reject —
pendingonly; an approved refund can never be rejected (ORDER_REFUND_TRANSITION_NOT_ALLOWED). -
settle — settlement reference required (§6.3). This is where a human records that money actually moved; no gateway refund is integrated.
9. Flow Diagrams
9.1 Route Ownership
9.2 Request Sequence (cancel)
9.3 Error Branch (refund settle)
10. Pagination, Sorting, Filtering, and Search
| Endpoint | Pagination Type | Default Size | Max Size | Sort Fields | Filters |
|---|---|---|---|---|---|
GET /api/mobile/orders | offset page/size | 20 | 100 | standard | status, date |
GET /api/orders | offset page/size | 20 | 100 | standard | status, paymentMethod, channel (online/pos/whatsapp), customer, order number, date, totals |
GET /api/order-returns | offset page/size | 20 | 100 | standard | status, order |
GET /api/order-refunds | offset page/size | 20 | 100 | standard | status — the finance queue |
11. Caching, Jobs, and External Integrations
| Integration | Used? | Details |
|---|---|---|
| Redis cache | No | Status reads recorded state only |
| BullMQ | Yes | ORDER queue — CREATE_ORDER from the outbox row + email jobs |
| Yes (optional key) | RESEND_API_KEY optional; without it emails render/queue and are logged instead of delivered | |
| Gateway refund | No | Settlement is human; reference required by constraint |
13. Mandatory Deep API Documentation Pack
13.1 Route-by-Route Completeness Matrix
| Route | Controller Method | Service Method | Guards | Permissions | DB Touches | Errors | Documented? |
|---|---|---|---|---|---|---|---|
GET /api/mobile/orders | findAll | OrderCustomerService.list | JWT | — | orders | — | Yes |
GET /api/mobile/orders/:id | findById | …findOne | JWT | — | order + lines | 404 | Yes |
GET /:id/status | status | …status | JWT | — | order | 404 | Yes |
GET /:id/invoice.pdf | invoice | …invoice | JWT | — | order | 404 | Yes |
POST /:id/cancel | cancel | …cancel | JWT | — | order + restock | 404/409/500 | Yes |
POST /:id/returns | requestReturn | return service | JWT | — | order, items | 400/404/409/422 | Yes |
GET /:id/returns | listReturns | — | JWT | — | returns | 404 | Yes |
POST /:id/returns/:returnId/cancel | cancelReturn | return service | JWT | — | return | 404/409 | Yes |
GET /api/orders | findAll | OrderAdminService.list | JWT+Role | Orders_READ | orders | — | Yes |
GET /api/orders/:id | findById | …findOne | JWT+Role | Orders_READ | order | 404 | Yes |
POST /:id/{confirm,processing,cancel,notes} | 4 methods | admin service | JWT+Role | Orders_UPDATE | order + events | 404/409 | Yes |
POST /:id/shipments | ship | admin service | JWT+Role | Orders_UPDATE | shipment + serials | 404/409 | Yes |
POST /:id/shipments/:shipmentId/{deliver,fail} | 2 methods | admin service | JWT+Role | Orders_UPDATE | shipment | 404/409 | Yes |
POST /:id/cod-collection | record | OrderCodAdminService.record → OrderLifecycleService | JWT+Role | Orders_UPDATE | order (row lock) + event | 404/409 | Yes |
PATCH /:id/cod-collection | correct | OrderCodAdminService.correct → OrderLifecycleService | JWT+Role | OrderCash_UPDATE | order (row lock) + event | 404/409 | Yes |
POST /:id/cod-collection/reversal | reverse | OrderCodAdminService.reverse → OrderLifecycleService | JWT+Role | OrderCash_DELETE | order (row lock) + event | 404/409 | Yes |
POST /api/orders/:id/refunds | createRefund | refund service | JWT+Role | Refunds_UPDATE | refund rows | 404/409 | Yes |
GET /api/order-returns / /:id | 2 methods | return service | JWT+Role | Returns_READ | returns | 404 | Yes |
POST /api/order-returns | openOnBehalf | OrderReturnAdminService.openOnBehalf → OrderReturnService.requestOnBehalf | JWT+Role + IpThrottlerGuard + IdempotencyInterceptor | Returns_UPDATE | order (row lock), return, return items, order items, order event, outbox | 400/404/409/422 | Yes |
POST /:id/{decide,receive,inspect} | 3 methods | return service | JWT+Role | Returns_UPDATE | return rows | 404/409 | Yes |
GET /api/order-refunds | findAll | refund service | JWT+Role | Refunds_READ | refunds | — | Yes |
POST /:id/{approve,reject,settle} | 3 methods | refund service | JWT+Role | Refunds_UPDATE | refund rows | 400/404/409 | Yes |
13.2 Request/Response Exhaustiveness
Covered in §8: refund-create without amount (§6.1/8.8), approve-with-method (§6.2), settle-with-reference (§6.3), the receipt disclaimer (§8.4), short-order shape (unavailableQuantity + label), domain errors per endpoint (§8 error tables), the two 409s that are not failures (RETURN_QUANTITY_UNAVAILABLE, REFUND_EXCEEDS_PAID).
13.3 API Diagram Pack
Route ownership (§9.1), sequence per endpoint family (§9.2, backend §7), error decision tree (§9.3), async flow (backend §7.1 — the outbox chain).
13.4 Consumer Integration Notes
| Consumer | Required Knowledge | Failure Handling | Contract Stability |
|---|---|---|---|
| Web frontend | Eleven statuses (returned and partially_returned included, no refunded); derived labels; receipt ≠ tax invoice | 409s per §8; double-tap return = refresh | Stable |
| Mobile app | pollAfterSeconds; COD refund-absence on cancel | ORDER_NOT_CANCELLABLE → offer return | Stable |
| Admin panel | Three permission modules; serials at dispatch; refund settle queue; channel on every order; a COD return can be opened before cash is collected, but its refund approval is refused until it is | REFUND_EXCEEDS_PAID → refresh; ORDER_REFUND_COD_UNCOLLECTED / ORDER_REFUND_EXCEEDS_COD_COLLECTED / ORDER_COD_COLLECTION_* → show the server message (written for operators) | Stable; new 409 codes are additive |
| QA | Quantities-as-truth; short orders; return budget | Reproduce via exact codes | Stable |
| Finance | awaiting_settlement queue; reference required | — | Stable |
13.5 API Tradeoffs and Rationale
| Decision | Chosen Behavior | Alternatives Considered | Why This Tradeoff | Risk | Mitigation |
|---|---|---|---|---|---|
| Background creation | Outbox chain | Synchronous | Paid customer never without a record | Delay | Unique index |
No refunded status | Refund state lives on the refund rows, not the order | Statuses | Derived badges | Client assumption | Documented |
| No item status | Quantities add up | Label column | Client work | Label provided | |
| Server computes refund money | No caller amounts | Client amounts | Ceilings enforced | — | CHECKs |
| Human-settled refunds | Money control | Gateway auto | Manual queue | Reference constraint | |
| Three permission modules | Least privilege | One Orders module | Warehouse can't refund | — | Documented |
13.6 API Change Impact
| Change | Affected Consumers | Backend Impact | Data Impact | Migration Needed? | Compatibility Plan |
|---|---|---|---|---|---|
| Fulfillment module later | Dispatch routes | Split services | None | No | Rows shaped for takeover |
| Gateway refund later | Settle flow | New integration | None | No | Human path remains |
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, enum, default, transform and validator is documented (§6, §7).
- Every response field and nullable field is documented (§8).
- Every auth, guard, permission and guest identity branch is documented (§5).
- Every success, validation, not-found, conflict, rate-limit and server-error branch is documented (§8).
- Every DB read/write, queue job and external call is documented (§11, backend §9).
- Every route has examples for minimal request, success response and representative failures (§8).
- Every endpoint family has route, sequence and error diagrams (§9, backend §7).
- Every tradeoff and compatibility risk is documented (§13.5, §13.6).
- The API doc links to backend and features/flows (§1, 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/order/backend
- Features and flows doc: /docs/developer/order/feature
- TDD: not yet published
Order Backend Documentation
Backend architecture, data model, services, and operational behavior for the Order module.
Manual (WhatsApp) Orders
Orders an administrator enters by hand from a WhatsApp chat — routes, permissions, channel allow-list, payment, fulfilment, customer matching and provisioning, idempotency, errors and the minimal create response.