Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f57894dcb7 | ||
|
|
1e8271e370 | ||
|
|
198f8ff571 |
@@ -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})."),
|
||||
|
||||
@@ -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')
|
||||
@@ -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)
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -32,7 +32,7 @@ from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session, selectinload
|
||||
|
||||
from config import settings
|
||||
from core.access.deps import require
|
||||
from core.access.deps import require, require_any
|
||||
from core.errors import XeniaError
|
||||
from core.timeutil import utcnow
|
||||
from database import get_db
|
||||
@@ -304,8 +304,13 @@ def _booking_changed(background: BackgroundTasks, r) -> None:
|
||||
broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status})
|
||||
|
||||
|
||||
# Bookings: the counter and, since 4.8, the waiters' phones; whoever handles online orders or
|
||||
# manages reservations
|
||||
_BOOKINGS = require_any("reservations.manage", MANAGE) # the last refusal is the one reported
|
||||
|
||||
|
||||
@router.get("/bookings")
|
||||
def list_bookings(db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
||||
def list_bookings(db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
|
||||
"""The counter's bookings: `requested` (online, waiting for an answer, soonest first) and
|
||||
`upcoming` (confirmed, from 4 hours ago on, soonest first; any source)."""
|
||||
from datetime import timedelta
|
||||
@@ -319,7 +324,7 @@ def list_bookings(db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
||||
|
||||
@router.post("/bookings/{reservation_id}/confirm")
|
||||
def confirm_booking(reservation_id: int, background: BackgroundTasks, db: Session = Depends(get_db),
|
||||
user=Depends(require(MANAGE))):
|
||||
user=Depends(_BOOKINGS)):
|
||||
"""Confirm: the customer is told; food ordered ahead goes to the kitchen at its fire time
|
||||
(at once if that time has passed and the day is open)."""
|
||||
from routers import orders as orders_api
|
||||
@@ -338,7 +343,7 @@ def confirm_booking(reservation_id: int, background: BackgroundTasks, db: Sessio
|
||||
|
||||
@router.post("/bookings/{reservation_id}/decline")
|
||||
def decline_booking(reservation_id: int, body: BookingAnswer, background: BackgroundTasks,
|
||||
db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
||||
db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
|
||||
from services import online_reservations as svc
|
||||
r = _booking(db, reservation_id)
|
||||
svc.decline(db, r, body.reason)
|
||||
@@ -349,7 +354,7 @@ def decline_booking(reservation_id: int, body: BookingAnswer, background: Backgr
|
||||
|
||||
@router.post("/bookings/{reservation_id}/arrive")
|
||||
def arrive_booking(reservation_id: int, body: ArriveRequest, background: BackgroundTasks,
|
||||
db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
||||
db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
|
||||
"""The guests are here: seat them (optional table); their food's order moves to the table
|
||||
(and goes to the kitchen now if it hadn't yet)."""
|
||||
from services import online_reservations as svc
|
||||
@@ -367,7 +372,7 @@ def arrive_booking(reservation_id: int, body: ArriveRequest, background: Backgro
|
||||
|
||||
@router.post("/bookings/{reservation_id}/cancel")
|
||||
def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks,
|
||||
db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
||||
db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
|
||||
from services import online_reservations as svc
|
||||
r = _booking(db, reservation_id)
|
||||
svc.cancel(db, r, body.status, body.reason)
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -374,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):
|
||||
@@ -708,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()
|
||||
@@ -1095,6 +1101,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"
|
||||
@@ -1604,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,
|
||||
@@ -2064,3 +2077,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}
|
||||
|
||||
@@ -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)]
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""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"
|
||||
|
||||
|
||||
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)]
|
||||
@@ -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])
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<SectionCard title="Ρυθμίσεις Τραπεζιών και Παραγγελιών" description="Συμπεριφορά τραπεζιών και παραγγελιών">
|
||||
@@ -399,6 +402,10 @@ function TableOrderSettingsSection() {
|
||||
>
|
||||
<Toggle checked={autoClose === 'true'} onChange={() => toggle('orders.auto_close_on_full_payment', autoClose)} disabled={updateMut.isPending} />
|
||||
</OptionRow>
|
||||
{/* 4.8: closing with unpaid items; when off, the phones take the payment first */}
|
||||
<OptionRow label={t('settings.operation.closeUnpaid')} description={t('settings.operation.closeUnpaidHint')}>
|
||||
<Toggle checked={closeUnpaid === 'true'} onChange={() => toggle('orders.close_with_unpaid', closeUnpaid)} disabled={updateMut.isPending} data-testid="setting-orders.close_with_unpaid" />
|
||||
</OptionRow>
|
||||
<OptionRow
|
||||
label="Παράκαμψη KDS και Κατάστασης Σερβιρίσματος"
|
||||
description="Οι νέες παραγγελίες σημειώνονται άμεσα ως σερβιρισμένες — δεν απαιτείται επιβεβαίωση από σερβιτόρο"
|
||||
|
||||
@@ -71,7 +71,8 @@
|
||||
"quantity": "«{{name}}»: αυτή η ποσότητα δεν επιτρέπεται (γραμμή {{line}}).",
|
||||
"price": "«{{name}}»: αυτή η αλλαγή τιμής δεν επιτρέπεται (γραμμή {{line}}).",
|
||||
"client_price": "«{{name}}»: η εφαρμογή έστειλε δικές της τιμές, ενώ οι τιμές έρχονται από τον server (γραμμή {{line}}). Ενημερώστε την εφαρμογή."
|
||||
}
|
||||
},
|
||||
"items_not_combinable": "Αυτές οι γραμμές δεν συνδυάζονται: μόνο απλήρωτες γραμμές του ίδιου είδους, με ίδιες επιλογές, σημείωση, τιμή και κατάσταση κουζίνας, χωρίς έκπτωση, προσφορά ή καρτέλα."
|
||||
},
|
||||
"notification": {
|
||||
"not_found": "Η ειδοποίηση {{notification_id}} δεν βρέθηκε."
|
||||
|
||||
@@ -378,6 +378,10 @@
|
||||
"never": "Μόνο όταν εγκαταλειφθεί",
|
||||
"after_one": "Μετά από {{count}} αποτυχία",
|
||||
"after_other": "Μετά από {{count}} αποτυχίες"
|
||||
},
|
||||
"operation": {
|
||||
"closeUnpaid": "Κλείσιμο τραπεζιού με απλήρωτα",
|
||||
"closeUnpaidHint": "Ανενεργό: το κλείσιμο τραπεζιού με απλήρωτα ζητά πρώτα την πληρωμή και μετά το κλείνει. Ενεργό: κλείνει και τα απλήρωτα καταγράφονται ως απλήρωτα."
|
||||
}
|
||||
},
|
||||
"logs": {
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"orderLog": "Αρχείο Παραγγελιών",
|
||||
"settings": "Ρυθμίσεις",
|
||||
"installApp": "Εγκατάσταση εφαρμογής",
|
||||
"chat": "Chat"
|
||||
"chat": "Chat",
|
||||
"bookings": "Κρατήσεις"
|
||||
},
|
||||
"shell": {
|
||||
"notifications": "Ειδοποιήσεις",
|
||||
@@ -311,7 +312,12 @@
|
||||
"operation": "Λειτουργία",
|
||||
"favorites": "Αγαπημένα"
|
||||
},
|
||||
"max": "μέγιστο"
|
||||
"max": "μέγιστο",
|
||||
"seats": {
|
||||
"title": "Θέσεις",
|
||||
"label": "Εμφάνιση θέσεων τραπεζιού",
|
||||
"desc": "Στις κάρτες τραπεζιών, δίπλα στο όνομα (τις ορίζει ο διαχειριστής ανά τραπέζι)"
|
||||
}
|
||||
},
|
||||
"venues": {
|
||||
"active": "ΕΝΕΡΓΟ",
|
||||
@@ -457,7 +463,10 @@
|
||||
"moveSub": "Μεταφορά επιλεγμένων αντικειμένων",
|
||||
"splitSub": "Χώρισμα σε δύο γραμμές",
|
||||
"cancel": "Ακύρωση παραγγελίας",
|
||||
"cancelSub": "Ακύρωση επιλεγμένων αντικειμένων"
|
||||
"cancelSub": "Ακύρωση επιλεγμένων αντικειμένων",
|
||||
"combine": "Συνδυασμός σε μία γραμμή",
|
||||
"combineSub_one": "{{count}} γραμμή του ίδιου είδους",
|
||||
"combineSub_other": "{{count}} γραμμές του ίδιου είδους"
|
||||
},
|
||||
"withApproval": "Με έγκριση διαχειριστή (PIN)",
|
||||
"cancelNotAllowed": "Δεν επιτρέπεται η ακύρωση",
|
||||
@@ -517,7 +526,8 @@
|
||||
"noTargetOrder": "Δεν βρέθηκε παραγγελία στο τραπέζι",
|
||||
"merge": "Σφάλμα συγχώνευσης",
|
||||
"moveItems": "Σφάλμα μεταφοράς αντικειμένων",
|
||||
"flags": "Σφάλμα αποθήκευσης σημαιών"
|
||||
"flags": "Σφάλμα αποθήκευσης σημαιών",
|
||||
"combine": "Σφάλμα συνδυασμού"
|
||||
},
|
||||
"openOrder": "Άνοιγμα Παραγγελίας",
|
||||
"noPaid": "Δεν υπάρχουν πληρωμένα αντικείμενα",
|
||||
@@ -540,7 +550,9 @@
|
||||
},
|
||||
"close": {
|
||||
"title": "Κλείσιμο παραγγελίας;",
|
||||
"body": "Αυτή η ενέργεια δεν αναιρείται."
|
||||
"body": "Αυτή η ενέργεια δεν αναιρείται.",
|
||||
"unpaid_one": "{{count}} αντικείμενο είναι απλήρωτο: θα κλείσει ως απλήρωτο.",
|
||||
"unpaid_other": "{{count}} αντικείμενα είναι απλήρωτα: θα κλείσουν ως απλήρωτα."
|
||||
},
|
||||
"move": {
|
||||
"pickFree": "Επιλέξτε κενό τραπέζι",
|
||||
@@ -574,6 +586,15 @@
|
||||
"tabs": {
|
||||
"unpaid": "Εκκρεμή",
|
||||
"paid": "Πληρωμένα"
|
||||
},
|
||||
"btn": {
|
||||
"close": "ΚΛΕΙΣΙΜΟ",
|
||||
"add": "ΠΡΟΣΘΗΚΗ",
|
||||
"pay": "€ ΠΛΗΡΩΜΗ",
|
||||
"served": "ΣΕΡΒΙΡΙΣΤΗΚΕ",
|
||||
"actions": "ΕΝΕΡΓΕΙΕΣ",
|
||||
"clear": "ΚΑΘΑΡΙΣΜΟΣ",
|
||||
"all": "ΟΛΑ"
|
||||
}
|
||||
},
|
||||
"add": {
|
||||
@@ -639,7 +660,12 @@
|
||||
"noItems": "Δεν υπάρχουν αντικείμενα",
|
||||
"due": "Εκκρεμεί",
|
||||
"paidBadge": "Πληρωμένο",
|
||||
"cancelledBadge": "Ακυρωμένο"
|
||||
"cancelledBadge": "Ακυρωμένο",
|
||||
"source": {
|
||||
"qr": "Στάλθηκε από τους πελάτες μέσω QR",
|
||||
"online": "Από online παραγγελία",
|
||||
"onlineShort": "Online"
|
||||
}
|
||||
},
|
||||
"picker": {
|
||||
"noService": "Δεν υπάρχουν service αντικείμενα",
|
||||
@@ -768,7 +794,8 @@
|
||||
"tables_one": "Τραπέζι: {{tables}}",
|
||||
"tables_other": "Τραπέζια: {{tables}}",
|
||||
"more_one": "+{{count}} ακόμα μήνυμα",
|
||||
"more_other": "+{{count}} ακόμα μηνύματα"
|
||||
"more_other": "+{{count}} ακόμα μηνύματα",
|
||||
"openTable": "Άνοιγμα τραπεζιού"
|
||||
},
|
||||
"history": {
|
||||
"tab": "Ιστορικό",
|
||||
@@ -779,5 +806,41 @@
|
||||
"cancelled": "ΑΚΥΡΩΜΕΝΗ",
|
||||
"limit_one": "Το πακέτο σας δείχνει την τελευταία {{count}} ημέρα",
|
||||
"limit_other": "Το πακέτο σας δείχνει τις τελευταίες {{count}} ημέρες"
|
||||
},
|
||||
"seats": {
|
||||
"table_one": "Τραπέζι για {{count}}",
|
||||
"table_other": "Τραπέζι για {{count}}",
|
||||
"over": "{{count}} άτομα σε τραπέζι για {{seats}}: εντάξει, είναι μόνο ένδειξη"
|
||||
},
|
||||
"bookings": {
|
||||
"title": "Κρατήσεις",
|
||||
"loadFailed": "Σφάλμα φόρτωσης κρατήσεων",
|
||||
"failed": "Σφάλμα αποθήκευσης",
|
||||
"requests": "Αιτήματα ({{count}})",
|
||||
"noRequests": "Δεν υπάρχουν αιτήματα",
|
||||
"upcoming": "Επιβεβαιωμένες ({{count}})",
|
||||
"noUpcoming": "Δεν υπάρχουν επιβεβαιωμένες κρατήσεις",
|
||||
"confirm": "Επιβεβαίωση",
|
||||
"decline": "Απόρριψη",
|
||||
"today": "Σήμερα {{time}}",
|
||||
"people_one": "{{count}} άτομο",
|
||||
"people_other": "{{count}} άτομα",
|
||||
"foodSent": "Φαγητό εκ των προτέρων: στην κουζίνα",
|
||||
"foodAt": "Φαγητό εκ των προτέρων: στην κουζίνα στις {{time}}",
|
||||
"foodOnConfirm": "Φαγητό εκ των προτέρων: στην κουζίνα μόλις επιβεβαιωθεί",
|
||||
"table": "Τραπέζι",
|
||||
"noTable": "Χωρίς τραπέζι ακόμα",
|
||||
"arrive": "Ήρθαν: τοποθέτηση",
|
||||
"cancel": "Ακύρωση",
|
||||
"noShow": "Δεν ήρθαν",
|
||||
"declineTitle": "Απόρριψη της κράτησης του/της {{name}};",
|
||||
"declineBody": "Ο πελάτης βλέπει τον λόγο.",
|
||||
"reason": "Λόγος",
|
||||
"reasons": {
|
||||
"full": "Είμαστε πλήρεις",
|
||||
"closed": "Είμαστε κλειστά τότε",
|
||||
"party": "Ιδιωτική εκδήλωση",
|
||||
"other": "Άλλος λόγος"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +71,8 @@
|
||||
"quantity": "{{name}}: that quantity isn't allowed (line {{line}}).",
|
||||
"price": "{{name}}: that price change isn't allowed (line {{line}}).",
|
||||
"client_price": "{{name}}: the app sent its own prices, but prices come from the server (line {{line}}). Update the app."
|
||||
}
|
||||
},
|
||||
"items_not_combinable": "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."
|
||||
},
|
||||
"notification": {
|
||||
"not_found": "Notification {{notification_id}} not found."
|
||||
|
||||
@@ -378,6 +378,10 @@
|
||||
"never": "Only when it is given up",
|
||||
"after_one": "After {{count}} failed attempt",
|
||||
"after_other": "After {{count}} failed attempts"
|
||||
},
|
||||
"operation": {
|
||||
"closeUnpaid": "Close a table with unpaid items",
|
||||
"closeUnpaidHint": "Off: closing a table with unpaid items asks for the payment first, then closes it. On: it closes and the unpaid items are recorded as unpaid."
|
||||
}
|
||||
},
|
||||
"logs": {
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"orderLog": "Order log",
|
||||
"settings": "Settings",
|
||||
"installApp": "Install the app",
|
||||
"chat": "Chat"
|
||||
"chat": "Chat",
|
||||
"bookings": "Bookings"
|
||||
},
|
||||
"shell": {
|
||||
"notifications": "Notifications",
|
||||
@@ -311,7 +312,12 @@
|
||||
"operation": "Operation",
|
||||
"favorites": "Favourites"
|
||||
},
|
||||
"max": "maximum"
|
||||
"max": "maximum",
|
||||
"seats": {
|
||||
"title": "Seats",
|
||||
"label": "Show each table's seats",
|
||||
"desc": "On the table cards, next to the name (set by the manager per table)"
|
||||
}
|
||||
},
|
||||
"venues": {
|
||||
"active": "ACTIVE",
|
||||
@@ -457,7 +463,10 @@
|
||||
"moveSub": "Move the selected items",
|
||||
"splitSub": "Split into two lines",
|
||||
"cancel": "Cancel",
|
||||
"cancelSub": "Cancel the selected items"
|
||||
"cancelSub": "Cancel the selected items",
|
||||
"combine": "Combine into one line",
|
||||
"combineSub_one": "{{count}} line of the same item",
|
||||
"combineSub_other": "{{count}} lines of the same item"
|
||||
},
|
||||
"withApproval": "With a manager's approval (PIN)",
|
||||
"cancelNotAllowed": "Cancelling is not allowed",
|
||||
@@ -517,7 +526,8 @@
|
||||
"noTargetOrder": "No order found on that table",
|
||||
"merge": "Couldn't merge",
|
||||
"moveItems": "Couldn't move the items",
|
||||
"flags": "Couldn't save the flags"
|
||||
"flags": "Couldn't save the flags",
|
||||
"combine": "Couldn't combine the lines"
|
||||
},
|
||||
"openOrder": "Open an order",
|
||||
"noPaid": "No paid items",
|
||||
@@ -540,7 +550,9 @@
|
||||
},
|
||||
"close": {
|
||||
"title": "Close the order?",
|
||||
"body": "This can't be undone."
|
||||
"body": "This can't be undone.",
|
||||
"unpaid_one": "{{count}} item is unpaid: it will be closed as unpaid.",
|
||||
"unpaid_other": "{{count}} items are unpaid: they will be closed as unpaid."
|
||||
},
|
||||
"move": {
|
||||
"pickFree": "Choose a free table",
|
||||
@@ -574,6 +586,15 @@
|
||||
"tabs": {
|
||||
"unpaid": "Unpaid",
|
||||
"paid": "Paid"
|
||||
},
|
||||
"btn": {
|
||||
"close": "CLOSE",
|
||||
"add": "ADD",
|
||||
"pay": "€ PAY",
|
||||
"served": "SERVED",
|
||||
"actions": "ACTIONS",
|
||||
"clear": "CLEAR",
|
||||
"all": "ALL"
|
||||
}
|
||||
},
|
||||
"add": {
|
||||
@@ -639,7 +660,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",
|
||||
@@ -768,7 +794,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",
|
||||
@@ -779,5 +806,41 @@
|
||||
"cancelled": "CANCELLED",
|
||||
"limit_one": "Your plan shows the last {{count}} day",
|
||||
"limit_other": "Your plan shows the last {{count}} days"
|
||||
},
|
||||
"seats": {
|
||||
"table_one": "Table for {{count}}",
|
||||
"table_other": "Table for {{count}}",
|
||||
"over": "{{count}} guests at a table for {{seats}}: fine, it is only a suggestion"
|
||||
},
|
||||
"bookings": {
|
||||
"title": "Bookings",
|
||||
"loadFailed": "Couldn't load the bookings",
|
||||
"failed": "Couldn't save the change",
|
||||
"requests": "Requests ({{count}})",
|
||||
"noRequests": "No requests waiting",
|
||||
"upcoming": "Confirmed ({{count}})",
|
||||
"noUpcoming": "No confirmed bookings coming up",
|
||||
"confirm": "Confirm",
|
||||
"decline": "Decline",
|
||||
"today": "Today {{time}}",
|
||||
"people_one": "{{count}} person",
|
||||
"people_other": "{{count}} people",
|
||||
"foodSent": "Food ordered ahead: in the kitchen",
|
||||
"foodAt": "Food ordered ahead: to the kitchen at {{time}}",
|
||||
"foodOnConfirm": "Food ordered ahead: to the kitchen once confirmed",
|
||||
"table": "Table",
|
||||
"noTable": "No table yet",
|
||||
"arrive": "They are here: seat them",
|
||||
"cancel": "Cancel",
|
||||
"noShow": "Didn't come",
|
||||
"declineTitle": "Decline {{name}}'s booking?",
|
||||
"declineBody": "The guest sees the reason.",
|
||||
"reason": "Reason",
|
||||
"reasons": {
|
||||
"full": "We are fully booked",
|
||||
"closed": "We're closed then",
|
||||
"party": "Private event",
|
||||
"other": "Other reason"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
Button, Dialog, EmptyState, Field, IconButton, InfoTip, Input, PinPad, Select, Sheet,
|
||||
Spinner, Stepper, Switch, Textarea, ToastProvider, useToast,
|
||||
ReasonPicker, Spinner, Stepper, Switch, Textarea, ToastProvider, useToast,
|
||||
} from '../src/index.js'
|
||||
import '../src/styles.css'
|
||||
|
||||
@@ -41,6 +41,8 @@ function Demo() {
|
||||
const [theme, setTheme] = useState('light')
|
||||
const [venue, setVenue] = useState('teal')
|
||||
const [dialog, setDialog] = useState(false)
|
||||
const [reason, setReason] = useState(null)
|
||||
const [reasonOther, setReasonOther] = useState('')
|
||||
const [locked, setLocked] = useState(false)
|
||||
const [sheet, setSheet] = useState(null)
|
||||
const [on, setOn] = useState(true)
|
||||
@@ -139,6 +141,13 @@ function Demo() {
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="ReasonPicker">
|
||||
<div style={{ maxWidth: 360 }}>
|
||||
<ReasonPicker ariaLabel="Reason" value={reason} onChange={setReason} other={reasonOther} onOther={setReasonOther}
|
||||
options={[{ value: 'full', label: 'We are fully booked' }, { value: 'closed', label: 'Closed that day' }]} />
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Switch + InfoTip">
|
||||
<div style={{ display: 'grid', gap: 'var(--x-space-4)', maxWidth: 520 }}>
|
||||
<Switch checked={on} onChange={setOn} label="Print kitchen tickets" description="Send new items to the kitchen printer." />
|
||||
|
||||
@@ -315,3 +315,16 @@
|
||||
.x-switch-row__label { display: block; font-size: var(--x-text-body); line-height: var(--x-leading-body); font-weight: var(--x-weight-medium); color: var(--x-ink); cursor: pointer; }
|
||||
.x-switch-row__description { margin-top: var(--x-space-0-5); font-size: var(--x-text-label); line-height: var(--x-leading-label); color: var(--x-ink-2); }
|
||||
.x-switch-row--disabled .x-switch-row__label { cursor: not-allowed; opacity: 0.6; }
|
||||
|
||||
/* ── ReasonPicker ───────────────────────────────────────────────────────────── */
|
||||
.x-reasons { display: grid; gap: var(--x-space-2); }
|
||||
.x-reasons__list { display: grid; gap: var(--x-space-1); }
|
||||
.x-reasons__option {
|
||||
min-height: var(--x-control-md); padding: 0 var(--x-space-3);
|
||||
border: 0; border-radius: var(--x-radius-control); text-align: left;
|
||||
font: inherit; font-size: var(--x-text-body); color: var(--x-ink); background: var(--x-surface-2);
|
||||
cursor: pointer; transition: background-color var(--x-duration-fast) var(--x-ease);
|
||||
}
|
||||
.x-reasons__option:hover { background: var(--x-surface-3); }
|
||||
.x-reasons__option:focus-visible { outline: none; box-shadow: var(--x-focus-ring); }
|
||||
.x-reasons__option--on, .x-reasons__option--on:hover { background: var(--x-accent); color: var(--x-accent-fg); }
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { cx } from '../internal/cx.js'
|
||||
|
||||
export { reasonText } from './reasons.js'
|
||||
|
||||
/**
|
||||
* Pick why (a booking declined, an online order rejected…): one of the given reasons or
|
||||
* "other" with free text (plan step 4.8; first shared by the counter and the waiter's phone).
|
||||
* <ReasonPicker options={[{ value: 'full', label: 'We are full' }]} value={choice} onChange={setChoice}
|
||||
* other={text} onOther={setText} otherLabel="Other" ariaLabel="Reason" />
|
||||
* `value` is the chosen option's value or 'other'. The reason to send:
|
||||
* reasonText(value, options, other)
|
||||
*/
|
||||
export function ReasonPicker({ options, value, onChange, other = '', onOther, otherLabel = 'Other', ariaLabel, testIdPrefix = 'reason', className }) {
|
||||
const all = [...options, { value: 'other', label: otherLabel }]
|
||||
return (
|
||||
<div className={cx('x-reasons', className)}>
|
||||
<div className="x-reasons__list" role="radiogroup" aria-label={ariaLabel}>
|
||||
{all.map(o => (
|
||||
<button key={o.value} type="button" role="radio" aria-checked={value === o.value}
|
||||
className={cx('x-reasons__option', value === o.value && 'x-reasons__option--on')}
|
||||
onClick={() => onChange(o.value)} data-testid={`${testIdPrefix}-${o.value}`}>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{value === 'other' && (
|
||||
<input className="x-input" value={other} maxLength={300} autoFocus aria-label={ariaLabel}
|
||||
onChange={e => onOther?.(e.target.value)} data-testid={`${testIdPrefix}-other-text`} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/** The text to send for a ReasonPicker choice: the option's label, the typed text for 'other',
|
||||
* '' for no choice. Plain JS so Node tests can import it. */
|
||||
export function reasonText(value, options, other = '') {
|
||||
if (!value) return ''
|
||||
if (value === 'other') return other.trim()
|
||||
return options.find(o => o.value === value)?.label ?? ''
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export { Spinner } from './components/Spinner.jsx'
|
||||
export { Field, Input, Textarea, Select } from './components/Field.jsx'
|
||||
export { Switch } from './components/Switch.jsx'
|
||||
export { Stepper } from './components/Stepper.jsx'
|
||||
export { ReasonPicker, reasonText } from './components/ReasonPicker.jsx'
|
||||
export { UiLabelsProvider, DEFAULT_LABELS } from './components/labels.js'
|
||||
export { cx } from './internal/cx.js'
|
||||
export { THEMES, THEME_STORAGE_KEY, applyTheme, getStoredTheme } from './theme.js'
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { reasonText } from '../src/components/reasons.js'
|
||||
|
||||
test('reasonText: the option label, the typed text for other, nothing for no choice', () => {
|
||||
const options = [{ value: 'full', label: 'We are full' }]
|
||||
assert.equal(reasonText('full', options), 'We are full')
|
||||
assert.equal(reasonText('other', options, ' Private party '), 'Private party')
|
||||
assert.equal(reasonText(null, options), '')
|
||||
})
|
||||
@@ -7,7 +7,7 @@ import { useState } from 'react'
|
||||
import { AlertTriangle, Ban, Check, ChefHat, MessageSquare, Phone, UserX, Users } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Input, Select } from '@xenia/ui'
|
||||
import { Button, Dialog, EmptyState, ReasonPicker, Select, reasonText } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { bookingSteps, foodState, freeTables, whenLabel } from './logic/bookings'
|
||||
|
||||
@@ -129,7 +129,8 @@ function DeclineDialog({ busy, error, onClose, onDecline }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const [choice, setChoice] = useState(null)
|
||||
const [other, setOther] = useState('')
|
||||
const reason = choice === 'other' ? other.trim() : choice ? t(`pos.bookings.reasons.${choice}`) : ''
|
||||
const options = REASONS.map(r => ({ value: r, label: t(`pos.bookings.reasons.${r}`) }))
|
||||
const reason = reasonText(choice, options, other)
|
||||
return (
|
||||
<Dialog open size="sm" title={t('pos.bookings.declineTitle')} onClose={busy ? undefined : onClose}
|
||||
footer={<>
|
||||
@@ -140,16 +141,8 @@ function DeclineDialog({ busy, error, onClose, onDecline }) {
|
||||
</>}>
|
||||
<div className="grid gap-2">
|
||||
<p className="text-body text-ink-2">{t('pos.online.rejectBody')}</p>
|
||||
<div className="grid gap-1" role="radiogroup" aria-label={t('pos.online.reason')}>
|
||||
{[...REASONS, 'other'].map(r => (
|
||||
<button key={r} type="button" role="radio" aria-checked={choice === r} onClick={() => setChoice(r)} data-testid={`decline-${r}`}
|
||||
className={`min-h-[var(--x-control-md)] px-3 rounded-control text-left text-body transition-colors duration-fast
|
||||
${choice === r ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink hover:bg-surface-3'}`}>
|
||||
{t(`pos.bookings.reasons.${r}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{choice === 'other' && <Input value={other} onChange={e => setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} />}
|
||||
<ReasonPicker options={options} value={choice} onChange={setChoice} other={other} onOther={setOther}
|
||||
otherLabel={t('pos.bookings.reasons.other')} ariaLabel={t('pos.online.reason')} testIdPrefix="decline" />
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useState } from 'react'
|
||||
import { AlertTriangle, Ban, Banknote, Bike, Check, ChefHat, Clock, MapPin, MessageSquare, PackageCheck, Phone, ShoppingBag, Utensils } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Input } from '@xenia/ui'
|
||||
import { Button, Dialog, EmptyState, ReasonPicker, reasonText } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { diffRows, finishWord as finishOf, kindOf, nextStep } from './logic/online'
|
||||
import { itemPayments, orderLines, orderSums, qtyLabel } from './logic/tables'
|
||||
@@ -190,7 +190,8 @@ function RejectDialog({ busy, error, onClose, onReject }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const [choice, setChoice] = useState(null)
|
||||
const [other, setOther] = useState('')
|
||||
const reason = choice === 'other' ? other.trim() : choice ? t(`pos.online.reasons.${choice}`) : ''
|
||||
const options = REASONS.map(r => ({ value: r, label: t(`pos.online.reasons.${r}`) }))
|
||||
const reason = reasonText(choice, options, other)
|
||||
return (
|
||||
<Dialog open size="sm" title={t('pos.online.rejectTitle')} onClose={busy ? undefined : onClose}
|
||||
footer={<>
|
||||
@@ -201,18 +202,8 @@ function RejectDialog({ busy, error, onClose, onReject }) {
|
||||
</>}>
|
||||
<div className="grid gap-2">
|
||||
<p className="text-body text-ink-2">{t('pos.online.rejectBody')}</p>
|
||||
<div className="grid gap-1" role="radiogroup" aria-label={t('pos.online.reason')}>
|
||||
{[...REASONS, 'other'].map(r => (
|
||||
<button key={r} type="button" role="radio" aria-checked={choice === r} onClick={() => setChoice(r)} data-testid={`reason-${r}`}
|
||||
className={`min-h-[var(--x-control-md)] px-3 rounded-control text-left text-body transition-colors duration-fast
|
||||
${choice === r ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink hover:bg-surface-3'}`}>
|
||||
{t(`pos.online.reasons.${r}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{choice === 'other' && (
|
||||
<Input value={other} onChange={e => setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} data-testid="reason-text" />
|
||||
)}
|
||||
<ReasonPicker options={options} value={choice} onChange={setChoice} other={other} onOther={setOther}
|
||||
otherLabel={t('pos.online.reasons.other')} ariaLabel={t('pos.online.reason')} testIdPrefix="reason" />
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
+72
-2
@@ -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' } })
|
||||
@@ -15,7 +16,7 @@ const vite = await startViteNative({ port: 5181, backendUrl: backend.url })
|
||||
const APP = 'http://localhost:5181'
|
||||
const TOKEN_KEY = 'xenia:dev:token'
|
||||
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
|
||||
const r = reporter('waiter: sign-in v2, lock, approvals (4.2), keys (4.3), server prices (4.4), languages (4.5), table history (4.7), look (4.6)')
|
||||
const r = reporter('waiter: sign-in v2, lock, approvals (4.2), keys (4.3), server prices (4.4), languages (4.5), table history (4.7), look (4.6), owner choices (4.8)')
|
||||
const errors = []
|
||||
let failures = 0
|
||||
|
||||
@@ -274,6 +275,75 @@ try {
|
||||
await a.getByTestId('menu-language-en').click()
|
||||
await waitFor(async () => (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')
|
||||
// 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`)
|
||||
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`)
|
||||
|
||||
// bookings on the phone: a request made online is confirmed and the guests seated (the counter's flow)
|
||||
const sqlite = sql => execFileSync(PYTHON, ['-c', `import sqlite3; c = sqlite3.connect(r"${path.join(backend.dataDir, 'pos.db')}"); r = c.execute(${JSON.stringify(sql)}).fetchall(); c.commit(); print(r)`], { encoding: 'utf8' }).trim()
|
||||
sqlite("insert into reservations (guest_name, party_size, phone, reserved_for, status, source, online_ref, created_at, updated_at) values ('E2E Guest', 2, '6900000000', datetime('now', '+2 hours'), 'requested', 'online', 'ORD-E2E', datetime('now'), datetime('now'))")
|
||||
const waiterRole = await api('GET', '/api/waiters/roles/waiter/permissions', { token: boss })
|
||||
await api('PUT', '/api/waiters/roles/waiter/permissions', { token: boss, body: { keys: [...waiterRole.keys, 'connect_orders.manage'] } })
|
||||
await a.goto(`${APP}/tables`)
|
||||
await a.reload()
|
||||
await a.locator('button').filter({ has: a.locator('svg') }).first().click().catch(() => {})
|
||||
const drawerHasBookings = await a.getByRole('button', { name: 'Bookings' }).isVisible({ timeout: 5000 }).catch(() => false)
|
||||
await a.goto(`${APP}/bookings`)
|
||||
const card = () => a.locator('[data-testid="booking-card"]').filter({ hasText: 'E2E Guest' })
|
||||
await card().first().waitFor({ timeout: 10_000 }).catch(() => {})
|
||||
r.check('4.8: with the online-orders key the phone lists the booking request (drawer: Bookings)', drawerHasBookings && await card().getAttribute('data-status') === 'requested')
|
||||
await card().getByTestId('booking-confirm').click()
|
||||
await waitFor(async () => await card().getAttribute('data-status') === 'pending', 10_000, 300)
|
||||
await card().getByTestId('booking-table').selectOption({ index: 1 })
|
||||
await card().getByTestId('booking-arrive').click()
|
||||
const seated = await waitFor(async () => /arrived', \d+/.test(sqlite("select status, table_id from reservations where online_ref = 'ORD-E2E'")) && 1, 10_000, 500)
|
||||
r.check('4.8: …confirmed and seated at a table from the phone', !!seated, sqlite("select status, table_id from reservations where online_ref = 'ORD-E2E'"))
|
||||
await api('PUT', '/api/waiters/roles/waiter/permissions', { token: boss, body: { keys: waiterRole.default_keys } })
|
||||
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')
|
||||
|
||||
@@ -25,6 +25,7 @@ import ChatListPage from './pages/ChatListPage'
|
||||
import ChatThreadPage from './pages/ChatThreadPage'
|
||||
import ShiftOverviewPage from './pages/ShiftOverviewPage'
|
||||
import OrderLogPage from './pages/OrderLogPage'
|
||||
import BookingsPage from './pages/BookingsPage'
|
||||
import { NotificationProvider } from './context/NotificationContext'
|
||||
import { LiveProvider } from './context/LiveContext'
|
||||
import ConnectivityBar from './components/ConnectivityBar'
|
||||
@@ -504,6 +505,7 @@ function Routed() {
|
||||
<Route path="/settings/favorites" element={<FavoritesSetupPage />} />
|
||||
<Route path="/shift-overview" element={<ShiftOverviewPage />} />
|
||||
<Route path="/order-log" element={<OrderLogPage />} />
|
||||
<Route path="/bookings" element={<BookingsPage />} />
|
||||
<Route path="/messages" element={<ChatListRoute />} />
|
||||
<Route path="/messages/:conversationId" element={<ChatThreadPage />} />
|
||||
</Route>
|
||||
|
||||
@@ -209,6 +209,7 @@ function BellButton({ onClick, count }) {
|
||||
|
||||
function NotificationDrawer({ messages, onClose }) {
|
||||
const { t } = useTranslation('waiter')
|
||||
const navigate = useNavigate()
|
||||
const { formatTime } = useFormat()
|
||||
return (
|
||||
<div className="modal-overlay" onClick={onClose}>
|
||||
@@ -224,9 +225,13 @@ function NotificationDrawer({ messages, onClose }) {
|
||||
{messages.map(msg => {
|
||||
const tableIds = (() => { try { return JSON.parse(msg.table_ids || '[]') } catch { 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)',
|
||||
display: 'flex', gap: 12, alignItems: 'flex-start',
|
||||
cursor: msg.message_type === 'qr_order' && tableIds.length ? 'pointer' : undefined,
|
||||
}}>
|
||||
<span style={{ fontSize: 20, flexShrink: 0 }}>📢</span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
@@ -270,6 +275,19 @@ const DRAWER_NAV_ITEMS = [
|
||||
},
|
||||
{ ...NAV_REGISTRY.orders },
|
||||
{ ...NAV_REGISTRY.messages },
|
||||
{
|
||||
// table bookings (4.8): for whoever handles online orders or manages reservations
|
||||
key: 'bookings',
|
||||
label: 'nav.bookings',
|
||||
href: '/bookings',
|
||||
match: (loc) => loc.pathname === '/bookings',
|
||||
icon: (
|
||||
<svg width="22" height="22" viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="5" width="18" height="16" rx="2" stroke="currentColor" strokeWidth="2"/>
|
||||
<path d="M3 10h18M8 3v4M16 3v4M9 15l2 2 4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'shift-overview',
|
||||
label: 'nav.shiftSummary',
|
||||
@@ -370,6 +388,10 @@ function SideDrawer({ open, onClose }) {
|
||||
const { t } = useTranslation('waiter')
|
||||
const navigate = useNavigate()
|
||||
const chatOn = useChatOn()
|
||||
const bookingsModule = useModule('connect_orders')
|
||||
const bookingsOnline = useCan('connect_orders.manage')
|
||||
const bookingsManage = useCan('reservations.manage')
|
||||
const bookingsOn = bookingsModule && (bookingsOnline || bookingsManage)
|
||||
const location = useLocation()
|
||||
const { activeZoneTab, setActiveZoneTab } = useTableViewStore()
|
||||
|
||||
@@ -420,7 +442,7 @@ function SideDrawer({ open, onClose }) {
|
||||
<div style={{ fontSize: 10, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1, padding: '4px 10px 8px' }}>
|
||||
{t('shell.navigation')}
|
||||
</div>
|
||||
{DRAWER_NAV_ITEMS.filter(shown(chatOn)).map(item => {
|
||||
{DRAWER_NAV_ITEMS.filter(shown(chatOn)).filter(item => item.key !== 'bookings' || bookingsOn).map(item => {
|
||||
const isStandaloneActive = location.pathname === '/tables' && activeZoneTab === 'standalone'
|
||||
const active = item.key === 'standalone'
|
||||
? isStandaloneActive
|
||||
|
||||
@@ -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' ? (
|
||||
<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 = (
|
||||
<span
|
||||
className={[
|
||||
@@ -394,6 +403,7 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
|
||||
>
|
||||
{item.product?.name || `#${item.product_id}`}
|
||||
{courseBadge}
|
||||
{sourceBadge}
|
||||
</span>
|
||||
)
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<p data-testid="seats-hint" data-over={over ? 'true' : 'false'}
|
||||
style={{ textAlign: 'center', fontSize: 13, margin: '-12px 0 16px', color: over ? 'var(--x-warning)' : 'var(--muted)', fontWeight: over ? 600 : 400 }}>
|
||||
{over ? t('seats.over', { count, seats }) : t('seats.table', { count: seats })}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<span data-testid="table-seats" title={t('seats.table', { count: table.seat_count })}
|
||||
style={{ marginLeft: 5, fontSize: '0.55em', fontWeight: 700, opacity: 0.6, verticalAlign: 'middle', whiteSpace: 'nowrap' }}>
|
||||
<svg width="0.9em" height="0.9em" viewBox="0 0 24 24" fill="none" style={{ verticalAlign: '-0.1em', marginRight: 1 }}>
|
||||
<circle cx="12" cy="7" r="4" stroke="currentColor" strokeWidth="2.4" />
|
||||
<path d="M4 21v-1a6 6 0 0 1 6-6h4a6 6 0 0 1 6 6v1" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" />
|
||||
</svg>
|
||||
{table.seat_count}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── 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}`}<SeatCount table={table} />
|
||||
</div>
|
||||
|
||||
{/* 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}`}<SeatCount table={table} />
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
@@ -397,7 +417,7 @@ function Card2x2({ table, order, flags, _waiterObjects, cfg, statusKey, kdsBadge
|
||||
fontSize: 'clamp(22px, 5.5vw, 36px)', fontWeight: 800,
|
||||
lineHeight: 1.05, color: cfg.nameText, letterSpacing: -0.5,
|
||||
}}>
|
||||
{table.label || `T${table.number}`}
|
||||
{table.label || `T${table.number}`}<SeatCount table={table} />
|
||||
</span>
|
||||
<div style={{ marginTop: 5 }}>
|
||||
<StatusPill label={t(STATUS_LABELS[statusKey])} badgeBg={cfg.badgeBg} badgeText={cfg.badgeText} small />
|
||||
@@ -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}`}<SeatCount table={table} />
|
||||
</div>
|
||||
|
||||
{/* 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}`}<SeatCount table={table} />
|
||||
</div>
|
||||
{groupName && (
|
||||
<div style={{
|
||||
@@ -604,7 +624,7 @@ function Card4x3({ table, order, flags, waiterObjects, groupName, cfg, statusKey
|
||||
fontWeight: 800, fontSize: 'clamp(28px, 6vw, 40px)',
|
||||
letterSpacing: -1.5, lineHeight: 1, color: cfg.nameText,
|
||||
}}>
|
||||
{table.label || `T${table.number}`}
|
||||
{table.label || `T${table.number}`}<SeatCount table={table} />
|
||||
</div>
|
||||
{groupName && (
|
||||
<div style={{
|
||||
|
||||
@@ -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 }) {
|
||||
</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
|
||||
onClick={() => onAck(message.id)}
|
||||
style={{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import '@xenia/ui/tokens.css' // shared --x-* tokens: the waiter's --bg/--text… are made of them (4.6)
|
||||
import '@xenia/ui/styles.css' // shared --x-* tokens (the waiter's --bg/--text… are made of them, 4.6) + the .x-* components (4.8)
|
||||
import './index.css'
|
||||
|
||||
// The theme before anything renders (no light flash on a dark phone): the user's light/dark
|
||||
|
||||
@@ -17,6 +17,7 @@ import { money } from '../i18n'
|
||||
import { LineError, estimate, wireLine } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { fade } from '../logic/colour'
|
||||
import SeatsHint from '../components/SeatsHint'
|
||||
|
||||
// A cart item whose option is not on the menu any more (4.4: lines go by id)
|
||||
const lineErrorText = (err, t) => 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 }) {
|
||||
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 20px' }}>
|
||||
{t('detail.guests.question')}
|
||||
</p>
|
||||
<SeatsHint seats={seats} count={count} />
|
||||
|
||||
{/* Quick pick */}
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 20 }}>
|
||||
@@ -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 && (
|
||||
<CustomerCountModal
|
||||
value={customerCount}
|
||||
seats={seats}
|
||||
onChange={v => setCustomerCount(v)}
|
||||
onClose={() => setCustomerCountOpen(false)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { ReasonPicker, reasonText } from '@xenia/ui'
|
||||
import AppShell from '../components/AppShell'
|
||||
import client from '../api/client'
|
||||
import { apiError } from '../api/errors'
|
||||
import db from '../db/posdb'
|
||||
|
||||
// Table bookings on the phone (plan step 4.8), the counter's flow (terminal BookingPanel):
|
||||
// requests made online are confirmed or declined (the guest sees the answer and the reason);
|
||||
// today's confirmed bookings are seated at a free table (their food's order moves there) or
|
||||
// cancelled / marked as a no-show. For whoever handles online orders or manages reservations.
|
||||
const DECLINE_REASONS = ['full', 'closed', 'party']
|
||||
const OPEN = ['open', 'partially_paid', 'paid']
|
||||
|
||||
export default function BookingsPage() {
|
||||
const { t } = useTranslation('waiter')
|
||||
const [data, setData] = useState(null)
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(null)
|
||||
const [declining, setDeclining] = useState(null)
|
||||
const [free, setFree] = useState([])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const r = await client.get('/api/connect/bookings')
|
||||
setData(r.data)
|
||||
setError('')
|
||||
} catch (err) { setError(apiError(err, t('bookings.loadFailed'))) }
|
||||
try {
|
||||
const [tables, orders] = await Promise.all([db.pos_tables.toArray(), db.pos_orders.toArray()])
|
||||
const busyTables = new Set(orders.filter(o => OPEN.includes(o.status)).map(o => o.table_id))
|
||||
setFree(tables.filter(tb => tb.is_active !== false && !busyTables.has(tb.id)))
|
||||
} catch { setFree([]) }
|
||||
}, [t])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
const onLive = e => { if (['reservation_updated', 'order_updated', 'online_reservation'].includes(e.detail?.type)) load() }
|
||||
window.addEventListener('live-event', onLive)
|
||||
window.addEventListener('live-reconnected', load)
|
||||
return () => { window.removeEventListener('live-event', onLive); window.removeEventListener('live-reconnected', load) }
|
||||
}, [load])
|
||||
|
||||
async function run(booking, path, body) {
|
||||
setBusy(booking.id)
|
||||
setError('')
|
||||
try {
|
||||
await client.post(`/api/connect/bookings/${booking.id}/${path}`, body ?? {})
|
||||
setDeclining(null)
|
||||
} catch (err) { setError(apiError(err, t('bookings.failed'))) } finally {
|
||||
setBusy(null)
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
const requested = data?.requested ?? []
|
||||
const upcoming = data?.upcoming ?? []
|
||||
return (
|
||||
<AppShell title={t('bookings.title')}>
|
||||
<div style={{ padding: '12px 12px 96px', display: 'flex', flexDirection: 'column', gap: 10 }} data-testid="bookings">
|
||||
{error && <p className="error-msg" role="alert">{error}</p>}
|
||||
{!data && !error && <p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24 }}>{t('common.loading')}</p>}
|
||||
{data && (
|
||||
<>
|
||||
<h2 style={sectionTitle}>{t('bookings.requests', { count: requested.length })}</h2>
|
||||
{requested.length === 0 && <p style={empty}>{t('bookings.noRequests')}</p>}
|
||||
{requested.map(b => (
|
||||
<BookingCard key={b.id} booking={b}>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn btn--accent" style={{ flex: 1 }} disabled={busy === b.id} onClick={() => run(b, 'confirm')} data-testid="booking-confirm">
|
||||
{t('bookings.confirm')}
|
||||
</button>
|
||||
<button className="btn btn--secondary" style={{ flex: 1 }} disabled={busy === b.id} onClick={() => setDeclining(b)} data-testid="booking-decline">
|
||||
{t('bookings.decline')}
|
||||
</button>
|
||||
</div>
|
||||
</BookingCard>
|
||||
))}
|
||||
|
||||
<h2 style={{ ...sectionTitle, marginTop: 12 }}>{t('bookings.upcoming', { count: upcoming.length })}</h2>
|
||||
{upcoming.length === 0 && <p style={empty}>{t('bookings.noUpcoming')}</p>}
|
||||
{upcoming.map(b => (
|
||||
<BookingCard key={b.id} booking={b}>
|
||||
<SeatControls booking={b} free={free} busy={busy === b.id} onSeat={tableId => run(b, 'arrive', { table_id: tableId })}
|
||||
onCancel={status => run(b, 'cancel', { status })} />
|
||||
</BookingCard>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{declining && <DeclineSheet booking={declining} busy={busy === declining.id} onClose={() => setDeclining(null)} onDecline={reason => run(declining, 'decline', { reason })} />}
|
||||
</AppShell>
|
||||
)
|
||||
}
|
||||
|
||||
const sectionTitle = { fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6, margin: '4px 2px 0' }
|
||||
const empty = { color: 'var(--muted)', fontSize: 14, padding: '6px 2px' }
|
||||
|
||||
function BookingCard({ booking: b, children }) {
|
||||
const { t } = useTranslation('waiter')
|
||||
const { formatTime, formatDate, formatDateTime, formatMoney } = useFormat()
|
||||
const today = formatDate(b.reserved_for) === formatDate(new Date())
|
||||
return (
|
||||
<div data-testid="booking-card" data-booking={b.id} data-status={b.status}
|
||||
style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 14, padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
|
||||
<span style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)', flex: 1 }}>
|
||||
{today ? t('bookings.today', { time: formatTime(b.reserved_for) }) : formatDateTime(b.reserved_for, 'datetimeShort')}
|
||||
</span>
|
||||
{b.ref && <span style={{ fontSize: 12, color: 'var(--muted)' }}>{b.ref}</span>}
|
||||
</div>
|
||||
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>
|
||||
{b.guest_name} · {t('bookings.people', { count: b.party_size })}
|
||||
{b.table_label && <span style={{ color: 'var(--muted)', fontWeight: 500 }}> · {b.table_label}</span>}
|
||||
</div>
|
||||
{b.phone && <a href={`tel:${b.phone}`} style={{ fontSize: 14, color: 'var(--accent)' }}>{b.phone}</a>}
|
||||
{b.note && <div style={{ fontSize: 13, color: 'var(--x-warning-ink)', background: 'var(--x-warning-soft)', borderRadius: 8, padding: '6px 10px' }}>{b.note}</div>}
|
||||
{b.lines?.length > 0 && (
|
||||
<div style={{ fontSize: 13, color: 'var(--text2)', borderTop: '1px solid var(--border)', paddingTop: 6 }}>
|
||||
<div style={{ fontWeight: 700, marginBottom: 2 }}>
|
||||
{b.order_id ? t('bookings.foodSent') : b.fire_at ? t('bookings.foodAt', { time: formatTime(b.fire_at) }) : t('bookings.foodOnConfirm')}
|
||||
</div>
|
||||
{b.lines.map((l, i) => <div key={i}>{l.quantity}× {l.name}</div>)}
|
||||
<div style={{ fontWeight: 700, marginTop: 2 }}>{formatMoney(b.total)}</div>
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SeatControls({ booking, free, busy, onSeat, onCancel }) {
|
||||
const { t } = useTranslation('waiter')
|
||||
const [table, setTable] = useState('')
|
||||
const options = free.map(tb => ({ id: tb.id, name: tb.label || `T${tb.number}`, seats: tb.seat_count }))
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<select value={table} onChange={e => setTable(e.target.value)} aria-label={t('bookings.table')} data-testid="booking-table"
|
||||
style={{ height: 44, borderRadius: 10, border: '1px solid var(--border)', background: 'var(--bg3)', color: 'var(--text)', padding: '0 10px', fontSize: 15 }}>
|
||||
<option value="">{t('bookings.noTable')}</option>
|
||||
{options.map(o => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}{o.seats ? ` · ${t('seats.table', { count: o.seats })}` : ''}
|
||||
{o.seats && booking.party_size > o.seats ? ' ⚠' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="btn btn--accent" disabled={busy} onClick={() => onSeat(table ? Number(table) : null)} data-testid="booking-arrive">
|
||||
{t('bookings.arrive')}
|
||||
</button>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn btn--secondary" style={{ flex: 1 }} disabled={busy} onClick={() => onCancel('cancelled')} data-testid="booking-cancel">{t('bookings.cancel')}</button>
|
||||
<button className="btn btn--secondary" style={{ flex: 1 }} disabled={busy} onClick={() => onCancel('no_show')} data-testid="booking-noshow">{t('bookings.noShow')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DeclineSheet({ booking, busy, onClose, onDecline }) {
|
||||
const { t } = useTranslation('waiter')
|
||||
const [choice, setChoice] = useState(null)
|
||||
const [other, setOther] = useState('')
|
||||
const options = DECLINE_REASONS.map(r => ({ value: r, label: t(`bookings.reasons.${r}`) }))
|
||||
const reason = reasonText(choice, options, other)
|
||||
return (
|
||||
<div className="modal-overlay" onClick={busy ? undefined : onClose}>
|
||||
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="decline-sheet">
|
||||
<div className="modal-handle" />
|
||||
<h2 className="modal-title">{t('bookings.declineTitle', { name: booking.guest_name })}</h2>
|
||||
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>{t('bookings.declineBody')}</p>
|
||||
<ReasonPicker options={options} value={choice} onChange={setChoice} other={other} onOther={setOther}
|
||||
otherLabel={t('bookings.reasons.other')} ariaLabel={t('bookings.reason')} testIdPrefix="decline" />
|
||||
<div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
|
||||
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose} disabled={busy}>{t('common.back')}</button>
|
||||
<button className="btn btn--danger" style={{ flex: 1 }} disabled={!reason || busy} onClick={() => onDecline(reason)} data-testid="decline-confirm">
|
||||
{t('bookings.decline')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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() {
|
||||
</section>
|
||||
|
||||
{/* Card density */}
|
||||
{/* Seats on the table cards (4.8) */}
|
||||
<section>
|
||||
<h2 style={sectionTitle}>{t('settings.seats.title')}</h2>
|
||||
<div style={{ marginTop: 14 }}>
|
||||
<ToggleRow label={t('settings.seats.label')} desc={t('settings.seats.desc')} checked={showSeats !== false} onChange={() => setShowSeats(!(showSeats !== false))} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 style={sectionTitle}>{t('settings.density.title')}</h2>
|
||||
<p style={sectionSub}>{t('settings.density.sub')}</p>
|
||||
|
||||
@@ -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: (
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 6h10M4 12h16M4 18h10M17 4l3 2-3 2M17 16l3 2-3 2" stroke="var(--x-info)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
),
|
||||
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
|
||||
<div className="modal-overlay modal-overlay--top" onClick={onClose}>
|
||||
<div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()} style={{ gap: 0 }}>
|
||||
<div className="modal-handle" />
|
||||
<h2 className="modal-title" style={{ marginBottom: 16 }}>ACTIONS</h2>
|
||||
<h2 className="modal-title" style={{ marginBottom: 16 }}>{t('detail.btn.actions')}</h2>
|
||||
{actions.map((a, i) => (
|
||||
<button
|
||||
key={i}
|
||||
@@ -1009,7 +1031,7 @@ function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, o
|
||||
|
||||
// ─── 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]
|
||||
@@ -1021,6 +1043,7 @@ function CustomerCountModal({ value, onChange, onClose }) {
|
||||
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 20px' }}>
|
||||
{t('detail.guests.question')}
|
||||
</p>
|
||||
<SeatsHint seats={seats} count={count} />
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 20 }}>
|
||||
{QUICK.map(n => (
|
||||
<button key={n} onClick={() => setCount(n)} style={{
|
||||
@@ -1057,6 +1080,7 @@ export default function TableDetailPage() {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [table, setTable] = useState(null)
|
||||
const [closeUnpaidAllowed, setCloseUnpaidAllowed] = useState(false) // 4.8: venue setting
|
||||
const [order, setOrder] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [paying, setPaying] = useState(false)
|
||||
@@ -1246,7 +1270,10 @@ export default function TableDetailPage() {
|
||||
|
||||
useEffect(() => {
|
||||
getVenueSettings()
|
||||
.then(r => setCardEnabled(r.data?.['payments.card_enabled']?.value === 'true'))
|
||||
.then(r => {
|
||||
setCardEnabled(r.data?.['payments.card_enabled']?.value === 'true')
|
||||
setCloseUnpaidAllowed(r.data?.['orders.close_with_unpaid']?.value === 'true')
|
||||
})
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
@@ -1648,7 +1675,7 @@ export default function TableDetailPage() {
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: 14 }}>⚡</span>
|
||||
<span>ACTIONS</span>
|
||||
<span>{t('detail.btn.actions')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
@@ -1867,7 +1894,7 @@ export default function TableDetailPage() {
|
||||
border: 'none', cursor: 'pointer',
|
||||
fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
|
||||
}}
|
||||
>CLEAR</button>
|
||||
>{t('detail.btn.clear')}</button>
|
||||
|
||||
{/* ALL */}
|
||||
{!allActiveSelected && (
|
||||
@@ -1881,7 +1908,7 @@ export default function TableDetailPage() {
|
||||
border: 'none', cursor: 'pointer',
|
||||
fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
|
||||
}}
|
||||
>ALL</button>
|
||||
>{t('detail.btn.all')}</button>
|
||||
)}
|
||||
|
||||
{/* SERVED — mark selected as served */}
|
||||
@@ -1896,7 +1923,7 @@ export default function TableDetailPage() {
|
||||
cursor: 'pointer',
|
||||
fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
|
||||
}}
|
||||
>SERVED</button>
|
||||
>{t('detail.btn.served')}</button>
|
||||
|
||||
{/* ACTIONS — opens item action modal */}
|
||||
<button
|
||||
@@ -1913,7 +1940,7 @@ export default function TableDetailPage() {
|
||||
border: 'none', cursor: 'pointer',
|
||||
fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
|
||||
}}
|
||||
>ACTIONS</button>
|
||||
>{t('detail.btn.actions')}</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
@@ -1957,7 +1984,7 @@ export default function TableDetailPage() {
|
||||
border: 'none', cursor: 'pointer',
|
||||
fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
|
||||
}}
|
||||
>CLEAR</button>
|
||||
>{t('detail.btn.clear')}</button>
|
||||
|
||||
<button
|
||||
onClick={() => doMarkServed(paidSelectedIds)}
|
||||
@@ -1970,7 +1997,7 @@ export default function TableDetailPage() {
|
||||
cursor: 'pointer',
|
||||
fontSize: 13, fontWeight: 700, letterSpacing: 0.5,
|
||||
}}
|
||||
>SERVED</button>
|
||||
>{t('detail.btn.served')}</button>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
@@ -2029,7 +2056,7 @@ export default function TableDetailPage() {
|
||||
onClick={() => navigate(addItemsPath)}
|
||||
style={{ borderRadius: 999, flex: 1 }}
|
||||
>
|
||||
<span style={{ marginRight: 6 }}>+</span>ADD
|
||||
<span style={{ marginRight: 6 }}>+</span>{t('detail.btn.add')}
|
||||
</button>
|
||||
|
||||
{canPay && (
|
||||
@@ -2042,7 +2069,7 @@ export default function TableDetailPage() {
|
||||
>
|
||||
{paying ? '…' : (
|
||||
<>
|
||||
<span>€ PAY</span>
|
||||
<span>{t('detail.btn.pay')}</span>
|
||||
{selectedIds.length > 0 && (
|
||||
<span style={{
|
||||
background: 'rgb(var(--x-scrim-rgb) / 0.25)', color: 'var(--x-on-colour)',
|
||||
@@ -2060,14 +2087,16 @@ export default function TableDetailPage() {
|
||||
className="btn btn--danger"
|
||||
onClick={() => {
|
||||
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}
|
||||
>
|
||||
<span style={{ marginRight: 6 }}>✕</span>CLOSE
|
||||
<span style={{ marginRight: 6 }}>✕</span>{t('detail.btn.close')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
@@ -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 && (
|
||||
<CustomerCountModal
|
||||
value={customerCount}
|
||||
seats={table?.seat_count}
|
||||
onChange={async (v) => {
|
||||
setCustomerCount(v)
|
||||
if (order) {
|
||||
@@ -2288,14 +2330,14 @@ export default function TableDetailPage() {
|
||||
<div className="modal-handle" />
|
||||
<h2 className="modal-title">{t('detail.close.title')}</h2>
|
||||
<p style={{ color: 'var(--x-ink-2)', textAlign: 'center', marginBottom: 24 }}>
|
||||
{t('detail.close.body')}
|
||||
{allPaid ? t('detail.close.body') : t('detail.close.unpaid', { count: activeItems.length })}
|
||||
</p>
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={() => setConfirmClose(false)}>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button className="btn btn--danger" style={{ flex: 1 }} onClick={closeOrder}>
|
||||
CLOSE
|
||||
<button className="btn btn--danger" style={{ flex: 1 }} onClick={closeOrder} data-testid="close-confirm">
|
||||
{t('detail.btn.close')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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 }),
|
||||
|
||||
Reference in New Issue
Block a user