Order Lifecycle & State Machine
How an order goes from cart to completed, the strict state machine the owner drives it through, and why the live status is "new" — not "pending".
This guide is for Flutter engineers building both the customer and owner order screens (same binary, type-gated). It covers placing an order, the linear fulfilment state machine, cancellation rules, and the payload differences between the customer and owner surfaces. Admin order operations are covered in Admin and the API reference.
All endpoints are under /api/v1 and require a Bearer token: Authorization: Bearer <oat_...>. Owner endpoints additionally require an active owner membership (otherwise 403 FORBIDDEN). Send Accept-Language: ar for Arabic error/notification copy. All wire timestamps are UTC ISO-8601 with a Z suffix; any datetime you send (scheduledFor, estimatedReadyAt) must also be UTC.
The live wire value of a freshly placed order is the string "new", not "pending". The
?status= filter is matched raw against the DB column, so GET /orders?status=pending and
GET /owner/orders?status=pending return nothing — you will silently miss every new order.
The real status set on the wire is: new | accepted | rejected | preparing | ready_for_pickup | completed | cancelled.
There is no draft/pending order step. The "draft" lives in the cart, not the order. POST /api/v1/orders either fully succeeds (a live order at "new" already in the owner's inbox) or
it throws. Do not build a UI that creates an order and then "submits" or "confirms" it as a
second step — success is the live order, and placing it wipes the cart atomically.
The flow at a glance
Step 1 — Customer builds a cart against an active, open truck
Handled by the Cart domain. The truck must be status=active and isOpen=true.
Step 2 — Customer places the order
POST /api/v1/orders builds the order from the caller's active cart in one transaction: it re-checks the truck is still active and open, snapshots every line item, generates an order number, writes the first status event (null → new), wipes the cart, and bumps truck.orders_count. Returns 201 with the full order at status "new".
Step 3 — Order is live in the owner's inbox
The order appears immediately in GET /api/v1/owner/orders. Every item includes its frozen selectedAdditions. An owner/staff push fires with data.type="order_new" and data.route="order". No further action is needed to make it visible.
Step 4 — Owner accepts or rejects from new
PATCH /api/v1/owner/orders/:id/status with {status: "accepted"} (optionally attaching estimatedReadyAt) or {status: "rejected"}.
Step 5 — Owner advances the order one legal step at a time
accepted → preparing → ready_for_pickup → completed. Each PATCH stamps the matching timestamp, writes a status event, returns the full owner order (including add-ons), and pushes localized status copy to the customer with data.type="order_status" and data.route="track".
Step 6 — Either party may cancel a pre-pickup order
Customer via POST /api/v1/orders/:id/cancel (reason required); owner via PATCH .../status {status: "cancelled"}. The owner cannot cancel once the order is ready_for_pickup — the customer still can.
Step 7 — Customer reviews a completed order
POST /api/v1/orders/:id/review once the order is completed.
Per-step detail
Step 2 — Place an order
POST /api/v1/orders builds the order from the caller's active cart. Body fields are both optional: customerNotes (string, max 1000) and scheduledFor (UTC datetime).
POST /api/v1/orders
Authorization: Bearer oat_xxx
Accept-Language: en
Content-Type: application/json
{
"customerNotes": "No pickles please.",
"scheduledFor": "2026-06-21T19:30:00.000Z"
}On success the response is 201 with the full order at status "new":
{
"data": {
"order": {
"id": "ord_01jq...",
"orderNumber": "TM-20260621-A1B2C3",
"customerId": "usr_01jq...",
"truckId": "trk_01jq...",
"truck": {
"id": "trk_01jq...",
"name": "Smash Co",
"langActual": "en",
"...": "localized truck object"
},
"status": "new",
"paymentMethod": "in_person",
"subtotalMinor": 4500,
"totalMinor": 4500,
"currencyCode": "SAR",
"customerNotes": "No pickles please.",
"scheduledFor": "2026-06-21T19:30:00.000Z",
"estimatedReadyAt": null,
"createdAt": "2026-06-21T18:02:11.000Z",
"items": [
{
"menuItemId": "itm_01jq...",
"name": "Double Smash",
"descriptionSnapshot": "Two patties, house sauce",
"imageSnapshot": null,
"quantity": 1,
"unitPriceMinor": 4500,
"lineTotalMinor": 4500,
"selectedAdditions": []
}
],
"statusHistory": [
{
"status": "new",
"actorType": "customer",
"actorId": "usr_01jq...",
"at": "2026-06-21T18:02:11.000Z"
}
],
"review": null,
"reviewedAt": null
}
},
"meta": { "requestId": "req_01jq..." }
}What happens server-side, atomically: the truck is re-validated (active + open), each line item's name/description/unit price/options/image is snapshotted into order_items, subtotal = total (taxMinor is always 0), paymentMethod is recorded as in_person, an order number TM-YYYYMMDD-<6char> is generated, the first OrderStatusEvent (null → new) is written, the cart is deleted, and truck.orders_count is incremented.
Failure modes — handle these distinctly from validation:
| Status | Code | When |
|---|---|---|
409 | CONFLICT | Cart is empty |
409 | CONFLICT | Truck went status != active since cart-build ("not currently accepting orders") |
409 | CONFLICT | Truck is isOpen = false ("currently closed") |
404 | NOT_FOUND | Truck was deleted |
422 | VALIDATION_ERROR | Body validation (customerNotes > 1000, bad scheduledFor) |
Step 3 — Owner sees the order
GET /api/v1/owner/orders lists orders across all trucks owned by the caller. Each item embeds a compact customer block and full item snapshots. items[].selectedAdditions is always an array; old orders without add-ons return [].
GET /api/v1/owner/orders?status=new&limit=50
Authorization: Bearer oat_xxxFilters: ?status= (raw — use new, not pending), ?truckId= (omit to span all owned trucks; passing a truckId you do not own = 403 FORBIDDEN), ?limit= (default 50, max 100). Newest-first. An owner with no trucks gets an empty list, not an error. customer is null if the account was deleted/anonymized.
Step 4 & 5 — Owner drives the state machine
PATCH /api/v1/owner/orders/:id/status. Body: { status, estimatedReadyAt?, reason? }.
status— one ofaccepted | rejected | preparing | ready_for_pickup | completed | cancelled.estimatedReadyAt(UTC) — only honored onaccepted; silently ignored on every other transition.reason(string, max 500) — stored ascancelReason, only meaningful oncancelled.
PATCH /api/v1/owner/orders/ord_01jq.../status
Authorization: Bearer oat_xxx
Content-Type: application/json
{ "status": "accepted", "estimatedReadyAt": "2026-06-21T18:25:00.000Z" }The response contains the updated full owner order, including totals and item add-on snapshots. It does not embed the separate customer block; use owner detail when customer contact data is needed:
{
"data": {
"order": {
"id": "ord_01jq...",
"orderNumber": "TM-20260621-0042",
"status": "accepted",
"paymentMethod": "in_person",
"subtotalMinor": 4800,
"totalMinor": 4800,
"estimatedReadyAt": "2026-06-21T18:25:00.000Z",
"acceptedAt": "2026-06-21T18:03:40.000Z",
"readyAt": null,
"completedAt": null,
"rejectedAt": null,
"cancelledAt": null,
"items": [
{
"id": "ori_01jq...",
"menuItemId": "mit_01jq...",
"name": "Double Smash",
"quantity": 1,
"unitPriceMinor": 4800,
"lineTotalMinor": 4800,
"selectedAdditions": [{ "id": "mia_cheese", "name": "Extra cheese", "priceMinor": 300 }]
}
]
}
},
"meta": { "requestId": "req_01jq..." }
}If you need customer contact data after a transition, re-fetch GET /api/v1/owner/orders/:id.
An illegal transition (e.g. new → preparing, accepted → ready_for_pickup, or any transition out of a terminal state) returns 422 with code INVALID_STATE_TRANSITION. An owner trying to cancel a ready_for_pickup order returns 409 CONFLICT ("Cannot cancel an order that is already prepared. Mark it complete instead.").
Step 6 — Cancel
Customer cancel — POST /api/v1/orders/:id/cancel. reason is required (2–500 chars). Returns the full customer order object.
POST /api/v1/orders/ord_01jq.../cancel
Authorization: Bearer oat_xxx
Content-Type: application/json
{ "reason": "Changed my mind, ordering from somewhere closer." }A 409 CONFLICT is returned if the order is already terminal (completed / cancelled / rejected). The customer can cancel from ready_for_pickup (the owner cannot). The successful customer action immediately returns the cancelled order; the server sends data.type="order_cancelled", route="order" to the owner and active truck staff. It does not send a redundant push back to the cancelling customer.
Owner cancel — PATCH .../status {status: "cancelled", reason?}. reason is optional here. Blocked at ready_for_pickup (see above).
Step 7 — Review a completed order
POST /api/v1/orders/:id/review is a thin wrapper over POST /trucks/:truckId/reviews with orderId pre-bound. Body: { orderId (5–30 chars, must equal :id), rating: 1..5, comment? (max 2000), fileIds? (max 3) }. Returns 201 with the review at status: "visible". The order must already be completed — reviewing any earlier state returns 409 CONFLICT ("Order is not completed yet."). A 409 is also returned if the body orderId does not match the URL :id, or if the order has already been reviewed (409 ORDER_ALREADY_REVIEWED). See Reviews for the underlying review flow.
State table
| State | Meaning | How you got here | Allowed next |
|---|---|---|---|
new | Order is live on placement, awaiting owner action. Serialized as the literal "new". | POST /orders from a cart | accepted, rejected, cancelled |
accepted | Owner accepted. Sets acceptedAt, optional estimatedReadyAt. | Owner PATCH from new | preparing, cancelled |
rejected | Terminal. Owner declined. Sets rejectedAt. | Owner PATCH from new | — (none) |
preparing | Owner is making the food. No dedicated timestamp. | Owner PATCH from accepted | ready_for_pickup, cancelled |
ready_for_pickup | Food prepared. Sets readyAt. Owner can no longer cancel. | Owner PATCH from preparing | completed, cancelled (customer only) |
completed | Terminal. Picked up. Sets completedAt. Unlocks review. | Owner PATCH from ready_for_pickup | — (review) |
cancelled | Terminal. Pre-pickup order cancelled by customer or owner. Sets cancelledAt + cancelReason. | Customer cancel / owner PATCH | — (none) |
Transitions
| From | To | Actor | Via |
|---|---|---|---|
(cart) | new | customer | POST /api/v1/orders |
new | accepted | owner | PATCH /owner/orders/:id/status {status:accepted, estimatedReadyAt?} |
new | rejected | owner | PATCH /owner/orders/:id/status {status:rejected} |
new | cancelled | customer or owner | POST /orders/:id/cancel (customer) or PATCH .../status {status:cancelled} (owner) |
accepted | preparing | owner | PATCH .../status {status:preparing} |
accepted | cancelled | customer or owner | customer cancel or owner PATCH status=cancelled |
preparing | ready_for_pickup | owner | PATCH .../status {status:ready_for_pickup} |
preparing | cancelled | customer or owner | customer cancel or owner PATCH status=cancelled |
ready_for_pickup | completed | owner | PATCH .../status {status:completed} |
ready_for_pickup | cancelled | customer ONLY | POST /orders/:id/cancel — owner is blocked (409 CONFLICT) |
completed | (review) | customer | POST /orders/:id/review |
Any edge not in this table returns 422 INVALID_STATE_TRANSITION. Terminal states (completed, cancelled, rejected) accept no further transitions.
Payload shape by surface
The same order serializes differently depending on which surface fetched it. Do not reuse one parser blindly.
| Field group | Customer (GET /orders, /orders/:id) | Owner detail (GET /owner/orders/:id) | Owner status PATCH response |
|---|---|---|---|
statusHistory (event log) | ✅ included | ❌ omitted | ❌ omitted |
Embedded localized truck | ✅ included | ❌ omitted | ❌ omitted |
customer contact block | ❌ omitted | ✅ {id, fullName, phone, email} | ❌ omitted |
items | ✅ full snapshot + selectedAdditions | ✅ full snapshot + selectedAdditions | ✅ full snapshot + selectedAdditions |
| Per-state timestamps | partial (estimatedReadyAt) | ✅ all (acceptedAt/readyAt/completedAt/rejectedAt/cancelledAt) | ✅ all |
review / reviewedAt | ✅ included | ❌ omitted | ❌ omitted |
Money is always in minor units (integers) on the customer and owner surfaces: subtotalMinor, totalMinor, unitPriceMinor, lineTotalMinor. The admin detail in the API reference serializes some money fields as strings for the operator table; do not copy admin examples for the mobile parser.
Implementation Notes
| Integration issue | Correct handling |
|---|---|
Hardcoding "pending" for the just-placed state, or filtering ?status=pending. | The live value is "new". Use ?status=new. The full set is new | accepted | rejected | preparing | ready_for_pickup | completed | cancelled. |
| Building a two-phase "create then submit/confirm" order UI. | There is no draft order. The draft is the cart. POST /orders produces a live order at "new" in one call. |
| Treating a "truck closed" placement failure as a validation error. | The truck is re-checked at checkout. Handle 409 (not accepting / closed) and 404 (deleted) distinctly from 422. |
| Re-fetching the cart after a successful order. | Placing an order wipes the cart atomically. After 201, treat the cart as empty. |
| Re-fetching live menu data to render an order. | Line items are snapshots frozen at order time. Render from items[]; later menu edits never alter an existing order. |
Letting the owner skip states (e.g. new → preparing). | Strict linear machine. Advance one legal step at a time or get 422 INVALID_STATE_TRANSITION. |
Showing the owner a cancel button on a ready_for_pickup order. | Owner cancel is blocked there (409 CONFLICT). Only the customer can cancel a prepared order; the owner marks it completed. |
| Sending a customer cancel with no/short reason. | reason is required, 2–500 chars, or you get 422. (Owner cancel reason is optional.) |
Sending estimatedReadyAt with preparing/ready_for_pickup. | It is only applied on accepted; silently ignored otherwise. |
Dropping selectedAdditions after an owner transition. | The owner list, detail, and status PATCH all return the frozen add-on snapshots. Replace the local order with the PATCH response; do not rebuild it from the live menu. |
| Owner inbox silently drops an order the customer cancelled. | A customer cancel pushes data.type=order_cancelled to the owner and active staff. Owner-driven transitions push data.type=order_status only to the customer. |
Treating statusHistory's last row as the source of truth. | It is an append-only audit log (may start with a null → new event). The authoritative current state is the top-level status field. |
| Assuming the API localizes timestamps. | Wire timestamps are always UTC ISO-8601 with Z. Send estimatedReadyAt/scheduledFor in UTC. X-Timezone only affects server-rendered display copy (push/email). |
Related
- Cart — building the cart the order is created from
- Reviews — the review flow
POST /orders/:id/reviewwraps - Notifications — the
order_*push events fired on each transition - Payments — note this flow records
paymentMethod: in_person(no online charge at order time) - API reference