feat(ordering): orders priced by the server (platform-v2 step 4.4)

The waiter app (and the manager's ordering tab) send what was chosen, by id; the
server prices it with the counter's code. No app sends a price any more.

- POST /api/orders/{id}/items takes `lines` (pos_cart's line + course_id,
  price_adjustment, is_service_item): sales point checked first, refusals name the
  product and line (order.line.*, order.not_sold_here); prices or selected_options in a
  line -> order.line.client_price, the old `items` shape -> order.lines_required; a
  by-hand price change needs ordering.prices.modify or a manager's approval (audited
  PRICE_SET_BY_HAND). add_priced_items is the one writer of priced items (pos too).
- POST /api/orders/quote: the cart's total before sending; /api/pos/quote shares
  pos_cart.quote().
- pos_cart: a preference set left out takes its default; a set at its free default
  isn't stored; a default that costs is charged (the waiter never sent it: fixed);
  an extra's sub-choice is charged per extra (the counter charged it once: fixed).
- @xenia/api lines.js: lineFromOptions / wireLine / estimate / LineError.
- Waiter: lines on send; cart total from the quote ("≈ estimate" offline); summary
  shows the same prices; offline orders queued by id, priced on sync, refused lines
  shown on a "Δεν στάλθηκαν" sheet (no empty order opened); dead ItemOptionsModal gone.
