From 198f8ff57162a2825b34e68f1c11eff6a1a1faa1 Mon Sep 17 00:00:00 2001 From: bonamin Date: Tue, 17 Nov 2026 09:54:37 +0200 Subject: [PATCH] feat(waiter): close with unpaid items as a setting, combine lines, seats (platform-v2 step 4.8a) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner's choices for 4.8 (2026-11-18), all configurable: - Setting orders.close_with_unpaid (default off): when off, the server refuses to close an order with unpaid items (pos.order_unpaid) and the phone's CLOSE takes the payment first ("instant-pay close"); when on, CLOSE confirms and the items stay unpaid. Manager Settings → Operation, next to "auto-close after full payment" (unchanged). - POST /api/orders/{id}/items/combine: unpaid lines of the same item (choices, note, price, course, kitchen state; no discount / deal / tab) become one line; the phone offers "Combine into one line" for selected lines or a grouped line. The grouping views (identical / same item) stay as they were. - Seats: the table's seats next to its name on the cards (waiter Settings → Layout, on by default) and in the guests dialog, where more guests than seats only shows a hint. - The table screen's last English-only labels (ADD, PAY, CLOSE, ACTIONS, SERVED, CLEAR, ALL) are keys too. - Tests: test_close_and_combine.py (5), waiter e2e +5. Co-Authored-By: Claude Opus 5.5 --- local_backend/core/errors.py | 1 + local_backend/modules/ordering/manifest.py | 1 + local_backend/routers/orders.py | 72 +++++++++++++++++ local_backend/tests/test_close_and_combine.py | 68 ++++++++++++++++ .../src/pages/Settings/tabs/OperationTab.jsx | 7 ++ packages/i18n/locales/el/errors.json | 3 +- packages/i18n/locales/el/manager.json | 4 + packages/i18n/locales/el/waiter.json | 33 +++++++- packages/i18n/locales/en/errors.json | 3 +- packages/i18n/locales/en/manager.json | 4 + packages/i18n/locales/en/waiter.json | 33 +++++++- tests/e2e/waiter.mjs | 39 +++++++++- waiter_pwa/src/components/SeatsHint.jsx | 15 ++++ waiter_pwa/src/components/TableCard.jsx | 32 ++++++-- waiter_pwa/src/pages/AddItemsPage.jsx | 10 ++- waiter_pwa/src/pages/SettingsPage.jsx | 10 ++- waiter_pwa/src/pages/TableDetailPage.jsx | 78 ++++++++++++++----- waiter_pwa/src/store/tableViewStore.js | 2 + 18 files changed, 376 insertions(+), 39 deletions(-) create mode 100644 local_backend/tests/test_close_and_combine.py create mode 100644 waiter_pwa/src/components/SeatsHint.jsx diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 232e2e1..6b0d422 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -74,6 +74,7 @@ CODES: dict[str, tuple[int, str]] = { "pos.table_not_yours": (403, "{table} isn't in your zones. A manager can add the zone to your account."), "pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."), "pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."), + "order.items_not_combinable": (422, "These lines can't be combined: only unpaid lines of the same item, with the same choices, note, price and kitchen state, and no discount, deal or tab."), "order.not_sold_here": (422, "{name} isn't sold for this kind of order."), "order.lines_required": (422, "This app sent the order in an old format. Update the app and send it again."), "order.line.product_unavailable": (422, "{name} isn't available any more (line {line})."), diff --git a/local_backend/modules/ordering/manifest.py b/local_backend/modules/ordering/manifest.py index ab02402..6a940bc 100644 --- a/local_backend/modules/ordering/manifest.py +++ b/local_backend/modules/ordering/manifest.py @@ -20,6 +20,7 @@ MODULE = Module( SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'), SettingDef('business_day.rollover_hour', '6', 'Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.', type='int'), SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'), + SettingDef('orders.close_with_unpaid', 'false', "Allow closing an order that still has unpaid items (they are written off as unpaid): 'true' | 'false'. When 'false', closing asks for the payment first (plan step 4.8).", type='bool'), SettingDef('orders.bypass_kds_serve', 'false', "Skip KDS pending/serve flow — new orders and items are immediately marked as served: 'true' | 'false'", type='bool'), SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'), SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'), diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index 379a85b..9e134ba 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -50,6 +50,9 @@ class MoveItemsRequest(BaseModel): item_ids: List[int] target_order_id: int +class CombineItemsRequest(BaseModel): + item_ids: List[int] = Field(min_length=2, max_length=200) + class RevertPaymentRequest(BaseModel): item_ids: List[int] @@ -1095,6 +1098,12 @@ def close_order(order_id: int, request: Request, db: Session = Depends(get_db), OrderItem.order_id == order_id, OrderItem.status == "active", ).all() + # 4.8: the venue decides whether an order may be closed with unpaid items (written off); + # when not, the apps take the payment first ("instant-pay close") + if active_items: + row = db.query(PosSettings).filter(PosSettings.key == "orders.close_with_unpaid").first() + if not (row and row.value == "true"): + raise XeniaError("pos.order_unpaid", count=len(active_items)) closed_item_ids = [] for item in active_items: item.status = "closed" @@ -2064,3 +2073,66 @@ def put_item_on_tab( db.commit() broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "status": order.status, "action": "item_tabbed"}) return {"status": "tabbed", "tab_id": tab.id, "entry_amount": entry.amount} + + +# ── Combine selected items (plan step 4.8) ──────────────────────────────────── + +def _combine_key(i: OrderItem): + """What must be the same for two lines to become one: the product, every choice, the note, + the price, the course, the kitchen state, and nothing attached to the line on its own.""" + import json as _json + + def norm(raw): + try: + return _json.dumps(_json.loads(raw), sort_keys=True) if raw else "[]" + except ValueError: + return raw + return (i.product_id, norm(i.selected_options), norm(i.removed_ingredients), (i.notes or "").strip(), + round(i.unit_price or 0.0, 4), round(i.price_adjustment or 0.0, 4), i.course_id, i.kds_status or "pending") + + +@router.post("/{order_id}/items/combine") +def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db: Session = Depends(get_db), + user: User = Depends(get_current_user)): + """Combine unpaid lines of the same item into one (2 + 2 + 2 beers ordered at different + times → one line of 6): the first line keeps its id and gets the quantities, the others are + removed, their price events move to it. Only lines that are the same in every way that + matters (_combine_key), unpaid, without a discount, a deal, a tab or a linked line. + Needs ordering.orders.open (like moving and splitting).""" + from models.pricing import PriceEventLog + from models.tabs import TabEntry + order = db.get(Order, order_id) + if order is None: + raise XeniaError("order.not_found", order_id=order_id) + _need(request, db, user, "ordering.orders.open", target=f"order:{order_id}") + if not _can_access_order(order, user, db): + raise HTTPException(status_code=403, detail="Access denied") + ids = sorted(set(body.item_ids)) + items = db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.id.in_(ids)).order_by(OrderItem.id).all() + if len(items) != len(ids) or len(items) < 2: + raise XeniaError("order.items_not_combinable", reason="not_found") + if any(i.status != "active" for i in items): + raise XeniaError("order.items_not_combinable", reason="not_unpaid") + if any(i.deal_id or i.linked_item_id for i in items) or \ + db.query(OrderItem).filter(OrderItem.linked_item_id.in_(ids)).first() is not None: + raise XeniaError("order.items_not_combinable", reason="deal") + if db.query(OrderDiscount).filter(OrderDiscount.item_id.in_(ids)).first() is not None: + raise XeniaError("order.items_not_combinable", reason="discount") + if db.query(TabEntry).filter(TabEntry.order_item_id.in_(ids)).first() is not None: + raise XeniaError("order.items_not_combinable", reason="tab") + if len({_combine_key(i) for i in items}) != 1: + raise XeniaError("order.items_not_combinable", reason="different") + keep, rest = items[0], items[1:] + keep.quantity = round(sum(i.quantity for i in items), 3) + keep.printed = all(i.printed for i in items) + rest_ids = [i.id for i in rest] + db.query(PriceEventLog).filter(PriceEventLog.order_item_id.in_(rest_ids)).update( + {PriceEventLog.order_item_id: keep.id}, synchronize_session=False) + for i in rest: + db.delete(i) + _audit(db, order_id, "ITEMS_COMBINED", waiter_id=user.id, item_ids=[keep.id] + rest_ids, + note=f"into #{keep.id}, quantity {keep.quantity:g}") + db.commit() + broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, + "action": "items_combined", "item_ids": [keep.id]}) + return {"item_id": keep.id, "quantity": keep.quantity, "removed": rest_ids} diff --git a/local_backend/tests/test_close_and_combine.py b/local_backend/tests/test_close_and_combine.py new file mode 100644 index 0000000..11f2350 --- /dev/null +++ b/local_backend/tests/test_close_and_combine.py @@ -0,0 +1,68 @@ +"""Owner's choices of plan step 4.8: closing with unpaid items is a venue setting, and unpaid +lines of the same item can be combined into one.""" +import pytest + +from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures) +from tests.test_pos import burger_line, drawer_printer, menu, on_shift, till # noqa: F401 (fixtures) +from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures) + + +@pytest.fixture(autouse=True) +def _no_printing(monkeypatch): + import routers.orders as orders + monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: []) + + +def order_with(client, phone, floor, lines): + oid = client.post("/api/orders/", headers=phone["h"], json={"table_id": floor["t1"].id, "order_type": "here"}).json()["id"] + for line in lines: + assert client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [line]}).status_code == 200 + return oid + + +def items(db, oid): + from models.order import OrderItem + db.expire_all() + return db.query(OrderItem).filter(OrderItem.order_id == oid).order_by(OrderItem.id).all() + + +def test_closing_with_unpaid_items_follows_the_setting(client, db, menu, phone, floor, owner_h): + beer = {"product_id": menu["coffee"].id, "quantity": 2} + oid = order_with(client, phone, floor, [beer]) + r = client.post(f"/api/orders/{oid}/close", headers=phone["h"]) + assert r.status_code == 409 and err(r) == "pos.order_unpaid" and r.json()["error"]["params"]["count"] == 1 + assert client.put("/api/settings/orders.close_with_unpaid", headers=owner_h, json={"value": "true"}).status_code == 200 + assert client.post(f"/api/orders/{oid}/close", headers=phone["h"]).status_code == 200 + assert [i.status for i in items(db, oid)] == ["closed"] + + +def test_combine_the_same_item_ordered_at_different_times(client, db, menu, phone, floor): + from models.order import OrderAuditLog + beer = {"product_id": menu["coffee"].id, "quantity": 2} + oid = order_with(client, phone, floor, [beer, beer, beer]) + ids = [i.id for i in items(db, oid)] + r = client.post(f"/api/orders/{oid}/items/combine", headers=phone["h"], json={"item_ids": ids}) + assert r.status_code == 200, r.text + left = items(db, oid) + assert [(i.id, i.quantity) for i in left] == [(ids[0], 6)] + assert db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "ITEMS_COMBINED").count() == 1 + + +@pytest.mark.parametrize("second,reason", [ + (lambda m: {"product_id": m["coffee"].id, "quantity": 1, "notes": "no ice"}, "different"), + (lambda m: burger_line(m), "different"), +]) +def test_only_lines_that_are_the_same(client, db, menu, phone, floor, second, reason): + oid = order_with(client, phone, floor, [{"product_id": menu["coffee"].id, "quantity": 1}, second(menu)]) + r = client.post(f"/api/orders/{oid}/items/combine", headers=phone["h"], json={"item_ids": [i.id for i in items(db, oid)]}) + assert r.status_code == 422 and err(r) == "order.items_not_combinable" and r.json()["error"]["params"]["reason"] == reason + assert len(items(db, oid)) == 2 + + +def test_paid_lines_are_not_combined(client, db, menu, phone, floor): + beer = {"product_id": menu["coffee"].id, "quantity": 1} + oid = order_with(client, phone, floor, [beer, beer]) + first, second = items(db, oid) + assert client.post(f"/api/orders/{oid}/pay", headers=phone["h"], json={"item_ids": [first.id], "payment_method": "cash"}).status_code == 200 + r = client.post(f"/api/orders/{oid}/items/combine", headers=phone["h"], json={"item_ids": [first.id, second.id]}) + assert err(r) == "order.items_not_combinable" and r.json()["error"]["params"]["reason"] == "not_unpaid" diff --git a/manager_dashboard/src/pages/Settings/tabs/OperationTab.jsx b/manager_dashboard/src/pages/Settings/tabs/OperationTab.jsx index e10a212..560a5d2 100644 --- a/manager_dashboard/src/pages/Settings/tabs/OperationTab.jsx +++ b/manager_dashboard/src/pages/Settings/tabs/OperationTab.jsx @@ -3,6 +3,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import toast from 'react-hot-toast' import client from '../../../api/client' import RolePermissions from '../sections/RolePermissions' +import { useTranslation } from '@xenia/i18n' function Toggle({ checked, onChange, disabled }) { return ( @@ -372,6 +373,7 @@ function CloudSyncSection() { } function TableOrderSettingsSection() { + const { t } = useTranslation('manager') const qc = useQueryClient() const { data: settings, isLoading } = useQuery({ queryKey: ['pos-settings'], @@ -387,6 +389,7 @@ function TableOrderSettingsSection() { updateMut.mutate({ key, value: current === 'true' ? 'false' : 'true' }) } const autoClose = settings?.['orders.auto_close_on_full_payment']?.value ?? 'false' + const closeUnpaid = settings?.['orders.close_with_unpaid']?.value ?? 'false' const bypassKds = settings?.['orders.bypass_kds_serve']?.value ?? 'false' return ( @@ -399,6 +402,10 @@ function TableOrderSettingsSection() { > toggle('orders.auto_close_on_full_payment', autoClose)} disabled={updateMut.isPending} /> + {/* 4.8: closing with unpaid items; when off, the phones take the payment first */} + + toggle('orders.close_with_unpaid', closeUnpaid)} disabled={updateMut.isPending} data-testid="setting-orders.close_with_unpaid" /> + (await navText()).includes('Tables'), 8000, 300) + // ── 4.8: the owner's choices: combine lines, close with unpaid items, seats ───────── + const t6 = free.find(t => t.id !== t4.id && t.id !== t5.id) + const o6 = await api('POST', '/api/orders/', { token: tokenA, body: { table_id: t6.id } }) + for (let i = 0; i < 3; i++) await api('POST', `/api/orders/${o6.id}/items`, { token: tokenA, body: { lines: [{ product_id: plain.id, quantity: 2 }] } }) + await a.goto(`${APP}/tables/${t6.id}`) + await a.locator('.order-item').first().waitFor({ timeout: 10_000 }) + for (let i = 0; i < 3; i++) await a.locator('.order-item').nth(i).click() + await a.getByRole('button', { name: 'ACTIONS', exact: true }).last().click() + await a.getByText('Combine into one line').click() + const combined = await waitFor(async () => { + const o = await api('GET', `/api/orders/${o6.id}`, { token: boss }) + const live = o.items.filter(i => i.status === 'active') + return live.length === 1 && live[0].quantity === 6 && o + }, 10_000, 500) + r.check('4.8: three lines of the same item (2 + 2 + 2) combined into one line of 6', !!combined) + // closing with an unpaid item: by default the payment comes first; the venue may allow closing + await a.goto(`${APP}/tables/${t6.id}`) + await a.getByRole('button', { name: /CLOSE/ }).last().click() + r.check('4.8: CLOSE with unpaid items asks for the payment first (default)', await a.getByText('Confirm payment and close').isVisible().catch(() => false)) + await a.keyboard.press('Escape').catch(() => {}) + await setting(boss, 'orders.close_with_unpaid', 'true') + await a.goto(`${APP}/tables/${t6.id}`) + await a.getByRole('button', { name: /CLOSE/ }).last().click() + await a.getByTestId('close-confirm').click({ timeout: 10_000 }) + const closed = await waitFor(async () => (await api('GET', `/api/orders/${o6.id}`, { token: boss })).status === 'closed', 10_000, 500) + r.check('4.8: with "close with unpaid items" on, CLOSE closes and the item stays unpaid', !!closed) + await setting(boss, 'orders.close_with_unpaid', 'false') + // seats: a suggestion on the card and in the guests dialog + await api('PUT', `/api/tables/${t6.id}`, { token: boss, body: { seat_count: 4 } }) + await a.goto(`${APP}/tables`) + r.check("4.8: the table's seats show on its card", await shown(a, 'table-seats', 10_000)) + await a.goto(`${APP}/tables/${t6.id}/add?new=1`) + await a.getByTitle('Number of guests').click() + for (let i = 0; i < 6; i++) await a.locator('.qty-btn').last().click() + r.check('4.8: more guests than seats is allowed, with a hint (not a limit)', await a.getByTestId('seats-hint').getAttribute('data-over') === 'true') + await a.goto(`${APP}/tables`) + // ── 4.6: the look on the shared tokens: the venue's colour and light / dark reach the phone ── const accentOf = () => a.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--x-accent-rgb').trim()) r.check('4.6: the venue colour (default amber) is on the phone', await a.evaluate(() => document.documentElement.dataset.venueTheme) === 'amber') diff --git a/waiter_pwa/src/components/SeatsHint.jsx b/waiter_pwa/src/components/SeatsHint.jsx new file mode 100644 index 0000000..b9895af --- /dev/null +++ b/waiter_pwa/src/components/SeatsHint.jsx @@ -0,0 +1,15 @@ +import { useTranslation } from '@xenia/i18n' + +// The table's seats next to the number of guests (plan step 4.8): a suggestion, never a limit +// — a table for 4 may seat 5 with a chair from another table. +export default function SeatsHint({ seats, count }) { + const { t } = useTranslation('waiter') + if (!seats) return null + const over = count > seats + return ( +

