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.
Audience: Admin-panel engineers, backend engineers, QA Scope:
POST /api/orders/manual,POST /api/orders/manual/quote,GET /api/orders/manual/customers, and thechannelfilter and field on the admin order list
Manual (WhatsApp) Orders
1. Documentation Evidence
| Area | Files Inspected | What Was Verified |
|---|---|---|
| Controller | apps/api/src/modules/pos/admin/manual-order/manual-order-admin.controller.ts | Routes, permissions, throttles, idempotency wiring |
| DTOs | .../manual-order/dto/manual-order-request.dto.ts, manual-order-response.dto.ts | Every field, limit and validator |
| Services | .../manual-order/manual-order.service.ts, manual-order-customer.service.ts | Transaction steps, payment rules, customer decision table, error codes and statuses |
| Shared POS pipeline | apps/api/src/modules/pos/shared/pos-sale-completion.service.ts, pos-checkout-materializer.service.ts, pos-sale-number.service.ts, pos-mail-queue.service.ts | completeWithin, WA sale number, payment attempt, invite outbox row |
| Error registry | apps/api/src/common/types/error-codes.ts (MANUAL ORDERS) | The MANUAL_ORDER_* codes |
| Error envelope | apps/api/src/common/filters/all-exceptions.filter.ts | details passthrough |
| Idempotency | apps/api/src/common/idempotency/idempotency.interceptor.ts, idempotency.service.ts | Header, scope, replay, TTL |
| Order admin list | apps/api/src/modules/order/admin/order/{dto,order-admin.service.ts,order-admin.builder.ts} | channel filter and field |
| Schema | packages/db/src/schema/pos/pos-sale.ts, migrations 0054 to 0057 | channel, prefix, status and payment CHECKs |
2. What this is
An administrator takes an order in a WhatsApp chat and enters it in the admin panel. The backend runs it through the same pipeline as a counter (POS) sale — draft, lines, stock reservation, materialised checkout, payment attempt, order — in one database transaction. The differences are the channel the rows carry (whatsapp) and that nothing is handed over now.
| Fact | Value |
|---|---|
| Channel | whatsapp (the only value the manual routes accept) |
| Module | Lives in the POS admin module (modules/pos/admin/manual-order/), mounted under the orders prefix |
| Sale number | WA-2026-000001, from its own sequence whatsapp_sale_number_seq (never consumes a till number) |
| Order number | The ordinary order series (HS-2026-000001) |
| Stock source | Movements are written with inventory_source = 'whatsapp' |
| Payment attempt | gatewayTransactionId is WA- plus the sale number; gatewayReference is the payment reference |
| Opening email | Sent like any order the customer does not hold (handover: false). No counter receipt is queued |
| POS isolation | The POS routes only see channel = 'pos' sales. A WhatsApp sale answers POS_SALE_NOT_FOUND on every POS route |
3. Routes and permissions
| Method | Path | Success | Permissions | Throttle | Idempotency |
|---|---|---|---|---|---|
POST | /api/orders/manual | 201 | Orders_CREATE and Pos_READ | ADMIN_POS_COMPLETE — 30/min per user | Idempotency-Key required |
POST | /api/orders/manual/quote | 200 | Orders_CREATE and Pos_READ | PUBLIC_SEARCH — 60/min per IP and device | — |
GET | /api/orders/manual/customers | 200 | Orders_CREATE and Pos_READ | PUBLIC_SEARCH — 60/min per IP and device | — |
All three use JwtAuthGuard and RoleGuard; RoleGuard requires every listed permission.
Why Pos_READ is also required. It is the till's deliberate customer-PII gate. All three routes can reveal a customer: the search lists them, and a create or quote that matches an existing account answers with its id, name and verification flags. Without Pos_READ on create, the search's gate could be walked around by submitting orders.
orders/manual is not captured by the orders/:id routes: no existing orders controller declares a one-segment POST, POST :id/quote or GET :id/customers.
4. Create — POST /api/orders/manual
The global ValidationPipe runs with whitelist and forbidNonWhitelisted: an unknown property anywhere in the body is a 400 (VALIDATION_FAILED).
4.1 Body
| Field | Type | Required | Rules |
|---|---|---|---|
channel | string | Yes | whatsapp only |
customer | object | Yes | Discriminated on kind — see §4.2 |
lines | array | Yes | 1 to 50 entries — see §4.3 |
fulfilment | object | Yes | Discriminated on type — see §4.4 |
payment | object | Yes | See §4.5 |
note | string | No | Max 1000 chars. Stored as an internal order note; never shown to the customer |
An unknown customer.kind or fulfilment.type is a 400, not a fall-through.
4.2 customer
kind: "existing"
| Field | Type | Rules |
|---|---|---|
customerPublicId | uuid | The customer's id, usually from the search route (§8) |
kind: "new"
| Field | Type | Rules |
|---|---|---|
name | string | Trimmed, non-empty, max 120 |
phone | string | Normalised to E.164 with region NP, so 9812345678 is accepted and stored as +9779812345678. Must match ^\+[1-9][0-9]{7,14}$ after normalising |
email | string | Required. Trimmed, lower-cased, valid email, max 320. It is the account id and where the set-password invitation goes |
detachPhone | boolean | Optional resubmit flag after a phone match (§6): create the customer without linking the phone |
4.3 lines[]
| Field | Type | Rules |
|---|---|---|
variantPublicId | uuid | The configuration being sold (every product has at least one variant) |
quantity | integer | 1 to 99 |
expectedUnitPrice | integer, minor units | >= 0. Required. The unit price the latest quote returned |
Prices come from the catalogue, never from the chat. expectedUnitPrice is compared, not charged blind: if any line's current price (campaign applied) differs, the whole order is refused with POS_PRODUCT_PRICE_CHANGED and details.lines lists every line that moved. The same variant twice — including two spellings of one uuid — is MANUAL_ORDER_DUPLICATE_LINE.
4.4 fulfilment
type: "pickup" — no other fields. Shipping is 0.
type: "delivery"
| Field | Type | Rules |
|---|---|---|
shippingAmount | integer, minor units | 0 to 10,000,000. Set by the administrator; the backend does not compute it |
address | object | A new address, saved to the customer's book. Required unless addressPublicId is sent |
addressPublicId | uuid | An address the customer already has |
Sending both address and addressPublicId is a 409 POS_DELIVERY_ADDRESS_REQUIRED ("choose a saved address or enter a new one, not both"). A saved address that is not the order customer's, or is soft-deleted, is a 404 POS_ADDRESS_NOT_FOUND; the same check applies when the customer is newly provisioned in the same request, and the whole transaction rolls back.
address fields:
| Field | Type | Rules |
|---|---|---|
districtPublicId | uuid | Must exist, else 422 MANUAL_ORDER_DISTRICT_NOT_FOUND |
municipalityName | string | Non-empty, max 120 |
ward | integer | 1 to 40 |
recipientName | string | Non-empty, max 120 |
recipientPhone | string | E.164 as sent (+9779812345678); this field is not normalised |
street | string | Non-empty, max 200 |
landmark | string | Optional, max 200 |
postalCode | string | Optional, exactly five digits |
4.5 payment and the rules behind it
method | reference | Meaning |
|---|---|---|
cod | Must be absent — 409 POS_PAYMENT_REFERENCE_NOT_ALLOWED | Cash on delivery. Stays uncollected until an administrator records the cash (POST /api/orders/:id/cod-collection) |
pos_qr | Required, max 120 chars | Already paid by QR or bank transfer |
pos_card | Required, max 120 chars | Already paid by card |
referenceis trimmed. A blank reference counts as absent: forpos_qrandpos_cardthat is 422MANUAL_ORDER_PAYMENT_REFERENCE_REQUIRED.pos_cashis not accepted (400VALIDATION_FAILED). Cash from a chat customer is cash on delivery, and recording it as already taken would be a sale nobody can reconcile against a till.esewaandonlineare rejected the same way.- The service re-checks the method against a per-channel allow-list and answers 422
MANUAL_ORDER_PAYMENT_METHOD_NOT_ALLOWEDfor a method the DTO admits but the channel does not. Today the DTO and thewhatsappallow-list both holdcod,pos_qr,pos_card, so this code is not reachable forwhatsapp; it exists for a future channel. - The database backs this up:
chk_pos_sale_pos_not_codforbidscodonchannel = 'pos'sales (migration 0057), andchk_pos_sale_payment_reference_methodforbids a reference on a method other thanpos_cardorpos_qr.
4.6 What happens, in order
All inside one db.transaction. Any failure rolls back every step, including stock holds, the new account and the invite row; there is no compensating release.
- Resolve every line against the catalogue (one query). Unknown variant: 404
POS_VARIANT_NOT_SELLABLE. Duplicate: 400MANUAL_ORDER_DUPLICATE_LINE. Unpublished, withdrawn, soft-deleted or priced above MRP: 409POS_PRODUCT_NOT_SELLABLE. Price differs fromexpectedUnitPrice: 409POS_PRODUCT_PRICE_CHANGED. - Resolve the district (delivery with a new address).
- Resolve or provision the customer (§6).
- Open the draft sale with
channel = 'whatsapp', then set fulfilment (delivery) — this creates the address row if a new address was sent. - Add the lines, frozen at the quoted price.
- If the customer was provisioned, queue the set-password invitation.
- Complete: reserve stock (409
POS_INSUFFICIENT_STOCKwhen short), materialise the checkout session, record the payment attempt, create the order. A price that moved between step 1 and the lock is caught again here and re-thrown asPOS_PRODUCT_PRICE_CHANGEDwith every moved line. - Insert the internal order note (if
notewas sent). - Record the admin-only order event
order.manual_entry_recorded(channel,source: "manual_entry",posSalePublicId). It is not customer-visible; it is the attribution of who entered the order, since the order module's opening events saysystem. - After commit: storefront/cache invalidation, as the till does.
A new customer's typed phone is recorded on the order and the address even when the customer row does not hold it (§6, rule 6).
4.7 Fulfilment after creation
| Type | Result |
|---|---|
pickup | The sale is ordered, not picked_up: the goods are not handed over now. The order then follows its own POST /api/orders/:id/ready-for-pickup and POST /api/orders/:id/collect steps. A pickup WhatsApp sale at ordered is legal only for channel = 'whatsapp' (chk_pos_sale_status_completion) |
delivery | The sale is ordered; the order follows the ordinary confirm, dispatch and deliver routes |
5. Idempotency
Idempotency-Key is required. A timeout after the order committed is the one failure the admin cannot see the outcome of; a retry under the same key replays the stored response instead of taking stock and money twice.
| Case | Result |
|---|---|
| No header (or blank) | 400 IDEMPOTENCY_KEY_REQUIRED |
| Same key, same actor, same method/path/query/body | Replays the stored status (201) and body; no second order |
| Same key, different payload | 409 IDEMPOTENCY_KEY_CONFLICT |
| Same key while the first request is still running | 409 IDEMPOTENCY_REQUEST_IN_PROGRESS (pending marker lives 120 s) |
| First request failed (any error) | The key is released; a retry under the same key runs afresh |
The stored success is kept for 24 hours. The key is scoped to the acting administrator and the scope order-manual-create.
IdempotencyInterceptor is not global; the controller names it explicitly with @UseInterceptors(IdempotencyInterceptor), and ManualOrderAdminModule imports IdempotencyModule.
6. Customer lookup, matching and auto-provisioning
An administrator typing a name, phone and email from a chat is making a claim, not an identity. The backend never silently attaches the order to a matching account; it answers 409 with a masked preview and the admin picks that customer explicitly (resubmitting as kind: "existing").
Attachable means: the account is live (not soft-deleted, status active) and someone has vouched for it — the customer verified an email or a phone, or a pos_sale of any channel created the account (customer_created = true). The last clause means a customer the shop created from a chat is attachable on the next order.
6.1 kind: "existing"
| Condition | Result |
|---|---|
| No such customer | 404 USER_NOT_FOUND |
Soft-deleted or not active | 409 MANUAL_ORDER_CUSTOMER_CLOSED |
| Not attachable | 409 MANUAL_ORDER_CUSTOMER_UNVERIFIED, no details (the admin chose by id, so there is no match to preview) |
| Otherwise | Order attaches. The order copies the customer's own phone |
6.2 kind: "new" — decision table
E = the customer holding this email (matched on lower(email), including closed accounts; a live row is preferred). P = the customer holding this phone (exact match, then a trailing-8-digit candidate set confirmed by normalising each stored number, because the till stored phones as typed). First matching row wins.
| # | Condition | Result |
|---|---|---|
| 1 | E and P both exist, differ, and P is attachable | 409 MANUAL_ORDER_CUSTOMER_CONFLICT |
| 2 | E exists and is not live | 409 MANUAL_ORDER_CUSTOMER_CLOSED |
| 3 | E is attachable | 409 MANUAL_ORDER_CUSTOMER_EXISTS with details (matched by email) |
| 4 | E is live but not attachable | 409 MANUAL_ORDER_CUSTOMER_UNVERIFIED with details (no customerPublicId) |
| 5 | No E; P attachable and detachPhone is not true | 409 MANUAL_ORDER_CUSTOMER_EXISTS with details (matched by phone) |
| 6 | No E; P exists otherwise (or detachPhone: true) | Provision a new customer with phone = null; the typed phone is still recorded on the order and address |
| 7 | Neither | Provision a new customer with the typed phone |
Rule 6 is the phone-squat defence: a number already held by an unverified or closed account is not handed to the new account, and the response does not reveal that the number was taken. For the same reason rule 1 applies only when the phone's owner is attachable; otherwise the email rules (2 to 4) decide.
Concurrent creates. The reads cannot stop two requests creating the same customer; the unique indexes (customers_email_unique, customers_phone_unique) do. The decision runs in a savepoint and is re-run once after a lost race. A second loss answers MANUAL_ORDER_CUSTOMER_EXISTS without details ("created at the same moment — search for them").
6.3 Provisioning and the invitation
A new customer is provisioned exactly as the till does it: a customers row plus a password-less account, unverified. A customer_created event is written on the sale (it carries the email, never a token).
The set-password invitation is an outbox row (pos.walk_in_created, POS queue job SEND_WALK_IN_INVITE) queued inside the order transaction, deduplicated on the customer id so one account gets one invitation. The worker mints the single-use token; no credential is stored in the outbox row. The invitation link does not expire and works once.
The invitation email reuses the counter's copy ("thanks for shopping with us in-store", "during your visit"). It is not WhatsApp-specific.
6.4 details shapes for the customer 409s
{
"statusCode": 409,
"errorCode": "MANUAL_ORDER_CUSTOMER_EXISTS",
"message": "A customer with this email already exists. Use that customer for the order.",
"details": {
"customerPublicId": "018f1e2a-0000-7000-8000-000000000001",
"matchedBy": "email",
"preview": {
"name": "Sita Sharma",
"emailMasked": "s***@example.com",
"phoneMasked": "+977*****678",
"emailVerified": true,
"phoneVerified": false
}
}
}| Code | details |
|---|---|
MANUAL_ORDER_CUSTOMER_EXISTS | customerPublicId, matchedBy (email or phone), preview — absent after a second lost race |
MANUAL_ORDER_CUSTOMER_UNVERIFIED (new customer) | matchedBy (email), preview — no customerPublicId |
MANUAL_ORDER_CUSTOMER_UNVERIFIED (existing customer) | none |
MANUAL_ORDER_CUSTOMER_CONFLICT, MANUAL_ORDER_CUSTOMER_CLOSED | none |
preview.emailMasked keeps the first character and the domain (s***@example.com); phoneMasked keeps only the last three digits (+977*****678). Both are null when the account has none.
7. Responses
7.1 The details envelope
Every API error body is { statusCode, errorCode, message } plus, in non-production, timestamp and path. The filter now also emits details — but only when the thrown exception carried a details key, so every other error body is unchanged. Clients that branch on errorCode and need more than the code (the matched customer, the moved prices) read details. Whatever a thrower puts there reaches the client; the manual-order throwers put only ids, masked previews and prices.
Two existing checkout refusals also surface it now, because they already attached fields to the exception and the filter used to drop them: the checkout-not-ready 409 (blockingReasons, unavailableVariantIds, shortfalls) and CHECKOUT_COUPON_NOT_APPLICABLE (couponCode, reason, which is null when the coupon was not found).
POS_PRODUCT_PRICE_CHANGED:
{
"statusCode": 409,
"errorCode": "POS_PRODUCT_PRICE_CHANGED",
"message": "Prices changed since you quoted the customer — confirm the new total with them.",
"details": {
"lines": [
{ "variantPublicId": "019ff58f-0956-722f-80c9-b5d7fc484b08", "currentUnitPrice": 47000 }
]
}
}7.2 Create success — 201
The envelope is { message: "Order created successfully", data } where data is the full admin order detail (OrderAdminDetailDto, the same shape as GET /api/orders/:id, with channel: "whatsapp").
Minimal response. The order has committed before the detail is read back. If that read fails, throwing would reach the idempotency interceptor as a failure, release the key, and a retry would create a second order. So the request still succeeds, logs the error class only, and answers with just the identifiers:
{
"message": "Order created successfully",
"errorCode": null,
"data": {
"id": "0198f2c1-4a3b-7c1d-9e2f-1a2b3c4d5e6f",
"orderNumber": "HS-2026-000123"
}
}id is the order's public id (the detail's own key name). Clients must redirect on data.id and must not assume any other detail field is present.
7.3 Example create request
{
"channel": "whatsapp",
"customer": {
"kind": "new",
"name": "Sita Sharma",
"phone": "9812345678",
"email": "sita.sharma@example.com"
},
"lines": [
{
"variantPublicId": "019ff58f-0956-722f-80c9-b5d7fc484b08",
"quantity": 2,
"expectedUnitPrice": 45000
}
],
"fulfilment": {
"type": "delivery",
"shippingAmount": 15000,
"address": {
"districtPublicId": "018f1e2a-0000-7000-8000-000000000027",
"municipalityName": "Lalitpur Metropolitan City",
"ward": 5,
"recipientName": "Sita Sharma",
"recipientPhone": "+9779812345678",
"street": "Jhamsikhel, Ward 5"
}
},
"payment": { "method": "pos_qr", "reference": "TXN-88213" },
"note": "Customer asked for evening delivery."
}Send it with Authorization: Bearer <token> and Idempotency-Key: <unique per submission>. This example was assembled from the DTO definitions and has not been executed against a running server.
8. Quote — POST /api/orders/manual/quote
Read-only: no write, no reservation. Create re-checks everything, so a quote is advisory.
Body: the create body with everything but lines optional, and expectedUnitPrice optional (and ignored) on each line. Same line rules (1 to 50 lines, quantity 1 to 99). customer, payment and note are accepted but not evaluated; only lines and fulfilment (for the delivery shippingAmount) affect the result. Shipping is 0 when no delivery fulfilment is sent.
Response data (ManualOrderQuoteResponseDto; all amounts integer minor units):
| Field | Type | Notes |
|---|---|---|
currency | string | NPR |
lines[].variantPublicId | uuid | |
lines[].productName | string | |
lines[].variantName | string | Empty string when the product's only configuration has no label |
lines[].sku | string or null | Variant SKU, else product SKU |
lines[].unitPrice | integer | Campaign applied. This is what to send as expectedUnitPrice |
lines[].quantity | integer | |
lines[].lineTotal | integer | |
lines[].available | integer or null | null when stock is not tracked for this configuration |
lines[].sellable | boolean | False when the configuration or product is withdrawn, unpublished, priced above MRP, or has no current price |
subtotal, shippingAmount, grandTotal | integer | grandTotal = subtotal + shippingAmount, by the till's own arithmetic |
Errors: 404 POS_VARIANT_NOT_SELLABLE (unknown variant), 400 MANUAL_ORDER_DUPLICATE_LINE, 400 VALIDATION_FAILED. An unsellable line is flagged (sellable: false), not refused.
9. Customer search — GET /api/orders/manual/customers
| Query | Type | Rules |
|---|---|---|
q | string | Name, email or phone; max 100. Fewer than 2 characters after normalising is 400 VALIDATION_FAILED |
size | integer | 1 to 20 |
Response data: an array of { customerPublicId, name, email, phone } (email and phone nullable). Only live, active customers are returned; soft-deleted and pending-deletion accounts are excluded. The result is the first page only.
Note this lists accounts regardless of whether they are attachable (§6). Choosing an unverified one still ends in MANUAL_ORDER_CUSTOMER_UNVERIFIED at create time.
10. Error reference
| HTTP | Code | Raised when |
|---|---|---|
| 400 | VALIDATION_FAILED | Any DTO violation, including unknown keys, pos_cash/esewa/online, channel other than whatsapp, quantity outside 1 to 99, 0 or more than 50 lines, a missing expectedUnitPrice, a bad phone |
| 400 | IDEMPOTENCY_KEY_REQUIRED | Create without Idempotency-Key |
| 400 | MANUAL_ORDER_DUPLICATE_LINE | Two lines resolve to the same variant |
| 401 / 403 | auth codes | Missing token; missing Orders_CREATE or Pos_READ |
| 404 | POS_VARIANT_NOT_SELLABLE | A variantPublicId does not exist |
| 404 | USER_NOT_FOUND | kind: "existing" and no such customer |
| 404 | POS_ADDRESS_NOT_FOUND | addressPublicId is not the order customer's live address |
| 409 | MANUAL_ORDER_CUSTOMER_EXISTS | §6 rules 3 and 5, or a second lost create race. Carries details except after the race |
| 409 | MANUAL_ORDER_CUSTOMER_UNVERIFIED | §6 rule 4, or an unattachable existing customer |
| 409 | MANUAL_ORDER_CUSTOMER_CONFLICT | §6 rule 1 |
| 409 | MANUAL_ORDER_CUSTOMER_CLOSED | Closed or non-active account |
| 409 | POS_PRODUCT_NOT_SELLABLE | A line is unpublished, withdrawn, soft-deleted or priced above MRP |
| 409 | POS_PRODUCT_PRICE_CHANGED | A line's current price differs from expectedUnitPrice. details.lines lists every moved line |
| 409 | POS_INSUFFICIENT_STOCK | Not enough stock at completion |
| 409 | POS_PAYMENT_REFERENCE_NOT_ALLOWED | cod with a reference |
| 409 | POS_DELIVERY_ADDRESS_REQUIRED | Both address and addressPublicId sent |
| 409 | IDEMPOTENCY_KEY_CONFLICT | Key reused with a different payload |
| 409 | IDEMPOTENCY_REQUEST_IN_PROGRESS | Same key still running |
| 422 | MANUAL_ORDER_DISTRICT_NOT_FOUND | districtPublicId does not exist |
| 422 | MANUAL_ORDER_PAYMENT_REFERENCE_REQUIRED | pos_qr/pos_card with no (or blank) reference |
| 422 | MANUAL_ORDER_PAYMENT_METHOD_NOT_ALLOWED | Method refused for the channel (not reachable for whatsapp today) |
| 429 | throttle | Over the route's limit |
11. Order list: channel filter and field
GET /api/ordersacceptschannel— one ofonline,pos,whatsapp. Anything else is 400. It filtersorder.channel; the count query shares the sameWHERE, so pagination stays correct.- Every admin order object (list items and
GET /api/orders/:id, which extends the list DTO) now carrieschannel:online(storefront),pos(the counter) orwhatsapp(entered by an administrator from a chat). The field is additive. order.channelandcheckout_session.channelare copies ofpos_sale.channelmade at materialisation; the three columns share thesales_channelenum.
12. Flow
See Also
- Order API reference: /docs/developer/order/api
- Order backend: /docs/developer/order/backend
- POS (the pipeline this reuses): /docs/developer/pos/backend
- Runtime config for the storefront WhatsApp button: /docs/developer/config/api
Order API Reference
Complete API contracts for the Order module, including routes, auth, DTOs, responses, errors, examples, and integration notes.
POS Module Overview
The admin-only counter till — draft sales, walk-in customers, pickup or delivery, completion that takes money, moves stock and creates an ordinary order in one transaction, and counter returns.