- Tests: test_order_lines.py (14), lines.test.mjs, waiter e2e +6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 03:35:03 +02:00
co-authored by Claude Opus 5.5
parent bcf91bf6e9
commit 8e0a786bbc
25 changed files with 1052 additions and 656 deletions
+134 -48
View File
@@ -1,5 +1,12 @@
import db from '../db/posdb'
import client from '../api/client'
import { apiError } from '../api/errors'
// Orders taken offline (plan step 4.4): the cart lines are queued by id (`_wire`, built when
// the order was taken: @xenia/api wireLine) and priced by the server when they reach it; the
// synthetic order shows the menu's price as an estimate until then. A line the server refuses
// is taken out, the rest is sent, and the refused one is kept in `kv.refused_lines` with the
// reason for the waiter to see (components/RefusedLines.jsx), never dropped silently.
// ─── Helpers ──────────────────────────────────────────────────────────────────
@@ -66,6 +73,7 @@ export async function queueOfflineOrder({ tableId, items, waiterId }) {
quantity: item.quantity,
unit_price: item._unitPrice || 0,
unit_type: item._unitType || null,
_estimated: true,
status: 'active',
kds_status: 'pending',
selected_options: item.selected_options || [],
@@ -238,30 +246,20 @@ async function _flushLegacyOfflineOrders() {
await db.offline_orders.update(entry.localId, { synced: 1 })
continue
}
// True legacy record — handle directly
// True legacy record (before v0.6.4): it can't be priced by the server (no lines by id)
if (!entry.items.some(i => i._wire)) {
await keepRefused(entry.items.map(i => refusedEntry(i, entry.tableId, entry.uuid, OLD_FORMAT)))
await db.offline_orders.update(entry.localId, { synced: 1 })
await db.pos_orders.delete(`offline_${entry.uuid}`)
continue
}
try {
let orderId = null
try {
const statusRes = await client.get(`/api/tables/${entry.tableId}/status`)
orderId = statusRes.data.active_order_id ?? null
} catch { /* offline */ }
if (!orderId) {
const createRes = await client.post('/api/orders/', { table_id: entry.tableId })
orderId = createRes.data?.id
if (!orderId) throw new Error('no order id returned')
const { orderId } = await sendLines(entry.items, { tableId: entry.tableId, uuid: entry.uuid }, () => tableOrderId(entry.tableId))
if (orderId == null) {
await db.offline_orders.update(entry.localId, { synced: 1 })
await db.pos_orders.delete(`offline_${entry.uuid}`)
continue
}
await client.post(`/api/orders/${orderId}/items`, {
items: entry.items.map(item => ({
product_id: item.product_id,
quantity: item.quantity,
selected_options: item.selected_options || [],
removed_ingredients: item.removed_ingredients || [],
notes: item.notes || '',
})),
})
const fullRes = await client.get(`/api/orders/${orderId}`)
await db.offline_orders.update(entry.localId, { synced: 1, serverId: orderId })
await db.pos_orders.delete(`offline_${entry.uuid}`)
@@ -295,32 +293,30 @@ async function _flushLegacyOfflinePayments() {
// ── Op handlers ───────────────────────────────────────────────────────────────
async function _flushCreateOrder(op, idMap) {
// Already synced by legacy drain? Check idMap or look for real order
let orderId = null
try {
const statusRes = await client.get(`/api/tables/${op.tableId}/status`)
orderId = statusRes.data.active_order_id ?? null
} catch { /* offline */ }
if (!orderId) {
const createRes = await client.post('/api/orders/', { table_id: op.tableId })
orderId = createRes.data?.id
if (!orderId) throw new Error('no order id returned')
const synthetic = await db.pos_orders.get(op.localOrderId)
// queued before 4.4: nothing the server can price → all refused, no empty order opened
if (!op.items.some(i => i._wire)) {
await keepRefused(op.items.map(i => refusedEntry(i, op.tableId, op.uuid, OLD_FORMAT)))
for (const it of synthetic?.items ?? []) idMap[it.id] = REFUSED
await db.offline_orders.where('uuid').equals(op.uuid).modify({ synced: 1 })
await db.offline_ops.update(op.localId, { synced: 1 })
await db.pos_orders.delete(op.localOrderId)
return
}
await client.post(`/api/orders/${orderId}/items`, {
items: op.items.map(item => ({
product_id: item.product_id,
quantity: item.quantity,
selected_options: item.selected_options || [],
removed_ingredients: item.removed_ingredients || [],
notes: item.notes || '',
})),
})
// the table's open order (one may have been opened meanwhile), or a new one, once a line
// is known to be accepted
const { orderId, sent } = await sendLines(op.items, { tableId: op.tableId, uuid: op.uuid }, () => tableOrderId(op.tableId))
// Capture synthetic order item ids BEFORE deleting it
const syntheticOrder = await db.pos_orders.get(op.localOrderId)
const syntheticItemIds = syntheticOrder?.items?.map(i => i.id) ?? []
const allLocalIds = synthetic?.items?.map(i => i.id) ?? []
allLocalIds.forEach((id, i) => { if (!sent.includes(i)) idMap[id] = REFUSED })
if (orderId == null) { // every line refused: nothing opened on the table
await db.offline_orders.where('uuid').equals(op.uuid).modify({ synced: 1 })
await db.offline_ops.update(op.localId, { synced: 1 })
await db.pos_orders.delete(op.localOrderId)
return
}
const syntheticItemIds = allLocalIds.filter((_, i) => sent.includes(i))
// Fetch full hydrated order
const fullRes = await client.get(`/api/orders/${orderId}`)
@@ -330,7 +326,7 @@ async function _flushCreateOrder(op, idMap) {
idMap[op.localOrderId] = orderId
// Map offline item ids → real item ids by position (last N added server items)
if (syntheticItemIds.length > 0 && serverOrder.items) {
if (syntheticItemIds.length > 0 && serverOrder.items && sent.length > 0) {
const addedServerItems = serverOrder.items.slice(-syntheticItemIds.length)
syntheticItemIds.forEach((localItemId, idx) => {
if (addedServerItems[idx]) {
@@ -393,14 +389,16 @@ async function _flushPay(op, idMap) {
return
}
// Resolve local item ids
const resolvedLocal = (op.localItemIds || []).map(lid => idMap[lid] ?? lid)
// Resolve local item ids (items the server refused when the order was sent can't be paid:
// the waiter sees them in the refused list)
const resolvedLocal = (op.localItemIds || []).map(lid => idMap[lid] ?? lid).filter(id => id !== REFUSED)
const stillLocal = resolvedLocal.filter(id => String(id).startsWith('offline_item_'))
if (stillLocal.length > 0) {
throw new Error('offline item ids not yet resolved')
}
const allIds = [...resolvedLocal, ...(op.realItemIds || [])]
if (!allIds.length) { await db.offline_ops.update(op.localId, { synced: 1 }); return }
await client.post(`/api/orders/${realOrderId}/pay-offline`, {
uuid: op.uuid,
item_ids: allIds,
@@ -410,6 +408,94 @@ async function _flushPay(op, idMap) {
await db.offline_ops.update(op.localId, { synced: 1 })
}
// ── Sending queued lines; refused ones come back to the waiter ──────────────────
const REFUSED_KEY = 'refused_lines'
const REFUSED = 'refused'
const OLD_FORMAT = 'Παλιά μορφή παραγγελίας: προσθέστε το ξανά'
/** Lines the server refused when an offline order was sent: [{ at, tableId, product, quantity, reason }]. */
export async function refusedLines() {
return (await db.kv.get(REFUSED_KEY))?.value ?? []
}
export async function clearRefusedLines() {
await db.kv.put({ key: REFUSED_KEY, value: [] })
window.dispatchEvent(new Event('refused-lines'))
}
async function keepRefused(entries) {
if (!entries.length) return
await db.kv.put({ key: REFUSED_KEY, value: [...(await refusedLines()), ...entries] })
window.dispatchEvent(new Event('refused-lines'))
}
/** The line a refusal names (order.line.*, order.not_sold_here carry `line`, 1-based), or null
* when the error isn't about one line (network, server error, the whole order). */
function refusedLine(err, count) {
const status = err?.response?.status
const line = err?.response?.data?.error?.params?.line
const refusal = status === 400 || status === 404 || status === 409 || status === 422
return refusal && Number.isInteger(line) && line >= 1 && line <= count ? line : null
}
/** Post `pending` lines; a refused line is taken out (with its reason) and the rest posted again. */
async function postLines(pending, refused, ctx, post) {
while (pending.length) {
try {
await post(pending.map(({ item }) => item._wire))
return pending
} catch (err) {
const n = refusedLine(err, pending.length)
if (n == null) throw err
const [{ item }] = pending.splice(n - 1, 1)
refused.push(refusedEntry(item, ctx.tableId, ctx.uuid, apiError(err, 'Ο server δεν το δέχτηκε')))
}
}
return pending
}
/**
* Send queued items, priced by the server. A quote first finds the lines the server refuses
* (so no order is opened for nothing), then `getOrderId()` gives the order and the rest is
* added (a line refused there is taken out too). An item queued before 4.4 (no `_wire`) can't
* be priced and is refused straight away. Network errors throw and the op stays queued (its
* refusals are found again next time). Returns { orderId (null: all refused), sent: [indexes] }.
*/
async function sendLines(items, ctx, getOrderId) {
const refused = items.filter(item => !item._wire).map(item => refusedEntry(item, ctx.tableId, ctx.uuid, OLD_FORMAT))
const opts = { noOverride: true }
let pending = items.map((item, index) => ({ item, index })).filter(({ item }) => item._wire)
pending = await postLines(pending, refused, ctx, lines => client.post('/api/orders/quote', { lines }, opts))
let orderId = null
if (pending.length) {
orderId = await getOrderId()
pending = await postLines(pending, refused, ctx, lines => client.post(`/api/orders/${orderId}/items`, { lines }, opts))
}
await keepRefused(refused)
return { orderId, sent: pending.map(({ index }) => index) }
}
async function tableOrderId(tableId) {
let orderId = null
try {
orderId = (await client.get(`/api/tables/${tableId}/status`)).data.active_order_id ?? null
} catch { /* offline */ }
if (!orderId) {
orderId = (await client.post('/api/orders/', { table_id: tableId })).data?.id
if (!orderId) throw new Error('no order id returned')
}
return orderId
}
function refusedEntry(item, tableId, uuid, reason) {
return {
at: new Date().toISOString(), uuid, tableId,
product: item._productSnapshot?.name ?? `#${item.product_id}`,
quantity: item.quantity, reason,
}
}
// ─── Queue size ───────────────────────────────────────────────────────────────
export async function pendingOrderCount() {