Nano Store - Ecommerce Docs
Developer ResourcesOrder

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 the channel filter and field on the admin order list

Manual (WhatsApp) Orders

1. Documentation Evidence

AreaFiles InspectedWhat Was Verified
Controllerapps/api/src/modules/pos/admin/manual-order/manual-order-admin.controller.tsRoutes, permissions, throttles, idempotency wiring
DTOs.../manual-order/dto/manual-order-request.dto.ts, manual-order-response.dto.tsEvery field, limit and validator
Services.../manual-order/manual-order.service.ts, manual-order-customer.service.tsTransaction steps, payment rules, customer decision table, error codes and statuses
Shared POS pipelineapps/api/src/modules/pos/shared/pos-sale-completion.service.ts, pos-checkout-materializer.service.ts, pos-sale-number.service.ts, pos-mail-queue.service.tscompleteWithin, WA sale number, payment attempt, invite outbox row
Error registryapps/api/src/common/types/error-codes.ts (MANUAL ORDERS)The MANUAL_ORDER_* codes
Error envelopeapps/api/src/common/filters/all-exceptions.filter.tsdetails passthrough
Idempotencyapps/api/src/common/idempotency/idempotency.interceptor.ts, idempotency.service.tsHeader, scope, replay, TTL
Order admin listapps/api/src/modules/order/admin/order/{dto,order-admin.service.ts,order-admin.builder.ts}channel filter and field
Schemapackages/db/src/schema/pos/pos-sale.ts, migrations 0054 to 0057channel, 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.

FactValue
Channelwhatsapp (the only value the manual routes accept)
ModuleLives in the POS admin module (modules/pos/admin/manual-order/), mounted under the orders prefix
Sale numberWA-2026-000001, from its own sequence whatsapp_sale_number_seq (never consumes a till number)
Order numberThe ordinary order series (HS-2026-000001)
Stock sourceMovements are written with inventory_source = 'whatsapp'
Payment attemptgatewayTransactionId is WA- plus the sale number; gatewayReference is the payment reference
Opening emailSent like any order the customer does not hold (handover: false). No counter receipt is queued
POS isolationThe POS routes only see channel = 'pos' sales. A WhatsApp sale answers POS_SALE_NOT_FOUND on every POS route

3. Routes and permissions

MethodPathSuccessPermissionsThrottleIdempotency
POST/api/orders/manual201Orders_CREATE and Pos_READADMIN_POS_COMPLETE — 30/min per userIdempotency-Key required
POST/api/orders/manual/quote200Orders_CREATE and Pos_READPUBLIC_SEARCH — 60/min per IP and device—
GET/api/orders/manual/customers200Orders_CREATE and Pos_READPUBLIC_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

FieldTypeRequiredRules
channelstringYeswhatsapp only
customerobjectYesDiscriminated on kind — see §4.2
linesarrayYes1 to 50 entries — see §4.3
fulfilmentobjectYesDiscriminated on type — see §4.4
paymentobjectYesSee §4.5
notestringNoMax 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"

FieldTypeRules
customerPublicIduuidThe customer's id, usually from the search route (§8)

kind: "new"

FieldTypeRules
namestringTrimmed, non-empty, max 120
phonestringNormalised to E.164 with region NP, so 9812345678 is accepted and stored as +9779812345678. Must match ^\+[1-9][0-9]{7,14}$ after normalising
emailstringRequired. Trimmed, lower-cased, valid email, max 320. It is the account id and where the set-password invitation goes
detachPhonebooleanOptional resubmit flag after a phone match (§6): create the customer without linking the phone

4.3 lines[]

FieldTypeRules
variantPublicIduuidThe configuration being sold (every product has at least one variant)
quantityinteger1 to 99
expectedUnitPriceinteger, 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"

FieldTypeRules
shippingAmountinteger, minor units0 to 10,000,000. Set by the administrator; the backend does not compute it
addressobjectA new address, saved to the customer's book. Required unless addressPublicId is sent
addressPublicIduuidAn 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:

FieldTypeRules
districtPublicIduuidMust exist, else 422 MANUAL_ORDER_DISTRICT_NOT_FOUND
municipalityNamestringNon-empty, max 120
wardinteger1 to 40
recipientNamestringNon-empty, max 120
recipientPhonestringE.164 as sent (+9779812345678); this field is not normalised
streetstringNon-empty, max 200
landmarkstringOptional, max 200
postalCodestringOptional, exactly five digits

4.5 payment and the rules behind it

