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
+75 -3
View File
@@ -13,6 +13,11 @@ import useConnectionStore from '../store/connectionStore'
import useAuthStore from '../store/authStore'
import { queueOfflineOrder } from '../services/offlineOrders'
import { assetUrl } from '../config/server'
import { LineError, estimate, wireLine } from '@xenia/api'
// A cart item whose option is not on the menu any more (4.4: lines go by id)
const lineErrorText = err => `«${err.product}»: το «${err.what}» δεν υπάρχει πια στο μενού. Αφαιρέστε το και προσθέστε το ξανά.`
const money = v => `${Number(v || 0).toFixed(2)} €`
// ─── Global Course Modal ──────────────────────────────────────────────────────
@@ -110,6 +115,28 @@ function CustomerCountModal({ value, onChange, onClose }) {
)
}
// ─── The cart's total (4.4) ───────────────────────────────────────────────────
// The server's price (POST /api/orders/quote) when online; offline, or until it answers, the
// menu's prices as an estimate. A line the server would refuse shows its reason here.
function CartTotal({ priced, estimatedTotal, offline }) {
const exact = !!priced?.data
return (
<div data-testid="cart-total" data-estimated={exact ? 'false' : 'true'}
style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
<span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600 }}>
{exact ? 'Σύνολο' : offline ? 'Σύνολο (εκτίμηση, χωρίς σύνδεση)' : 'Σύνολο (εκτίμηση)'}
</span>
<span style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>
{exact ? money(priced.data.total) : `≈ ${money(estimatedTotal)}`}
</span>
</div>
{priced?.error && <div data-testid="cart-total-error" style={{ fontSize: 12, color: 'var(--danger)' }}>{priced.error}</div>}
</div>
)
}
// ─────────────────────────────────────────────────────────────────────────────
const _AI_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
@@ -156,6 +183,7 @@ export default function AddItemsPage() {
const [dealOffers, setDealOffers] = useState([]) // pending deal prompts from server
const [activeDealOffer, setActiveDealOffer] = useState(null) // currently shown offer
const quickToastTimer = useRef(null)
const [quote, setQuote] = useState(null) // { key, data, error } — the server's price of the cart (4.4)
useEffect(() => {
async function load() {
@@ -283,6 +311,34 @@ export default function AddItemsPage() {
setEditItem(null)
}
// The cart as the lines the server prices (4.4): what was chosen, by id — never a price
function cartLines() {
return cart.map(({ _key, _drawerState, ...item }) => wireLine(item, getProduct(item.product_id)))
}
const estimates = cart.map(item => estimate(item, getProduct(item.product_id)))
const estimatedTotal = estimates.reduce((s, v) => s + v, 0)
// The server's price of the cart while it's on screen (debounced); offline → the estimate
const showPrices = (cartOpen || summaryOpen) && cart.length > 0 && !isOffline
const quoteKey = showPrices ? JSON.stringify([orderId, cart.map(({ _key, _drawerState, ...i }) => i)]) : null
useEffect(() => {
if (!quoteKey) return undefined
let lines
try { lines = cartLines() } catch (err) {
const t = setTimeout(() => setQuote({ key: quoteKey, data: null, error: err instanceof LineError ? lineErrorText(err) : String(err) }), 0)
return () => clearTimeout(t)
}
const t = setTimeout(() => {
client.post('/api/orders/quote', {
lines, order_id: orderId ?? undefined, order_type: isStandalone ? orderType : 'here',
}, { noOverride: true })
.then(r => setQuote({ key: quoteKey, data: r.data, error: null }))
.catch(err => setQuote({ key: quoteKey, data: null, error: apiError(err, '') }))
}, 250)
return () => clearTimeout(t)
}, [quoteKey]) // eslint-disable-line react-hooks/exhaustive-deps
const priced = quote && quote.key === quoteKey ? quote : null
async function sendOrder() {
if (cart.length === 0) return
setSending(true)
@@ -293,12 +349,14 @@ export default function AddItemsPage() {
// ── Offline path (not supported for standalone orders) ────────────────────
if (isOffline && !isStandalone) {
try {
// queued by id; the server prices them when the phone is back (the menu's price is shown as an estimate)
const items = cart.map(({ _key, _drawerState, ...item }) => {
const product = products.find(p => p.id === item.product_id)
return {
...item,
_wire: wireLine(item, product),
_productSnapshot: product ? { name: product.name } : null,
_unitPrice: product?.base_price ?? 0,
_unitPrice: estimate({ ...item, quantity: 1 }, product),
_unitType: product?.unit_type ?? null,
}
})
@@ -312,7 +370,7 @@ export default function AddItemsPage() {
setTimeout(() => navigate('/tables'), 1200)
} catch (err) {
console.error('[offline order] save failed:', err)
setError('Σφάλμα αποθήκευσης offline παραγγελίας')
setError(err instanceof LineError ? lineErrorText(err) : 'Σφάλμα αποθήκευσης offline παραγγελίας')
} finally {
setSending(false)
}
@@ -321,6 +379,12 @@ export default function AddItemsPage() {
// ── Online path ───────────────────────────────────────────────────────────
try {
let lines
try { lines = cartLines() } catch (err) {
if (!(err instanceof LineError)) throw err
setError(lineErrorText(err))
return
}
let activeOrderId = orderId
if (!activeOrderId) {
const orderPayload = isStandalone
@@ -332,7 +396,7 @@ export default function AddItemsPage() {
}
const res = await client.post(`/api/orders/${activeOrderId}/items`, {
items: cart.map(({ _key, _drawerState, ...item }) => item),
lines,
order_note: orderNote || null,
customer_count: customerCount ?? null,
})
@@ -542,6 +606,7 @@ export default function AddItemsPage() {
{/* Cart button with badge */}
<button
className="icon-btn"
data-testid="cart-open"
style={{ position: 'relative' }}
onClick={() => setCartOpen(true)}
>
@@ -801,6 +866,9 @@ export default function AddItemsPage() {
{/* Drawer footer */}
<div style={{ padding: '0 12px 20px', borderTop: '1px solid var(--border)', paddingTop: 12, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
{cart.length > 0 && (
<CartTotal priced={priced} estimatedTotal={estimatedTotal} offline={isOffline} />
)}
<button
className="btn btn--primary btn--lg"
style={{ width: '100%' }}
@@ -831,6 +899,10 @@ export default function AddItemsPage() {
<OrderSummaryModal
cart={cart}
products={products}
prices={priced?.data ? priced.data.lines.map(l => l.total) : estimates}
total={priced?.data ? priced.data.total : estimatedTotal}
estimated={!priced?.data}
priceError={priced?.error ?? null}
orderNote={orderNote}
setOrderNote={setOrderNote}
onSend={() => { setSummaryOpen(false); sendOrder() }}