diff --git a/local_backend/migrations/versions/0025_order_item_source.py b/local_backend/migrations/versions/0025_order_item_source.py new file mode 100644 index 0000000..0bcb6f3 --- /dev/null +++ b/local_backend/migrations/versions/0025_order_item_source.py @@ -0,0 +1,28 @@ +"""order_items.source: where a line came from (plan step 4.8): waiter | counter | qr | online. + +The waiter's phone marks the lines the guests sent themselves (QR menu) and online orders. +Lines of online orders get 'online'; older lines stay NULL (unknown). + +Revision ID: 0025_order_item_source +Revises: 0024_role_permissions +Create Date: 2026-11-18 10:00:00 +""" +from alembic import op +import sqlalchemy as sa + + +revision = '0025_order_item_source' +down_revision = '0024_role_permissions' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table('order_items', schema=None) as batch_op: + batch_op.add_column(sa.Column('source', sa.String(), nullable=True)) + op.execute("UPDATE order_items SET source = 'online' WHERE order_id IN (SELECT id FROM orders WHERE source = 'online')") + + +def downgrade() -> None: + with op.batch_alter_table('order_items', schema=None) as batch_op: + batch_op.drop_column('source') diff --git a/local_backend/models/order.py b/local_backend/models/order.py index 4c6fe2f..19932e0 100644 --- a/local_backend/models/order.py +++ b/local_backend/models/order.py @@ -123,6 +123,8 @@ class OrderItem(Base): # Courses — optional course assignment for sequenced firing course_id = Column(Integer, nullable=True) + # where the line came from (plan step 4.8): waiter | counter | qr | online; NULL = before 4.8 + source = Column(String, nullable=True) # Deal binding — which deal created this item, and which original item it's linked to deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True) diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index 9e134ba..2a54b43 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -377,6 +377,8 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends "price_adjustment": getattr(i, 'price_adjustment', 0.0) or 0.0, "unit_type": i.unit_type, "system_key": i.system_key, # the delivery fee line (phase 3S, S.5) + "source": i.source, # waiter | counter | qr | online (4.8) + "course_id": i.course_id, } def fmt_log(l): @@ -711,6 +713,7 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us removed_ingredients=json.dumps(item_in.removed_ingredients) if item_in.removed_ingredients else None, notes=item_in.notes, course_id=item_in.course_id, + source=item_in.source or "waiter", ) db.add(item) db.flush() @@ -1613,6 +1616,7 @@ def split_item( # Create split-off item new_item = OrderItem( + source=item.source, order_id=order_id, product_id=item.product_id, added_by=item.added_by, diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index f2d8285..418fbb3 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -271,7 +271,7 @@ def _items_in(lines, adjs): return [OrderItemInput( product_id=line.product.id, quantity=line.quantity, selected_options=[SelectedOptionInput(**e) for e in line.entries] or None, - removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None, + removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None, source="counter", ) for line, adj in zip(lines, adjs)] diff --git a/local_backend/schemas/order.py b/local_backend/schemas/order.py index b1b0365..33fcbf9 100644 --- a/local_backend/schemas/order.py +++ b/local_backend/schemas/order.py @@ -25,6 +25,7 @@ class OrderItemInput(BaseModel): price_adjustment: Optional[float] = None # on-the-fly price delta, applied at add-time is_service_item: bool = False # priceless: print-once ephemeral; priced: saved as real item course_id: Optional[int] = None + source: Optional[str] = None # set by the server (4.8): waiter | counter | qr | online class AddItemsRequest(BaseModel): @@ -64,6 +65,7 @@ class OrderItemOut(BaseModel): paid_in_shift_id: Optional[int] = None price_adjustment: float = 0.0 course_id: Optional[int] = None + source: Optional[str] = None # waiter | counter | qr | online (4.8); None = before 4.8 deal_id: Optional[int] = None linked_item_id: Optional[int] = None system_key: Optional[str] = None # a line the system added: "delivery_fee" (phase 3S, S.5) diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 21fb4af..293c566 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -460,13 +460,14 @@ def store_online_orders(db, orders: list[dict], booked: list | None = None, at_t return out -def add_cloud_items(db, order_id: int, opener_id: int, items: list) -> list: +def add_cloud_items(db, order_id: int, opener_id: int, items: list, source: str = "online") -> list: """The cloud's lines as order items, at the cloud's prices (what the customer pays).""" from models.order import OrderItem out = [] for item in items: row = OrderItem( order_id=order_id, + source=source, product_id=item.get("product_id"), added_by=opener_id, quantity=item.get("quantity", 1), diff --git a/local_backend/services/qr_orders.py b/local_backend/services/qr_orders.py index 3c72936..ae687d3 100644 --- a/local_backend/services/qr_orders.py +++ b/local_backend/services/qr_orders.py @@ -51,7 +51,7 @@ def place(db, cloud_order: dict, opener_id: int): db.add(order) db.flush() _audit(db, order.id, "ORDER_OPENED", waiter_id=opener_id, note="QR menu") - items = add_cloud_items(db, order.id, opener_id, json.loads(cloud_order.get("items_json") or "[]")) + items = add_cloud_items(db, order.id, opener_id, json.loads(cloud_order.get("items_json") or "[]"), source="qr") db.flush() ids = [i.id for i in items] _audit(db, order.id, EVENT, waiter_id=opener_id, item_ids=ids, amount=cloud_order.get("total"), note=cloud_order.get("public_ref")) diff --git a/local_backend/tests/test_close_and_combine.py b/local_backend/tests/test_close_and_combine.py index 11f2350..0769b0a 100644 --- a/local_backend/tests/test_close_and_combine.py +++ b/local_backend/tests/test_close_and_combine.py @@ -66,3 +66,29 @@ def test_paid_lines_are_not_combined(client, db, menu, phone, floor): 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" + + +def test_lines_know_where_they_came_from(client, db, menu, phone, floor, till): + """order_items.source (4.8): the phone's lines are 'waiter', the counter's 'counter' (QR: test_qr_table).""" + oid = order_with(client, phone, floor, [{"product_id": menu["coffee"].id, "quantity": 1}]) + r = client.post(f"/api/pos/tables/{floor['t1'].id}/items", headers=till["h"], json={"lines": [{"product_id": menu["coffee"].id}]}) + assert r.status_code == 201, r.text + assert [i.source for i in items(db, oid)] == ["waiter", "counter"] + assert [i["source"] for i in client.get(f"/api/orders/{oid}", headers=phone["h"]).json()["items"]] == ["waiter", "counter"] + + +def test_migration_0025_marks_online_lines(tmp_path): + from alembic import command + from sqlalchemy import create_engine, text + from core.schema import alembic_config, upgrade_to_head + eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}") + with eng.begin() as conn: + command.upgrade(alembic_config(conn), "0024_role_permissions") + conn.execute(text("insert into orders (id, opened_by, status, source, order_type, kds_status) values (1, 1, 'open', 'online', 'delivery', 'pending'), (2, 1, 'open', 'pos', 'here', 'pending')")) + conn.execute(text("insert into order_items (id, order_id, product_id, added_by, quantity, unit_price, product_name, status, kds_status, printed, price_adjustment) " + "values (1, 1, 1, 1, 1, 3, 'x', 'active', 'pending', 0, 0), (2, 2, 1, 1, 1, 3, 'x', 'active', 'pending', 0, 0)")) + upgrade_to_head(eng) + with eng.connect() as conn: + rows = conn.execute(text("select id, source from order_items order by id")).fetchall() + eng.dispose() + assert rows == [(1, "online"), (2, None)] diff --git a/local_backend/tests/test_qr_table.py b/local_backend/tests/test_qr_table.py index 1766902..e2227f8 100644 --- a/local_backend/tests/test_qr_table.py +++ b/local_backend/tests/test_qr_table.py @@ -114,6 +114,7 @@ def test_a_free_table_gets_a_new_order_and_its_zone_waiters_hear(db, counter, me order = db.get(Order, local) assert (order.table_id, order.source, order.sales_point, order.status) == (floor["t9"].id, "pos", "in_store", "open") assert [i.unit_price for i in order.items] == [3.0] + assert [i.source for i in order.items] == ["qr"] # marked on the phones (4.8) msg = db.query(StaffMessage).filter(StaffMessage.message_type == "qr_order").one() assert sorted(json.loads(msg.target_waiter_ids)) == sorted([hall_waiter.id, everywhere.id]) diff --git a/packages/i18n/locales/el/waiter.json b/packages/i18n/locales/el/waiter.json index 7843997..b5b6091 100644 --- a/packages/i18n/locales/el/waiter.json +++ b/packages/i18n/locales/el/waiter.json @@ -659,7 +659,12 @@ "noItems": "Δεν υπάρχουν αντικείμενα", "due": "Εκκρεμεί", "paidBadge": "Πληρωμένο", - "cancelledBadge": "Ακυρωμένο" + "cancelledBadge": "Ακυρωμένο", + "source": { + "qr": "Στάλθηκε από τους πελάτες μέσω QR", + "online": "Από online παραγγελία", + "onlineShort": "Online" + } }, "picker": { "noService": "Δεν υπάρχουν service αντικείμενα", @@ -788,7 +793,8 @@ "tables_one": "Τραπέζι: {{tables}}", "tables_other": "Τραπέζια: {{tables}}", "more_one": "+{{count}} ακόμα μήνυμα", - "more_other": "+{{count}} ακόμα μηνύματα" + "more_other": "+{{count}} ακόμα μηνύματα", + "openTable": "Άνοιγμα τραπεζιού" }, "history": { "tab": "Ιστορικό", diff --git a/packages/i18n/locales/en/waiter.json b/packages/i18n/locales/en/waiter.json index 2a5f9bd..f984e8b 100644 --- a/packages/i18n/locales/en/waiter.json +++ b/packages/i18n/locales/en/waiter.json @@ -659,7 +659,12 @@ "noItems": "No items", "due": "Due", "paidBadge": "Paid", - "cancelledBadge": "Cancelled" + "cancelledBadge": "Cancelled", + "source": { + "qr": "Sent by the guests from the QR menu", + "online": "From an online order", + "onlineShort": "Online" + } }, "picker": { "noService": "No service items", @@ -788,7 +793,8 @@ "tables_one": "Table: {{tables}}", "tables_other": "Tables: {{tables}}", "more_one": "+{{count}} more message", - "more_other": "+{{count}} more messages" + "more_other": "+{{count}} more messages", + "openTable": "Open the table" }, "history": { "tab": "History", diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index abd6ef5..47e945f 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -7,7 +7,8 @@ // node waiter.mjs import path from 'node:path' import { chromium } from 'playwright' -import { BROWSER_CHANNEL, OUT, reporter, sleep, waitFor } from './lib/env.mjs' +import { execFileSync } from 'node:child_process' +import { BROWSER_CHANNEL, OUT, PYTHON, reporter, sleep, waitFor } from './lib/env.mjs' import { login, startBackend, startViteNative } from './lib/proc.mjs' const backend = await startBackend({ port: 8061, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } }) @@ -301,6 +302,16 @@ try { 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') + // a line the guests sent from the QR menu is marked on the phone (the QR flow itself: qr_table.mjs) + const o7 = await api('POST', '/api/orders/', { token: tokenA, body: { table_id: t6.id } }) + await api('POST', `/api/orders/${o7.id}/items`, { token: tokenA, body: { lines: [{ product_id: plain.id, quantity: 1 }, { product_id: other.id, quantity: 1 }] } }) + execFileSync(PYTHON, ['-c', `import sqlite3; c = sqlite3.connect(r"${path.join(backend.dataDir, 'pos.db')}"); c.execute("update order_items set source = 'qr' where order_id = ${o7.id} and product_id = ${other.id}"); c.commit()`]) + await a.goto(`${APP}/tables/${t6.id}`) + r.check("4.8: the QR menu's lines are marked on the waiter's order", await shown(a, 'item-source', 10_000) + && await a.getByTestId('item-source').count() === 1 && await a.getByTestId('item-source').getAttribute('data-source') === 'qr') + await setting(boss, 'orders.close_with_unpaid', 'true') + await api('POST', `/api/orders/${o7.id}/close`, { token: boss }) + 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`) diff --git a/waiter_pwa/src/components/AppShell.jsx b/waiter_pwa/src/components/AppShell.jsx index f42fb42..76b8431 100644 --- a/waiter_pwa/src/components/AppShell.jsx +++ b/waiter_pwa/src/components/AppShell.jsx @@ -209,6 +209,7 @@ function BellButton({ onClick, count }) { function NotificationDrawer({ messages, onClose }) { const { t } = useTranslation('waiter') + const navigate = useNavigate() const { formatTime } = useFormat() return (
@@ -224,9 +225,13 @@ function NotificationDrawer({ messages, onClose }) { {messages.map(msg => { const tableIds = (() => { try { return JSON.parse(msg.table_ids || '[]') } catch { return [] } })() return ( -
{ onClose(); navigate(`/tables/${tableIds[0]}`) } : undefined} + style={{ padding: '12px 4px', borderBottom: '1px solid var(--border)', display: 'flex', gap: 12, alignItems: 'flex-start', + cursor: msg.message_type === 'qr_order' && tableIds.length ? 'pointer' : undefined, }}> 📢
diff --git a/waiter_pwa/src/components/OrderSummary.jsx b/waiter_pwa/src/components/OrderSummary.jsx index c4f6c5d..56d7cc5 100644 --- a/waiter_pwa/src/components/OrderSummary.jsx +++ b/waiter_pwa/src/components/OrderSummary.jsx @@ -382,6 +382,15 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd ) })() : null + // Lines the guests sent themselves (QR menu at the table) or an online order (plan step 4.8) + const sourceBadge = item.source === 'qr' || item.source === 'online' ? ( + + {item.source === 'qr' ? '📱 QR' : `🌐 ${t('summary.source.onlineShort')}`} + + ) : null + const nameEl = ( {item.product?.name || `#${item.product_id}`} {courseBadge} + {sourceBadge} ) diff --git a/waiter_pwa/src/context/NotificationContext.jsx b/waiter_pwa/src/context/NotificationContext.jsx index bc408f8..3dd694a 100644 --- a/waiter_pwa/src/context/NotificationContext.jsx +++ b/waiter_pwa/src/context/NotificationContext.jsx @@ -3,6 +3,7 @@ import useAuthStore from '../store/authStore' import useNotificationSettingsStore from '../store/notificationSettingsStore' import client from '../api/client' import { useTranslation } from '@xenia/i18n' +import { useNavigate } from 'react-router-dom' const NotificationContext = createContext(null) @@ -97,6 +98,7 @@ function RichBody({ text }) { function NotificationBanner({ message, onAck, autoDismiss }) { const { t } = useTranslation('waiter') + const navigate = useNavigate() // a QR order opens its table (4.8) const tableIds = (() => { try { return JSON.parse(message.table_ids || '[]') } catch { return [] } })() const theme = getTheme(message.message_type) @@ -130,6 +132,17 @@ function NotificationBanner({ message, onAck, autoDismiss }) {
)}
+ {message.message_type === 'qr_order' && tableIds.length > 0 && ( + + )}