+ {over ? t('seats.over', { count, seats }) : t('seats.table', { count: seats })} +

+ ) +} diff --git a/waiter_pwa/src/components/TableCard.jsx b/waiter_pwa/src/components/TableCard.jsx index d58dce8..28fc173 100644 --- a/waiter_pwa/src/components/TableCard.jsx +++ b/waiter_pwa/src/components/TableCard.jsx @@ -1,6 +1,7 @@ import { useRef, useState, useEffect } from 'react' import { useFormat, useTranslation } from '@xenia/i18n' import useThemeStore from '../store/themeStore' +import useTableViewStore from '../store/tableViewStore' import useTableColourStore from '../store/tableColourStore' import { assetUrl } from '../config/server' import { fade } from '../logic/colour' @@ -283,6 +284,25 @@ function Amount({ value, size = 22, color }) { ) } +// ─── Seats (plan step 4.8) ─────────────────────────────────────────────────── +// The table's seats next to its name: a suggestion for seating, never a limit. Shown unless the +// waiter turned it off (Settings → Layout). +function SeatCount({ table }) { + const { t } = useTranslation('waiter') + const show = useTableViewStore(s => s.showSeats) + if (!show || !table.seat_count) return null + return ( + + + + + + {table.seat_count} + + ) +} + // ─── Card variants ──────────────────────────────────────────────────────────── // 1x1 — square-ish, 4 per row. Badges top (up to 2 + +N), name center, KDS badge bottom (replaces status). @@ -311,7 +331,7 @@ function Card1x1({ table, _order, flags, _waiterObjects, cfg, statusKey, kdsBadg letterSpacing: -0.5, color: cfg.nameText, lineHeight: 1, position: 'relative', zIndex: 2, }}> - {table.label || `T${table.number}`} + {table.label || `T${table.number}`} {/* bottom strip: KDS badge if present, else status */} @@ -353,7 +373,7 @@ function Card2x1({ table, _order, flags, _waiterObjects, cfg, statusKey, kdsBadg letterSpacing: -0.5, color: cfg.nameText, lineHeight: 1, flexShrink: 0, position: 'relative', zIndex: 2, }}> - {table.label || `T${table.number}`} + {table.label || `T${table.number}`}
- {table.label || `T${table.number}`} + {table.label || `T${table.number}`}
@@ -448,7 +468,7 @@ function Card4x1({ table, order, flags, _waiterObjects, cfg, statusKey, kdsBadge letterSpacing: -0.5, color: cfg.nameText, lineHeight: 1, flexShrink: 0, position: 'relative', zIndex: 2, }}> - {table.label || `T${table.number}`} + {table.label || `T${table.number}`}
{/* separator dot */} @@ -506,7 +526,7 @@ function Card4x2({ table, order, flags, waiterObjects, groupName, cfg, statusKey fontWeight: 800, fontSize: 'clamp(30px, 7vw, 44px)', letterSpacing: -1.5, lineHeight: 1, color: cfg.nameText, }}> - {table.label || `T${table.number}`} + {table.label || `T${table.number}`}
{groupName && (
- {table.label || `T${table.number}`} + {table.label || `T${table.number}`}
{groupName && (
t('add.optionGone', { product: err.product, what: err.what }) @@ -71,7 +72,7 @@ function GlobalCourseModal({ courses, selected, onSelect, onClose }) { // ─── Customer count modal ───────────────────────────────────────────────────── -function CustomerCountModal({ value, onChange, onClose }) { +function CustomerCountModal({ value, seats, onChange, onClose }) { const { t } = useTranslation('waiter') const [count, setCount] = useState(value ?? 0) const QUICK = [1, 2, 3, 4, 5, 6] @@ -84,6 +85,7 @@ function CustomerCountModal({ value, onChange, onClose }) {

{t('detail.guests.question')}

+ {/* Quick pick */}
@@ -181,6 +183,7 @@ export default function AddItemsPage() { const [searchQuery, setSearchQuery] = useState('') const [quickToast, setQuickToast] = useState(null) // { product, count } const [customerCount, setCustomerCount] = useState(null) // number of people at table + const [seats, setSeats] = useState(null) // the table's seats: a suggestion (4.8) const [customerCountOpen, setCustomerCountOpen] = useState(false) const [courses, setCourses] = useState([]) const [quickNotes, setQuickNotes] = useState(null) // null = not yet fetched; use drawer's fallback @@ -206,7 +209,7 @@ export default function AddItemsPage() { const statusRes = await client.get(`/api/tables/${tableId}/status`) setOrderId(statusRes.data.active_order_id) const tbl = statusRes.data.table - if (tbl) setTableLabel(tbl.label || `T${tbl.number}`) + if (tbl) { setTableLabel(tbl.label || `T${tbl.number}`); setSeats(tbl.seat_count ?? null) } // Load existing customer count from the active order if (statusRes.data.active_order_id) { const { data: o } = await client.get(`/api/orders/${statusRes.data.active_order_id}`) @@ -215,7 +218,7 @@ export default function AddItemsPage() { } catch { // Offline — read table label from IDB snapshot const tbl = await db.pos_tables.get(Number(tableId)) - if (tbl) setTableLabel(tbl.label || `T${tbl.number}`) + if (tbl) { setTableLabel(tbl.label || `T${tbl.number}`); setSeats(tbl.seat_count ?? null) } // orderId stays null — offline orders don't need a pre-existing server order } } @@ -934,6 +937,7 @@ export default function AddItemsPage() { {customerCountOpen && ( setCustomerCount(v)} onClose={() => setCustomerCountOpen(false)} /> diff --git a/waiter_pwa/src/pages/SettingsPage.jsx b/waiter_pwa/src/pages/SettingsPage.jsx index edf0aa9..d94e87c 100644 --- a/waiter_pwa/src/pages/SettingsPage.jsx +++ b/waiter_pwa/src/pages/SettingsPage.jsx @@ -172,7 +172,7 @@ const ORDER_ITEM_LAYOUT_OPTIONS = [ function LayoutTab() { const { t } = useTranslation('waiter') - const { density, setDensity, chipStyle, setChipStyle, kdsDisplayStyle, setKdsDisplayStyle, orderItemLayout, setOrderItemLayout, mergePersist, setMergePersist } = useTableViewStore() + const { density, setDensity, chipStyle, setChipStyle, kdsDisplayStyle, setKdsDisplayStyle, orderItemLayout, setOrderItemLayout, mergePersist, setMergePersist, showSeats, setShowSeats } = useTableViewStore() const { dark, toggle } = useThemeStore() return ( @@ -217,6 +217,14 @@ function LayoutTab() { {/* Card density */} + {/* Seats on the table cards (4.8) */} +
+

{t('settings.seats.title')}

+
+ setShowSeats(!(showSeats !== false))} /> +
+
+

{t('settings.density.title')}

{t('settings.density.sub')}

diff --git a/waiter_pwa/src/pages/TableDetailPage.jsx b/waiter_pwa/src/pages/TableDetailPage.jsx index c5a5248..097bf42 100644 --- a/waiter_pwa/src/pages/TableDetailPage.jsx +++ b/waiter_pwa/src/pages/TableDetailPage.jsx @@ -15,6 +15,7 @@ import usePaymentSettingsStore from '../store/paymentSettingsStore' import useTableViewStore from '../store/tableViewStore' import { useTranslation } from '@xenia/i18n' import { fade } from '../logic/colour' +import SeatsHint from '../components/SeatsHint' const fmtPrice = money @@ -24,6 +25,11 @@ const MERGE_OFF = 'off' const MERGE_IDENTICAL = 'identical' // same product + options + price const MERGE_SAME_ITEM = 'same_item' // same product + same effective unit price +// The real order lines behind what's on screen (a grouped line stands for several) +function combineIds(items) { + return items.flatMap(i => i._sourceIds ?? [i.id]).filter(id => typeof id === 'number') +} + // Returns a stable string key for grouping under MERGE_IDENTICAL function identicalKey(item) { const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4) @@ -243,7 +249,7 @@ function PriceAdjustModal({ item, onConfirm, onClose }) { // ─── Item action modal (long-press) ────────────────────────────────────────── -function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, onClose }) { +function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, onClose }) { const { t } = useTranslation('waiter') const { items, singleStacked, multiSelect } = target const label = multiSelect @@ -295,6 +301,22 @@ function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCance onClick: onMoveToTable, enabled: true, }] : []), + // 4.8: lines of the same item ordered at different times become one (the server checks + // they really are the same: choices, note, price, kitchen state) + ...(canMove && combineIds(items).length > 1 && items.every(i => i.product_id === items[0].product_id && i.status === 'active') ? [{ + key: 'combine', + color: 'var(--x-info)', + iconBg: 'rgb(var(--x-info-rgb) / 0.15)', + label: t('detail.item.combine'), + sub: t('detail.item.combineSub', { count: combineIds(items).length }), + icon: ( + + + + ), + onClick: onCombine, + enabled: true, + }] : []), ...(canMove && singleStacked && !multiSelect ? [{ key: 'split', color: 'var(--x-info)', @@ -578,7 +600,7 @@ function ActionsSheet({ order, _tableId, isStandalone, onClose, onTransfer, onMe
e.stopPropagation()} style={{ gap: 0 }}>
-

ACTIONS

+

{t('detail.btn.actions')}

{actions.map((a, i) => ( )}
@@ -1867,7 +1894,7 @@ export default function TableDetailPage() { border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 700, letterSpacing: 0.5, }} - >CLEAR + >{t('detail.btn.clear')} {/* ALL */} {!allActiveSelected && ( @@ -1881,7 +1908,7 @@ export default function TableDetailPage() { border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 700, letterSpacing: 0.5, }} - >ALL + >{t('detail.btn.all')} )} {/* SERVED — mark selected as served */} @@ -1896,7 +1923,7 @@ export default function TableDetailPage() { cursor: 'pointer', fontSize: 13, fontWeight: 700, letterSpacing: 0.5, }} - >SERVED + >{t('detail.btn.served')} {/* ACTIONS — opens item action modal */} + >{t('detail.btn.actions')}
)} @@ -1957,7 +1984,7 @@ export default function TableDetailPage() { border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 700, letterSpacing: 0.5, }} - >CLEAR + >{t('detail.btn.clear')} + >{t('detail.btn.served')} {canPay && ( @@ -2042,7 +2069,7 @@ export default function TableDetailPage() { > {paying ? '…' : ( <> - € PAY + {t('detail.btn.pay')} {selectedIds.length > 0 && ( { if (isOffline) return - if (!allPaid) setConfirmPayAndClose(true) + // unpaid items: take the payment first ("instant-pay close"), unless the venue lets + // an order close with unpaid items (they are written off; 4.8 setting) + if (!allPaid && !closeUnpaidAllowed) setConfirmPayAndClose(true) else setConfirmClose(true) }} disabled={isOffline} style={{ borderRadius: 999, flex: 1, opacity: isOffline ? 0.4 : 1 }} title={isOffline ? t('detail.notOffline') : undefined} > - ✕CLOSE + ✕{t('detail.btn.close')} )}
@@ -2168,6 +2197,18 @@ export default function TableDetailPage() { setItemActionTarget(null) setCancelConfirm({ mode: 'items', ids }) }} + onCombine={async () => { + const ids = combineIds(itemActionTarget.items) + setItemActionTarget(null) + try { + await client.post(`/api/orders/${order.id}/items/combine`, { item_ids: ids }) + setSelectedIds([]) + setVirtualItems(null) + await load() + } catch (err) { + setError(apiError(err, t('detail.err.combine'))) + } + }} onClose={() => setItemActionTarget(null)} /> )} @@ -2217,6 +2258,7 @@ export default function TableDetailPage() { {customerCountOpen && ( { setCustomerCount(v) if (order) { @@ -2288,14 +2330,14 @@ export default function TableDetailPage() {

{t('detail.close.title')}

- {t('detail.close.body')} + {allPaid ? t('detail.close.body') : t('detail.close.unpaid', { count: activeItems.length })}

-
diff --git a/waiter_pwa/src/store/tableViewStore.js b/waiter_pwa/src/store/tableViewStore.js index 8600af3..31241ce 100644 --- a/waiter_pwa/src/store/tableViewStore.js +++ b/waiter_pwa/src/store/tableViewStore.js @@ -18,6 +18,7 @@ const useTableViewStore = create( activeZoneTab: 'all', chipStyle: 'icon_short', // 'full' | 'short' | 'icon_full' | 'icon_short' | 'icon' tabSwitcherStyle: 'text', // 'text' | 'icon' + showSeats: true, // the table's seats on its card (4.8) // Footer nav settings // navStyle: 'triple' | 'icon_navbar' @@ -35,6 +36,7 @@ const useTableViewStore = create( setActiveZoneTab: (activeZoneTab) => set({ activeZoneTab }), setChipStyle: (chipStyle) => set({ chipStyle }), setTabSwitcherStyle: (tabSwitcherStyle) => set({ tabSwitcherStyle }), + setShowSeats: (showSeats) => set({ showSeats }), setNavStyle: (navStyle) => set({ navStyle }), setNavItems: (navItems) => set({ navItems }), setTripleItems: (tripleItems) => set({ tripleItems }),