methodreferenceMeaning
codMust be absent — 409 POS_PAYMENT_REFERENCE_NOT_ALLOWEDCash on delivery. Stays uncollected until an administrator records the cash (POST /api/orders/:id/cod-collection)
pos_qrRequired, max 120 charsAlready paid by QR or bank transfer
pos_cardRequired, max 120 charsAlready paid by card
  • reference is trimmed. A blank reference counts as absent: for pos_qr and pos_card that is 422 MANUAL_ORDER_PAYMENT_REFERENCE_REQUIRED.
  • pos_cash is not accepted (400 VALIDATION_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. esewa and online are rejected the same way.
  • The service re-checks the method against a per-channel allow-list and answers 422 MANUAL_ORDER_PAYMENT_METHOD_NOT_ALLOWED for a method the DTO admits but the channel does not. Today the DTO and the whatsapp allow-list both hold cod, pos_qr, pos_card, so this code is not reachable for whatsapp; it exists for a future channel.
  • The database backs this up: chk_pos_sale_pos_not_cod forbids cod on channel = 'pos' sales (migration 0057), and chk_pos_sale_payment_reference_method forbids a reference on a method other than pos_card or pos_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.

  1. Resolve every line against the catalogue (one query). Unknown variant: 404 POS_VARIANT_NOT_SELLABLE. Duplicate: 400 MANUAL_ORDER_DUPLICATE_LINE. Unpublished, withdrawn, soft-deleted or priced above MRP: 409 POS_PRODUCT_NOT_SELLABLE. Price differs from expectedUnitPrice: 409 POS_PRODUCT_PRICE_CHANGED.
  2. Resolve the district (delivery with a new address).
  3. Resolve or provision the customer (§6).
  4. Open the draft sale with channel = 'whatsapp', then set fulfilment (delivery) — this creates the address row if a new address was sent.
  5. Add the lines, frozen at the quoted price.
  6. If the customer was provisioned, queue the set-password invitation.
  7. Complete: reserve stock (409 POS_INSUFFICIENT_STOCK when 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 as POS_PRODUCT_PRICE_CHANGED with every moved line.
  8. Insert the internal order note (if note was sent).
  9. 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 say system.
  10. 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

TypeResult
pickupThe 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)
deliveryThe 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.

CaseResult
No header (or blank)400 IDEMPOTENCY_KEY_REQUIRED
Same key, same actor, same method/path/query/bodyReplays the stored status (201) and body; no second order
Same key, different payload409 IDEMPOTENCY_KEY_CONFLICT
Same key while the first request is still running409 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"

ConditionResult
No such customer404 USER_NOT_FOUND
Soft-deleted or not active409 MANUAL_ORDER_CUSTOMER_CLOSED
Not attachable409 MANUAL_ORDER_CUSTOMER_UNVERIFIED, no details (the admin chose by id, so there is no match to preview)
OtherwiseOrder 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.

#ConditionResult
1E and P both exist, differ, and P is attachable409 MANUAL_ORDER_CUSTOMER_CONFLICT
2E exists and is not live409 MANUAL_ORDER_CUSTOMER_CLOSED
3E is attachable409 MANUAL_ORDER_CUSTOMER_EXISTS with details (matched by email)
4E is live but not attachable409 MANUAL_ORDER_CUSTOMER_UNVERIFIED with details (no customerPublicId)
5No E; P attachable and detachPhone is not true409 MANUAL_ORDER_CUSTOMER_EXISTS with details (matched by phone)
6No 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
7NeitherProvision 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
    }
  }
}
Codedetails
MANUAL_ORDER_CUSTOMER_EXISTScustomerPublicId, 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_CLOSEDnone

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):

FieldTypeNotes
currencystringNPR
lines[].variantPublicIduuid
lines[].productNamestring
lines[].variantNamestringEmpty string when the product's only configuration has no label
lines[].skustring or nullVariant SKU, else product SKU
lines[].unitPriceintegerCampaign applied. This is what to send as expectedUnitPrice
lines[].quantityinteger
lines[].lineTotalinteger
lines[].availableinteger or nullnull when stock is not tracked for this configuration
lines[].sellablebooleanFalse when the configuration or product is withdrawn, unpublished, priced above MRP, or has no current price
subtotal, shippingAmount, grandTotalintegergrandTotal = 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

QueryTypeRules
qstringName, email or phone; max 100. Fewer than 2 characters after normalising is 400 VALIDATION_FAILED
sizeinteger1 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

HTTPCodeRaised when
400VALIDATION_FAILEDAny 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
400IDEMPOTENCY_KEY_REQUIREDCreate without Idempotency-Key
400MANUAL_ORDER_DUPLICATE_LINETwo lines resolve to the same variant
401 / 403auth codesMissing token; missing Orders_CREATE or Pos_READ
404POS_VARIANT_NOT_SELLABLEA variantPublicId does not exist
404USER_NOT_FOUNDkind: "existing" and no such customer
404POS_ADDRESS_NOT_FOUNDaddressPublicId is not the order customer's live address
409MANUAL_ORDER_CUSTOMER_EXISTS§6 rules 3 and 5, or a second lost create race. Carries details except after the race
409MANUAL_ORDER_CUSTOMER_UNVERIFIED§6 rule 4, or an unattachable existing customer
409MANUAL_ORDER_CUSTOMER_CONFLICT§6 rule 1
409MANUAL_ORDER_CUSTOMER_CLOSEDClosed or non-active account
409POS_PRODUCT_NOT_SELLABLEA line is unpublished, withdrawn, soft-deleted or priced above MRP
409POS_PRODUCT_PRICE_CHANGEDA line's current price differs from expectedUnitPrice. details.lines lists every moved line
409POS_INSUFFICIENT_STOCKNot enough stock at completion
409POS_PAYMENT_REFERENCE_NOT_ALLOWEDcod with a reference
409POS_DELIVERY_ADDRESS_REQUIREDBoth address and addressPublicId sent
409IDEMPOTENCY_KEY_CONFLICTKey reused with a different payload
409IDEMPOTENCY_REQUEST_IN_PROGRESSSame key still running
422MANUAL_ORDER_DISTRICT_NOT_FOUNDdistrictPublicId does not exist
422MANUAL_ORDER_PAYMENT_REFERENCE_REQUIREDpos_qr/pos_card with no (or blank) reference
422MANUAL_ORDER_PAYMENT_METHOD_NOT_ALLOWEDMethod refused for the channel (not reachable for whatsapp today)
429throttleOver the route's limit

11. Order list: channel filter and field

  • GET /api/orders accepts channel — one of online, pos, whatsapp. Anything else is 400. It filters order.channel; the count query shares the same WHERE, so pagination stays correct.
  • Every admin order object (list items and GET /api/orders/:id, which extends the list DTO) now carries channel: online (storefront), pos (the counter) or whatsapp (entered by an administrator from a chat). The field is additive.
  • order.channel and checkout_session.channel are copies of pos_sale.channel made at materialisation; the three columns share the sales_channel enum.

12. Flow

See Also