feat(waiter): where each line came from; QR lines marked, the QR message opens the table (platform-v2 step 4.8b)

- order_items.source (Alembic 0025): waiter | counter | qr | online, set by the server
  (orders.add_priced_items: the phone / manager 'waiter', the counter 'counter'; the QR
  menu's lines 'qr', online orders 'online'; a split line keeps its source); lines of
  existing online orders backfilled 'online'; in the order's item output.
- Waiter: lines the guests sent from the QR menu (or an online order) carry a "📱 QR" /
  "🌐 Online" mark; the qr_order message's banner has "Open the table", and in the bell's
  list the message opens it.
- Tests: source per channel, migration 0025, QR placement marks 'qr'; waiter e2e +1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 09:59:57 +02:00
co-authored by Claude Opus 5.5
parent 198f8ff571
commit 1e8271e370
15 changed files with 124 additions and 9 deletions
@@ -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')
+2
View File
@@ -123,6 +123,8 @@ class OrderItem(Base):
# Courses — optional course assignment for sequenced firing # Courses — optional course assignment for sequenced firing
course_id = Column(Integer, nullable=True) 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 binding — which deal created this item, and which original item it's linked to
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True) deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
+4
View File
@@ -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, "price_adjustment": getattr(i, 'price_adjustment', 0.0) or 0.0,
"unit_type": i.unit_type, "unit_type": i.unit_type,
"system_key": i.system_key, # the delivery fee line (phase 3S, S.5) "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): 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, removed_ingredients=json.dumps(item_in.removed_ingredients) if item_in.removed_ingredients else None,
notes=item_in.notes, notes=item_in.notes,
course_id=item_in.course_id, course_id=item_in.course_id,
source=item_in.source or "waiter",
) )
db.add(item) db.add(item)
db.flush() db.flush()
@@ -1613,6 +1616,7 @@ def split_item(
# Create split-off item # Create split-off item
new_item = OrderItem( new_item = OrderItem(
source=item.source,
order_id=order_id, order_id=order_id,
product_id=item.product_id, product_id=item.product_id,
added_by=item.added_by, added_by=item.added_by,
+1 -1
View File
@@ -271,7 +271,7 @@ def _items_in(lines, adjs):
return [OrderItemInput( return [OrderItemInput(
product_id=line.product.id, quantity=line.quantity, product_id=line.product.id, quantity=line.quantity,
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None, 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)] ) for line, adj in zip(lines, adjs)]
+2
View File
@@ -25,6 +25,7 @@ class OrderItemInput(BaseModel):
price_adjustment: Optional[float] = None # on-the-fly price delta, applied at add-time 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 is_service_item: bool = False # priceless: print-once ephemeral; priced: saved as real item
course_id: Optional[int] = None course_id: Optional[int] = None
source: Optional[str] = None # set by the server (4.8): waiter | counter | qr | online
class AddItemsRequest(BaseModel): class AddItemsRequest(BaseModel):
@@ -64,6 +65,7 @@ class OrderItemOut(BaseModel):
paid_in_shift_id: Optional[int] = None paid_in_shift_id: Optional[int] = None
price_adjustment: float = 0.0 price_adjustment: float = 0.0
course_id: Optional[int] = None course_id: Optional[int] = None
source: Optional[str] = None # waiter | counter | qr | online (4.8); None = before 4.8
deal_id: Optional[int] = None deal_id: Optional[int] = None
linked_item_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) system_key: Optional[str] = None # a line the system added: "delivery_fee" (phase 3S, S.5)
+2 -1
View File
@@ -460,13 +460,14 @@ def store_online_orders(db, orders: list[dict], booked: list | None = None, at_t
return out 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).""" """The cloud's lines as order items, at the cloud's prices (what the customer pays)."""
from models.order import OrderItem from models.order import OrderItem
out = [] out = []
for item in items: for item in items:
row = OrderItem( row = OrderItem(
order_id=order_id, order_id=order_id,
source=source,
product_id=item.get("product_id"), product_id=item.get("product_id"),
added_by=opener_id, added_by=opener_id,
quantity=item.get("quantity", 1), quantity=item.get("quantity", 1),
+1 -1
View File
@@ -51,7 +51,7 @@ def place(db, cloud_order: dict, opener_id: int):
db.add(order) db.add(order)
db.flush() db.flush()
_audit(db, order.id, "ORDER_OPENED", waiter_id=opener_id, note="QR menu") _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() db.flush()
ids = [i.id for i in items] 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")) _audit(db, order.id, EVENT, waiter_id=opener_id, item_ids=ids, amount=cloud_order.get("total"), note=cloud_order.get("public_ref"))
@@ -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 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]}) 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" 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)]
+1
View File
@@ -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) order = db.get(Order, local)
assert (order.table_id, order.source, order.sales_point, order.status) == (floor["t9"].id, "pos", "in_store", "open") 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.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() 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]) assert sorted(json.loads(msg.target_waiter_ids)) == sorted([hall_waiter.id, everywhere.id])
+8 -2
View File
@@ -659,7 +659,12 @@
"noItems": "Δεν υπάρχουν αντικείμενα", "noItems": "Δεν υπάρχουν αντικείμενα",
"due": "Εκκρεμεί", "due": "Εκκρεμεί",
"paidBadge": "Πληρωμένο", "paidBadge": "Πληρωμένο",
"cancelledBadge": "Ακυρωμένο" "cancelledBadge": "Ακυρωμένο",
"source": {
"qr": "Στάλθηκε από τους πελάτες μέσω QR",
"online": "Από online παραγγελία",
"onlineShort": "Online"
}
}, },
"picker": { "picker": {
"noService": "Δεν υπάρχουν service αντικείμενα", "noService": "Δεν υπάρχουν service αντικείμενα",
@@ -788,7 +793,8 @@
"tables_one": "Τραπέζι: {{tables}}", "tables_one": "Τραπέζι: {{tables}}",
"tables_other": "Τραπέζια: {{tables}}", "tables_other": "Τραπέζια: {{tables}}",
"more_one": "+{{count}} ακόμα μήνυμα", "more_one": "+{{count}} ακόμα μήνυμα",
"more_other": "+{{count}} ακόμα μηνύματα" "more_other": "+{{count}} ακόμα μηνύματα",
"openTable": "Άνοιγμα τραπεζιού"
}, },
"history": { "history": {
"tab": "Ιστορικό", "tab": "Ιστορικό",
+8 -2
View File
@@ -659,7 +659,12 @@
"noItems": "No items", "noItems": "No items",
"due": "Due", "due": "Due",
"paidBadge": "Paid", "paidBadge": "Paid",
"cancelledBadge": "Cancelled" "cancelledBadge": "Cancelled",
"source": {
"qr": "Sent by the guests from the QR menu",
"online": "From an online order",
"onlineShort": "Online"
}
}, },
"picker": { "picker": {
"noService": "No service items", "noService": "No service items",
@@ -788,7 +793,8 @@
"tables_one": "Table: {{tables}}", "tables_one": "Table: {{tables}}",
"tables_other": "Tables: {{tables}}", "tables_other": "Tables: {{tables}}",
"more_one": "+{{count}} more message", "more_one": "+{{count}} more message",
"more_other": "+{{count}} more messages" "more_other": "+{{count}} more messages",
"openTable": "Open the table"
}, },
"history": { "history": {
"tab": "History", "tab": "History",
+12 -1
View File
@@ -7,7 +7,8 @@
// node waiter.mjs // node waiter.mjs
import path from 'node:path' import path from 'node:path'
import { chromium } from 'playwright' 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' import { login, startBackend, startViteNative } from './lib/proc.mjs'
const backend = await startBackend({ port: 8061, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } }) 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) 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) 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') 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 // 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 api('PUT', `/api/tables/${t6.id}`, { token: boss, body: { seat_count: 4 } })
await a.goto(`${APP}/tables`) await a.goto(`${APP}/tables`)
+6 -1
View File
@@ -209,6 +209,7 @@ function BellButton({ onClick, count }) {
function NotificationDrawer({ messages, onClose }) { function NotificationDrawer({ messages, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const navigate = useNavigate()
const { formatTime } = useFormat() const { formatTime } = useFormat()
return ( return (
<div className="modal-overlay" onClick={onClose}> <div className="modal-overlay" onClick={onClose}>
@@ -224,9 +225,13 @@ function NotificationDrawer({ messages, onClose }) {
{messages.map(msg => { {messages.map(msg => {
const tableIds = (() => { try { return JSON.parse(msg.table_ids || '[]') } catch { return [] } })() const tableIds = (() => { try { return JSON.parse(msg.table_ids || '[]') } catch { return [] } })()
return ( return (
<div key={msg.id} style={{ <div key={msg.id}
data-testid={msg.message_type === 'qr_order' && tableIds.length ? 'notify-row-table' : undefined}
onClick={msg.message_type === 'qr_order' && tableIds.length ? () => { onClose(); navigate(`/tables/${tableIds[0]}`) } : undefined}
style={{
padding: '12px 4px', borderBottom: '1px solid var(--border)', padding: '12px 4px', borderBottom: '1px solid var(--border)',
display: 'flex', gap: 12, alignItems: 'flex-start', display: 'flex', gap: 12, alignItems: 'flex-start',
cursor: msg.message_type === 'qr_order' && tableIds.length ? 'pointer' : undefined,
}}> }}>
<span style={{ fontSize: 20, flexShrink: 0 }}>📢</span> <span style={{ fontSize: 20, flexShrink: 0 }}>📢</span>
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
@@ -382,6 +382,15 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
) )
})() : null })() : 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' ? (
<span data-testid="item-source" data-source={item.source} title={t(`summary.source.${item.source}`)}
style={{ marginLeft: 6, fontSize: 10, fontWeight: 800, padding: '1px 5px', borderRadius: 4, verticalAlign: 'middle',
background: 'rgb(var(--x-info-rgb) / 0.15)', color: 'var(--x-info)', border: '1px solid rgb(var(--x-info-rgb) / 0.35)' }}>
{item.source === 'qr' ? '📱 QR' : `🌐 ${t('summary.source.onlineShort')}`}
</span>
) : null
const nameEl = ( const nameEl = (
<span <span
className={[ className={[
@@ -394,6 +403,7 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
> >
{item.product?.name || `#${item.product_id}`} {item.product?.name || `#${item.product_id}`}
{courseBadge} {courseBadge}
{sourceBadge}
</span> </span>
) )
@@ -3,6 +3,7 @@ import useAuthStore from '../store/authStore'
import useNotificationSettingsStore from '../store/notificationSettingsStore' import useNotificationSettingsStore from '../store/notificationSettingsStore'
import client from '../api/client' import client from '../api/client'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { useNavigate } from 'react-router-dom'
const NotificationContext = createContext(null) const NotificationContext = createContext(null)
@@ -97,6 +98,7 @@ function RichBody({ text }) {
function NotificationBanner({ message, onAck, autoDismiss }) { function NotificationBanner({ message, onAck, autoDismiss }) {
const { t } = useTranslation('waiter') 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 tableIds = (() => { try { return JSON.parse(message.table_ids || '[]') } catch { return [] } })()
const theme = getTheme(message.message_type) const theme = getTheme(message.message_type)
@@ -130,6 +132,17 @@ function NotificationBanner({ message, onAck, autoDismiss }) {
</div> </div>
)} )}
</div> </div>
{message.message_type === 'qr_order' && tableIds.length > 0 && (
<button
data-testid="notify-open-table"
onClick={() => { onAck(message.id); navigate(`/tables/${tableIds[0]}`) }}
style={{
flexShrink: 0, height: 32, padding: '0 12px', borderRadius: 8,
border: `1px solid ${theme.border}`, background: 'transparent', color: theme.labelColor,
fontSize: 12, fontWeight: 700, cursor: 'pointer',
}}
>{t('notify.openTable')}</button>
)}
<button <button
onClick={() => onAck(message.id)} onClick={() => onAck(message.id)}
style={{ style={{