diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 3a7fe0b..48c3b1e 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -70,6 +70,10 @@ CODES: dict[str, tuple[int, str]] = { "pos.payment_invalid": (422, "This payment doesn't add up ({reason})."), "pos.fiscal_vat_missing": (422, "Fiscal receipts are on, but these products have no VAT group: {names}."), "pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."), + "pos.table_not_found": (404, "Table {table_id} not found."), + "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."), "kds.item_not_found": (404, "Item {item_id} not found on this order."), "kds.item_claimed": (409, "{name} is already on this item."), "kds.claim_needs_staff": (403, "Only a staff member can claim an item."), diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index 07d3fa8..d8553fc 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -508,16 +508,8 @@ def add_items( if order.source == "online": order_channel = "online" # Snapshot existing cart items for condition evaluation - existing_cart = [ - { - "product_id": i.product_id, - "category_id": i.product.primary_category_id if i.product else None, - "category_ids": i.product.category_ids if i.product else [], - "quantity": i.quantity, - "unit_price": i.unit_price, - } - for i in order.items if i.status == "active" - ] + from services.pos_cart import order_cart + existing_cart = order_cart(order) # the counter's table quote starts from the same (3.3c) for item_in in body.items: product = db.query(Product).filter(Product.id == item_in.product_id).first() @@ -800,6 +792,8 @@ def cancel_item( _audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=cancelled_ids, note=_approval_note(approval)) db.commit() + broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, + "action": "items_cancelled", "item_ids": cancelled_ids}) should_print = print_cancellation if is_manager else True if should_print: @@ -1197,6 +1191,9 @@ def cancel_items_bulk( if cancelled_ids: _audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=cancelled_ids, note=_approval_note(approval)) db.commit() + if cancelled_ids: + broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, + "action": "items_cancelled", "item_ids": cancelled_ids}) should_print = body.print_cancellation if is_manager else True if should_print and cancelled_ids: diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index 8f7edd1..b547f87 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -5,6 +5,15 @@ GET /api/pos/menu categories and products to sell, with options and today' POST /api/pos/quote a cart priced by the backend (services/pos_cart.py) POST /api/pos/sales a quick sale (3.3b): order + items + payment(s) in one call, the cash drawer on cash, the fiscal receipt as for any payment +GET /api/pos/tables the tables the cashier may serve (their zones, as in the waiter app) + with each one's open order: totals, people, flags, ready items (3.3c) +POST /api/pos/tables/{id}/items send cart lines to a table (opens its order if it has none) +POST /api/pos/orders/{id}/pay pay chosen items of a table's order (cash/card/split, drawer) +POST /api/pos/orders/{id}/close close a fully paid order (never writes unpaid items off) + +Tables use the waiter app's rules and functions (routers/orders.py): zone access, the person +assigned to an order, business day, kitchen tickets, shift totals. Cancelling items is the +waiter's own POST /api/orders/{id}/cancel-items (manager approval when the cashier can't). Prices are never computed on the screen: the menu's `price` is the pricing engine's answer for one unit with no options right now (happy hours, price groups), and the cart is priced with @@ -131,6 +140,7 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi class QuoteBody(BaseModel): order_type: Literal["takeaway", "here"] = "takeaway" lines: List[dict] = Field(default_factory=list, max_length=200) + order_id: Optional[int] = None # adding to a table's order: its items count for deals (3.3c) def _adjustments(db, events) -> list[dict]: @@ -149,7 +159,11 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi """The cart priced exactly as the order will be: per line the unit price (base + options, then price groups/modifiers), its total, what was chosen (names) and any adjustment.""" lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)] - priced = pos_cart.price_lines(db, lines, body.order_type) if lines else [] + order_type, existing = body.order_type, None + if body.order_id is not None: + order = _order_for(db, user, body.order_id) + order_type, existing = order.order_type or "here", pos_cart.order_cart(order) + priced = pos_cart.price_lines(db, lines, order_type, existing) if lines else [] out = [] for line, (unit, events) in zip(lines, priced): adj = pos_cart.discount_adjustment(unit, line.discount_pct) @@ -161,7 +175,7 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi "entries": [{"name": e["name"], "price": e["price_delta"], "type": e["type"]} for e in line.entries], "removed": line.removed, "notes": line.notes, "adjustments": _adjustments(db, events), }) - return {"order_type": body.order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)} + return {"order_type": order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)} @@ -196,42 +210,23 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us shift, the fiscal receipt, auto-close), and open the cash drawer of the screen's receipt printer when cash was taken. The checks run before anything is written. Discounted lines need ordering.prices.modify or a manager's approval (D-10).""" - from core.access.context import authorize, current_device - from core.modules import device_config from models.order import OrderItem - from models.printer import Printer - from models.shift import WaiterShift - from models.user import User from routers import orders as orders_api - from schemas.order import AddItemsRequest, OrderCreate, OrderItemInput, PayItemsRequest, SelectedOptionInput - from services.fiscal_service import is_fiscal_enabled - from services.printer_service import open_cash_drawer + from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest - if not isinstance(user, User) or db.query(WaiterShift).filter( - WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() is None: - raise XeniaError("pos.shift_required") + _require_shift(db, user) lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)] groups = _payment_groups(body, len(lines)) - if any(line.discount_pct for line in lines): - authorize(request, db, user, "ordering.prices.modify", target="pos sale discount") - if is_fiscal_enabled(db): - missing = sorted({line.product.name for line in lines if not line.product.fiscal_vat_group_id}) - if missing: - raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing)) + _check_discounts(request, db, user, lines) + _check_fiscal(db, {line.product for line in lines}) priced = pos_cart.price_lines(db, lines, body.order_type) adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)] totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)] cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2) - if body.cash_given is not None and cash_due and body.cash_given + 0.004 < cash_due: - raise XeniaError("pos.payment_invalid", reason="cash_short") + _check_cash(body.cash_given, cash_due) order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user) - items_in = [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, - ) for line, adj in zip(lines, adjs)] - added = orders_api.add_items(order.id, AddItemsRequest(items=items_in), db, user) + added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user) item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()] paid, fiscal = [], None for method, idx in groups: @@ -239,16 +234,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us paid.append({"method": method, "amount": round(sum(totals[i] for i in idx), 2), "item_ids": res["paid_item_ids"]}) fiscal = res.get("fiscal") or fiscal - drawer = "none" - if cash_due > 0: - dev = current_device(request, db) - cfg = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db) - printer = db.get(Printer, cfg["receipt_printer_id"]) if cfg.get("receipt_printer_id") else None - if printer is not None and printer.is_active: - ok, _ = open_cash_drawer(printer, db, reason=f"order {order.id}") - drawer = "opened" if ok else "failed" - orders_api._audit(db, order.id, "DRAWER_OPENED" if ok else "DRAWER_FAILED", waiter_id=user.id, note=printer.name) - db.commit() + drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none" change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None return { @@ -256,3 +242,243 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us "cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []), } + + +# ── shared checks (3.3b, 3.3c) ───────────────────────────────────────────────── + +def _require_shift(db, user): + from models.shift import WaiterShift + from models.user import User + if not isinstance(user, User) or db.query(WaiterShift).filter( + WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() is None: + raise XeniaError("pos.shift_required") + + +def _check_discounts(request, db, user, lines): + from core.access.context import authorize + if any(line.discount_pct for line in lines): + authorize(request, db, user, "ordering.prices.modify", target="pos sale discount") + + +def _check_fiscal(db, products): + from services.fiscal_service import is_fiscal_enabled + if is_fiscal_enabled(db): + missing = sorted({p.name for p in products if p is not None and not p.fiscal_vat_group_id}) + if missing: + raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing)) + + +def _check_cash(cash_given, cash_due): + if cash_given is not None and cash_due and cash_given + 0.004 < cash_due: + raise XeniaError("pos.payment_invalid", reason="cash_short") + + +def _items_in(lines, adjs): + """Cart lines as POST /api/orders/{id}/items takes them (the waiter's selected_options + entries with the database's prices; a discount as the item's price_adjustment).""" + from schemas.order import OrderItemInput, SelectedOptionInput + 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, + ) for line, adj in zip(lines, adjs)] + + +def _open_drawer(request, db, user, order_id) -> str: + """Kick the cash drawer of the screen's receipt printer: opened | failed | none (no printer).""" + from core.access.context import current_device + from core.modules import device_config + from models.printer import Printer + from routers import orders as orders_api + from services.printer_service import open_cash_drawer + dev = current_device(request, db) + cfg = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db) + printer = db.get(Printer, cfg["receipt_printer_id"]) if cfg.get("receipt_printer_id") else None + if printer is None or not printer.is_active: + return "none" + ok, _ = open_cash_drawer(printer, db, reason=f"order {order_id}") + orders_api._audit(db, order_id, "DRAWER_OPENED" if ok else "DRAWER_FAILED", waiter_id=user.id, note=printer.name) + db.commit() + return "opened" if ok else "failed" + + +# ── tables (3.3c) ─────────────────────────────────────────────────────────────── + +ACTIVE = ("open", "partially_paid", "paid") +UNPAID = ("active", "ready") + + +def _table_name(t) -> str: + return t.label or f"T{t.number}" + + +def _item_total(i) -> float: + return (i.unit_price + (i.price_adjustment or 0.0)) * i.quantity + + +def _in_zones(db, user, table) -> bool: + """The waiter app's table rule (routers/tables.py list_tables): managers see every table, + staff the tables of their zones (a zone row without a group = every zone).""" + from models.user import WaiterZone + if holds(user, "core.dashboard.access"): + return True + zones = db.query(WaiterZone).filter(WaiterZone.waiter_id == user.id).all() + return any(z.group_id is None or z.group_id == table.group_id for z in zones) + + +def _order_for(db, user, order_id): + """The order, if this cashier may act on it (the waiter app's rule, orders._can_access_order).""" + from models.order import Order + from routers import orders as orders_api + order = db.get(Order, order_id) + if order is None: + raise XeniaError("order.not_found", order_id=order_id) + if not orders_api._can_access_order(order, user, db): + raise XeniaError("pos.table_not_yours", table=_table_name(order.table) if order.table else f"#{order_id}") + return order + + +@router.get("/tables") +def pos_tables(db: Session = Depends(get_db), user=Depends(require(ACCESS))): + """The tables this cashier may serve and, for each, its open order: totals (all, unpaid), + item count, who is on it (and whether it's the cashier), when it opened, ready items + (KDS done), flags and a reservation due soon.""" + from models.flag import TableFlagAssignment, TableFlagDef + from models.order import Order + from models.table import TableGroup + from models.user import User + from routers import tables as tables_api + visible = tables_api.list_tables(include_inactive=False, db=db, user=user) + ids = [t.id for t in visible] + orders = {} + if ids: + orders = {o.table_id: o for o in db.query(Order).filter(Order.table_id.in_(ids), Order.status.in_(ACTIVE)) + .options(selectinload(Order.items), selectinload(Order.waiters)).all()} + people_ids = {w.waiter_id for o in orders.values() for w in o.waiters} + people = {u.id: u.nickname or u.full_name or u.username + for u in db.query(User).filter(User.id.in_(people_ids)).all()} if people_ids else {} + flags: dict[int, list] = {} + if ids: + rows = (db.query(TableFlagAssignment, TableFlagDef).join(TableFlagDef, TableFlagDef.id == TableFlagAssignment.flag_id) + .filter(TableFlagAssignment.table_id.in_(ids), TableFlagDef.is_active.is_(True)) + .order_by(TableFlagDef.sort_order).all()) + for a, d in rows: + flags.setdefault(a.table_id, []).append({"id": d.id, "name": d.name, "emoji": d.emoji, "color": d.color, + "text_color": d.text_color}) + + def order_out(o): + live = [i for i in o.items if i.status in UNPAID or i.status == "paid"] + return { + "id": o.id, "status": o.status, "opened_at": _iso(o.opened_at), + "total": round(sum(_item_total(i) for i in live), 2), + "unpaid": round(sum(_item_total(i) for i in live if i.status in UNPAID), 2), + "items": len(live), + "ready": sum(1 for i in live if (i.kds_status or "pending") == "done"), + "people": [people[w.waiter_id] for w in o.waiters if w.waiter_id in people], + "mine": any(w.waiter_id == user.id for w in o.waiters), + } + + group_ids = [t.group_id for t in visible if t.group_id is not None] + groups = db.query(TableGroup).filter(TableGroup.id.in_(group_ids)).order_by(TableGroup.sort_order).all() if group_ids else [] + return { + "groups": [{"id": g.id, "name": g.name, "color": g.color} for g in groups], + "tables": [{ + "id": t.id, "name": _table_name(t), "number": t.number, "group_id": t.group_id, "seats": t.seat_count, + "flags": flags.get(t.id, []), + "reservation": ({"guest_name": t.upcoming_reservation.guest_name, "party_size": t.upcoming_reservation.party_size, + "reserved_for": _iso(t.upcoming_reservation.reserved_for)} if t.upcoming_reservation else None), + "order": order_out(orders[t.id]) if t.id in orders else None, + } for t in visible], + } + + +class TableItemsBody(BaseModel): + lines: List[dict] = Field(min_length=1, max_length=200) + + +@router.post("/tables/{table_id}/items", status_code=201) +def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: Session = Depends(get_db), + user=Depends(require(ACCESS))): + """Send cart lines to a table, exactly as the waiter app does: into its open order, or a + new one (the cashier is assigned to it). Kitchen tickets, KDS, price events, deals.""" + from models.order import Order + from models.table import Table + from routers import orders as orders_api + from schemas.order import AddItemsRequest, OrderCreate + _require_shift(db, user) + table = db.get(Table, table_id) + if table is None or not table.is_active: + raise XeniaError("pos.table_not_found", table_id=table_id) + order = db.query(Order).filter(Order.table_id == table_id, Order.status.in_(ACTIVE)).first() + if order is not None: + order = _order_for(db, user, order.id) + elif not _in_zones(db, user, table): + raise XeniaError("pos.table_not_yours", table=_table_name(table)) + lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)] + _check_discounts(request, db, user, lines) + existing = pos_cart.order_cart(order) if order is not None else None + priced = pos_cart.price_lines(db, lines, (order.order_type or "here") if order is not None else "here", existing) + adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)] + if order is None: + order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user) + added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user) + return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])} + + +class ItemsPayment(BaseModel): + method: Literal["cash", "card"] + item_ids: List[int] = Field(min_length=1, max_length=500) + + +class OrderPayBody(BaseModel): + payments: List[ItemsPayment] = Field(min_length=1, max_length=2) + cash_given: Optional[float] = Field(default=None, ge=0, le=100000) + + +@router.post("/orders/{order_id}/pay") +def pos_order_pay(order_id: int, body: OrderPayBody, request: Request, db: Session = Depends(get_db), + user=Depends(require(ACCESS))): + """Pay chosen items of an order (a table's) through POST /api/orders/{id}/pay, one call per + method: the cashier's shift, the fiscal receipt, auto-close. Cash opens the drawer. Items + someone else paid or cancelled meanwhile → pos.items_changed, nothing is paid.""" + from models.order import OrderItem + from routers import orders as orders_api + from schemas.order import PayItemsRequest + _require_shift(db, user) + order = _order_for(db, user, order_id) + wanted = [i for pay in body.payments for i in pay.item_ids] + if len(set(wanted)) != len(wanted) or len({pay.method for pay in body.payments}) != len(body.payments): + raise XeniaError("pos.payment_invalid", reason="lines") + items = {i.id: i for i in db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.id.in_(wanted)).all()} + if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()): + raise XeniaError("pos.items_changed") + _check_fiscal(db, {i.product for i in items.values()}) + amount = {pay.method: round(sum(_item_total(items[i]) for i in pay.item_ids), 2) for pay in body.payments} + cash_due = amount.get("cash", 0.0) + _check_cash(body.cash_given, cash_due) + + paid, fiscal, res = [], None, {} + for pay in body.payments: + res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=pay.item_ids, payment_method=pay.method), db, user) + paid.append({"method": pay.method, "amount": amount[pay.method], "item_ids": res["paid_item_ids"]}) + fiscal = res.get("fiscal") or fiscal + drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none" + change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None + return { + "order_id": order.id, "status": res.get("status"), "auto_closed": bool(res.get("auto_closed")), + "total": round(sum(amount.values()), 2), "payments": paid, "cash_given": body.cash_given, "change": change, + "drawer": drawer, "fiscal": fiscal, + } + + +@router.post("/orders/{order_id}/close") +def pos_order_close(order_id: int, db: Session = Depends(get_db), user=Depends(require(ACCESS))): + """Close an order once everything on it is paid (or cancelled). Unlike the manager's close, + the counter never writes unpaid items off: pos.order_unpaid {count}.""" + from models.order import OrderItem + from routers import orders as orders_api + order = _order_for(db, user, order_id) + unpaid = db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.status.in_(UNPAID)).count() + if unpaid: + raise XeniaError("pos.order_unpaid", count=unpaid) + return orders_api.close_order(order.id, db, user) diff --git a/local_backend/services/pos_cart.py b/local_backend/services/pos_cart.py index 46642f8..55150e5 100644 --- a/local_backend/services/pos_cart.py +++ b/local_backend/services/pos_cart.py @@ -197,6 +197,21 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No return out +def order_cart(order) -> list[dict]: + """An order's active items as the pricing engine's cart context (what POST + /api/orders/{id}/items starts from, and what a table's quote starts from, 3.3c).""" + return [ + { + "product_id": i.product_id, + "category_id": i.product.primary_category_id if i.product else None, + "category_ids": i.product.category_ids if i.product else [], + "quantity": i.quantity, + "unit_price": i.unit_price, + } + for i in order.items if i.status == "active" + ] + + def discount_adjustment(unit_price: float, pct) -> float: """A line's discount (percent of its unit price) as the order item's price_adjustment (negative, rounded to cents).""" diff --git a/local_backend/tests/test_pos_tables.py b/local_backend/tests/test_pos_tables.py new file mode 100644 index 0000000..c6b3f0a --- /dev/null +++ b/local_backend/tests/test_pos_tables.py @@ -0,0 +1,199 @@ +"""Counter POS: tables at the counter (plan step 3.3c). The counter works on tables with the +waiter app's rules and functions; these tests prove both sides see and change the same order.""" +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) + + +@pytest.fixture +def floor(db, till): + """Two zones: Terrace (T1, T2) for the cashier and Inside (T3) that isn't theirs.""" + from models.table import Table, TableGroup + from models.user import WaiterZone + terrace, inside = TableGroup(name="Terrace", sort_order=1), TableGroup(name="Inside", sort_order=2) + db.add_all([terrace, inside]) + db.flush() + t1, t2 = Table(number=1, group_id=terrace.id, seat_count=4), Table(number=2, label="Corner", group_id=terrace.id) + t3 = Table(number=3, group_id=inside.id) + db.add_all([t1, t2, t3]) + db.add(WaiterZone(waiter_id=till["cashier"].id, group_id=terrace.id)) + db.commit() + return {"terrace": terrace, "inside": inside, "t1": t1, "t2": t2, "t3": t3} + + +@pytest.fixture +def phone(db, make_user, login, floor, on_shift): + """A waiter on their phone, working the terrace too, with their own shift.""" + from models.shift import WaiterShift + from models.user import WaiterZone + maria = make_user(role="waiter", nickname="Maria") + db.add(WaiterZone(waiter_id=maria.id, group_id=floor["terrace"].id)) + db.add(WaiterShift(waiter_id=maria.id, business_day_id=on_shift.business_day_id)) + db.commit() + return {"user": maria, "h": login(maria, "waiter")} + + +@pytest.fixture +def events(monkeypatch): + """Order events broadcast by routers/orders.py (what phones, the KDS and the counter hear).""" + import routers.orders as orders + got = [] + real = orders.broadcast_sync + monkeypatch.setattr(orders, "broadcast_sync", lambda kind, data, **kw: (got.append((kind, data)), real(kind, data, **kw))) + return got + + +def tables(client, till): + r = client.get("/api/pos/tables", headers=till["h"]) + assert r.status_code == 200, r.text + return {t["name"]: t for t in r.json()["tables"]}, r.json()["groups"] + + +def send(client, till, table, lines): + return client.post(f"/api/pos/tables/{table.id}/items", headers=till["h"], json={"lines": lines}) + + +def test_tables_follow_the_cashiers_zones(client, db, till, floor, phone, menu): + from models.flag import TableFlagAssignment, TableFlagDef + flag = TableFlagDef(name="VIP", emoji="⭐", color="#aa0000") + db.add(flag) + db.flush() + db.add(TableFlagAssignment(table_id=floor["t2"].id, flag_id=flag.id)) + db.commit() + by_name, groups = tables(client, till) + assert set(by_name) == {"T1", "Corner"} and [g["name"] for g in groups] == ["Terrace"] + assert by_name["T1"]["order"] is None and by_name["T1"]["seats"] == 4 + assert by_name["Corner"]["flags"] == [{"id": flag.id, "name": "VIP", "emoji": "⭐", "color": "#aa0000", "text_color": None}] + # the waiter opens T1 on the phone; the counter sees it with totals and who is on it + o = client.post("/api/orders/", headers=phone["h"], json={"table_id": floor["t1"].id}).json() + client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"items": [{"product_id": menu["coffee"].id, "quantity": 2}]}) + t1 = tables(client, till)[0]["T1"]["order"] + assert t1["id"] == o["id"] and t1["total"] == 6.0 and t1["unpaid"] == 6.0 and t1["items"] == 1 + assert t1["people"] == ["Maria"] and t1["mine"] is False + + +def test_counter_and_phone_share_a_table(client, db, till, floor, phone, menu, events): + """The done-when of 3.3c at the API level: both sides add to one order and see the other's + changes; every change is broadcast.""" + m = menu + r = send(client, till, floor["t1"], [{"product_id": m["coffee"].id}]) + assert r.status_code == 201, r.text + oid = r.json()["order_id"] + assert ("order_updated", {"order_id": oid, "table_id": floor["t1"].id, "status": "open", "action": "opened"}) in events + # the phone sees the counter's order and adds to it + seen = client.get(f"/api/orders/{oid}", headers=phone["h"]).json() + assert [i["product_name"] for i in seen["items"]] == ["Freddo"] + assert client.post(f"/api/orders/{oid}/items", headers=phone["h"], + json={"items": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200 + # the counter adds a burger to the same order (not a second one) + assert send(client, till, floor["t1"], [burger_line(m)]).json()["order_id"] == oid + t1 = tables(client, till)[0]["T1"]["order"] + assert t1["total"] == 16.0 and t1["mine"] is True and t1["people"] == [till["cashier"].full_name] + detail = client.get(f"/api/orders/{oid}", headers=till["h"]).json() + assert sorted(i["product_name"] for i in detail["items"]) == ["Burger", "Freddo", "Freddo"] + + +def test_quote_for_a_table_counts_its_items(client, db, till, floor, menu, on_shift): + """The table's items already on the order count for cart conditions, as in add_items.""" + import json as _json + from models.order import OrderItem + from models.pricing import PriceModifier, PriceModifierCondition + mod = PriceModifier(name="2nd coffee", scope="item", item_id=menu["coffee"].id, action_type="add_percent", action_value=-10, is_active=1) + db.add(mod) + db.flush() + db.add(PriceModifierCondition(modifier_id=mod.id, condition_type="min_item_quantity", params=_json.dumps({"min": 2}))) + db.commit() + line = [{"product_id": menu["coffee"].id}] + oid = send(client, till, floor["t1"], line).json()["order_id"] + assert client.post("/api/pos/quote", headers=till["h"], json={"lines": line}).json()["total"] == 3.0 + q = client.post("/api/pos/quote", headers=till["h"], json={"order_id": oid, "lines": line}).json() + assert q["order_type"] == "here" and q["total"] == 2.7 + send(client, till, floor["t1"], line) + prices = [i.unit_price for i in db.query(OrderItem).filter(OrderItem.order_id == oid).order_by(OrderItem.id)] + assert prices == [3.0, 2.7] # the order charged what the quote said + + +def test_tables_outside_the_zones_are_refused(client, db, till, floor, menu, on_shift, make_user, login): + from models.shift import WaiterShift + from models.user import WaiterZone + assert err(send(client, till, floor["t3"], [{"product_id": menu["coffee"].id}])) == "pos.table_not_yours" + # an order inside, opened by someone else, can't be quoted, paid or closed from here + nikos = make_user(role="waiter") + db.add(WaiterZone(waiter_id=nikos.id, group_id=floor["inside"].id)) + db.add(WaiterShift(waiter_id=nikos.id, business_day_id=on_shift.business_day_id)) + db.commit() + h = login(nikos, "waiter") + o = client.post("/api/orders/", headers=h, json={"table_id": floor["t3"].id}).json() + client.post(f"/api/orders/{o['id']}/items", headers=h, json={"items": [{"product_id": menu["coffee"].id, "quantity": 1}]}) + item = client.get(f"/api/orders/{o['id']}", headers=h).json()["items"][0]["id"] + assert err(client.post("/api/pos/quote", headers=till["h"], json={"order_id": o["id"], "lines": []})) == "pos.table_not_yours" + assert err(client.post(f"/api/pos/orders/{o['id']}/pay", headers=till["h"], + json={"payments": [{"method": "cash", "item_ids": [item]}]})) == "pos.table_not_yours" + assert err(client.post(f"/api/pos/orders/{o['id']}/close", headers=till["h"])) == "pos.table_not_yours" + assert err(client.post("/api/pos/tables/999999/items", headers=till["h"], json={"lines": [{"product_id": menu["coffee"].id}]})) == "pos.table_not_found" + + +def test_sending_needs_a_shift_and_checks_lines_first(client, db, till, floor, menu): + from models.order import Order + assert err(send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}])) == "pos.shift_required" + assert db.query(Order).count() == 0 + + +def test_pay_some_add_more_pay_the_rest_close(client, db, till, floor, menu, on_shift, drawer_printer, events): + from models.order import Order + m = menu + oid = send(client, till, floor["t1"], [{"product_id": m["coffee"].id, "quantity": 2}, burger_line(m)]).json()["order_id"] + items = {i["product_name"]: i["id"] for i in client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"]} + # pay the coffees in cash: change, drawer + r = client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"], + json={"payments": [{"method": "cash", "item_ids": [items["Freddo"]]}], "cash_given": 10}) + assert r.status_code == 200, r.text + assert (r.json()["total"], r.json()["change"], r.json()["drawer"], r.json()["status"]) == (6.0, 4.0, "opened", "partially_paid") + assert any(k == "order_paid" and d["order_id"] == oid for k, d in events) + # paying them again (someone else did) → nothing happens + assert err(client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"], + json={"payments": [{"method": "card", "item_ids": [items["Freddo"], items["Burger"]]}]})) == "pos.items_changed" + # can't close with the burger unpaid + r = client.post(f"/api/pos/orders/{oid}/close", headers=till["h"]) + assert err(r) == "pos.order_unpaid" and r.json()["error"]["params"] == {"count": 1} + # add more, then pay the rest split: burger by card, the new coffee in cash + send(client, till, floor["t1"], [{"product_id": m["coffee"].id}]) + rest = [i for i in client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"] if i["status"] == "active"] + burger = next(i["id"] for i in rest if i["product_name"] == "Burger") + coffee = next(i["id"] for i in rest if i["product_name"] == "Freddo") + r = client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"], + json={"payments": [{"method": "card", "item_ids": [burger]}, {"method": "cash", "item_ids": [coffee]}]}) + assert r.status_code == 200 and r.json()["status"] == "paid" and r.json()["change"] is None + assert [(p["method"], p["amount"]) for p in r.json()["payments"]] == [("card", 10.0), ("cash", 3.0)] + shift = client.get("/api/shifts/my", headers=till["h"]).json() + assert (shift["cash_sales"], shift["card_sales"]) == (9.0, 10.0) + assert client.post(f"/api/pos/orders/{oid}/close", headers=till["h"]).json() == {"status": "closed"} + assert db.get(Order, oid).status == "closed" and tables(client, till)[0]["T1"]["order"] is None + + +def test_pay_checks(client, till, floor, menu, on_shift): + oid = send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}]).json()["order_id"] + item = client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"][0]["id"] + pay = lambda body: client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"], json=body) # noqa: E731 + assert err(pay({"payments": [{"method": "cash", "item_ids": [item]}], "cash_given": 1})) == "pos.payment_invalid" + assert err(pay({"payments": [{"method": "cash", "item_ids": [item]}, {"method": "card", "item_ids": [item]}]})) == "pos.payment_invalid" + assert err(pay({"payments": [{"method": "cash", "item_ids": [999999]}]})) == "pos.items_changed" + + +def test_cancel_from_the_counter_needs_a_manager_and_is_broadcast(client, db, till, floor, menu, on_shift, pair, make_user, events): + from models.order import OrderItem + oid = send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}, {"product_id": menu["coffee"].id, "notes": "iced"}]).json()["order_id"] + ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == oid).order_by(OrderItem.id)] + # a waiter-role cashier can't cancel sent items alone: the manager-approval dialog + r = client.post(f"/api/orders/{oid}/cancel-items", headers=till["h"], json={"item_ids": [ids[0]]}) + assert err(r) == "access.override_possible" + # a manager at the counter can; everyone hears about it + token, _ = pair("pos_counter", "Till 3") + boss = make_user(role="owner") + h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"} + r = client.post(f"/api/orders/{oid}/cancel-items", headers=h, json={"item_ids": [ids[0]]}) + assert r.status_code == 200 and r.json()["cancelled"] == [ids[0]] + assert ("order_updated", {"order_id": oid, "table_id": floor["t1"].id, "status": "open", + "action": "items_cancelled", "item_ids": [ids[0]]}) in events + assert tables(client, till)[0]["T1"]["order"]["total"] == 3.0 diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index c9e26d6..45e2920 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -82,6 +82,10 @@ "line_invalid": "Η γραμμή {{line}} του καλαθιού δεν μπορεί να πουληθεί όπως επιλέχθηκε ({{reason}}).", "shift_required": "Ξεκινήστε τη βάρδιά σας πριν πουλήσετε.", "payment_invalid": "Αυτή η πληρωμή δεν βγαίνει ({{reason}}).", - "fiscal_vat_missing": "Οι φορολογικές αποδείξεις είναι ενεργές, αλλά αυτά τα προϊόντα δεν έχουν ομάδα ΦΠΑ: {{names}}." + "fiscal_vat_missing": "Οι φορολογικές αποδείξεις είναι ενεργές, αλλά αυτά τα προϊόντα δεν έχουν ομάδα ΦΠΑ: {{names}}.", + "table_not_found": "Δεν βρέθηκε το τραπέζι {{table_id}}.", + "table_not_yours": "Το {{table}} δεν είναι στις ζώνες σας. Ένας διαχειριστής μπορεί να προσθέσει τη ζώνη στον λογαριασμό σας.", + "items_changed": "Κάποια από αυτά πληρώθηκαν ή ακυρώθηκαν στο μεταξύ. Ελέγξτε την παραγγελία και δοκιμάστε ξανά.", + "order_unpaid": "Απλήρωτα είδη: {{count}}. Πάρτε την πληρωμή ή ακυρώστε τα πρώτα." } } diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index f494ca9..24d38c3 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -237,6 +237,59 @@ "again": "Τα ίδια ξανά", "toast": "Πληρώθηκε", "toastChange": "Πληρώθηκε. Ρέστα: {{change}}" + }, + "mode": { + "label": "Λειτουργία ταμείου", + "sale": "Πώληση", + "tables": "Τραπέζια" + }, + "tables": { + "none": "Δεν έχετε τραπέζια", + "noneBody": "Βλέπετε τα τραπέζια των ζωνών σας, όπως στην εφαρμογή σερβιτόρου. Ένας διαχειριστής μπορεί να προσθέσει ζώνες στον λογαριασμό σας.", + "allZones": "Όλες οι ζώνες", + "state": { + "free": "Ελεύθερο", + "mine": "Δικό σας", + "open": "Πιασμένο", + "paid": "Πληρωμένο, ανοιχτό" + }, + "ofTotal": "από {{total}}", + "since": "από τις {{time}}", + "ready_one": "{{count}} έτοιμο", + "ready_other": "{{count}} έτοιμα", + "reserved": "Κράτηση {{time}} · {{name}} ({{count}})", + "noZone": "Χωρίς ζώνη" + }, + "table": { + "back": "Πίσω στα τραπέζια", + "closedElsewhere": "Το {{table}} έκλεισε από άλλη συσκευή.", + "sent": "Στάλθηκε στο {{table}}", + "closed": "Το {{table}} έκλεισε", + "cancelled_one": "Ακυρώθηκε {{count}} είδος", + "cancelled_other": "Ακυρώθηκαν {{count}} είδη", + "onOrder": "Στην παραγγελία", + "new": "Νέα, δεν έχουν σταλεί", + "empty": "Δεν υπάρχει τίποτα ακόμη σε αυτό το τραπέζι", + "emptyBody": "Πατήστε προϊόντα για να τα προσθέσετε και μετά στείλτε τα στο τραπέζι.", + "newTotal": "Νέα είδη", + "send": "Αποστολή στο {{table}}", + "due": "Υπόλοιπο", + "paySelected": "Πληρωμή επιλεγμένων {{amount}}", + "payAll": "Πληρωμή όλων {{amount}}", + "cancel": "Ακύρωση επιλεγμένων", + "selectAll": "Επιλογή όλων", + "selectNone": "Καμία επιλογή", + "close": "Κλείσιμο {{table}}", + "cancelTitle_one": "Ακύρωση {{count}} είδους;", + "cancelTitle_other": "Ακύρωση {{count}} ειδών;", + "cancelBody": "Φεύγουν από τον λογαριασμό και η κουζίνα παίρνει δελτίο ακύρωσης. Αν δεν μπορείτε να ακυρώσετε σταλμένα είδη, το εγκρίνει ένας διαχειριστής με το PIN του.", + "keep": "Να μείνουν", + "cancelConfirm": "Ακύρωση ειδών", + "paidBy": { + "cash": "πληρώθηκε · μετρητά", + "card": "πληρώθηκε · κάρτα" + }, + "readyItem": "έτοιμο" } } } diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 776f94a..180d224 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -82,6 +82,10 @@ "line_invalid": "Cart line {{line}} can't be sold as chosen ({{reason}}).", "shift_required": "Start your shift before selling.", "payment_invalid": "This payment doesn't add up ({{reason}}).", - "fiscal_vat_missing": "Fiscal receipts are on, but these products have no VAT group: {{names}}." + "fiscal_vat_missing": "Fiscal receipts are on, but these products have no VAT group: {{names}}.", + "table_not_found": "Table {{table_id}} not found.", + "table_not_yours": "{{table}} isn't in your zones. A manager can add the zone to your account.", + "items_changed": "Some of these items were paid or cancelled in the meantime. Check the order and try again.", + "order_unpaid": "Items still unpaid: {{count}}. Take the payment or cancel them first." } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index 03231c1..62e2752 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -237,6 +237,59 @@ "again": "Same again", "toast": "Paid", "toastChange": "Paid. Change: {{change}}" + }, + "mode": { + "label": "Counter mode", + "sale": "Sale", + "tables": "Tables" + }, + "tables": { + "none": "No tables for you", + "noneBody": "You see the tables of your zones, as in the waiter app. A manager can add zones to your account.", + "allZones": "All zones", + "state": { + "free": "Free", + "mine": "Yours", + "open": "Taken", + "paid": "Paid, not closed" + }, + "ofTotal": "of {{total}}", + "since": "since {{time}}", + "ready_one": "{{count}} ready", + "ready_other": "{{count}} ready", + "reserved": "Reserved {{time}} · {{name}} ({{count}})", + "noZone": "No zone" + }, + "table": { + "back": "Back to the tables", + "closedElsewhere": "{{table}} was closed on another device.", + "sent": "Sent to {{table}}", + "closed": "{{table}} is closed", + "cancelled_one": "{{count}} item cancelled", + "cancelled_other": "{{count}} items cancelled", + "onOrder": "On the order", + "new": "New, not sent yet", + "empty": "Nothing on this table yet", + "emptyBody": "Tap products to add them, then send them to the table.", + "newTotal": "New items", + "send": "Send to {{table}}", + "due": "Still due", + "paySelected": "Pay selected {{amount}}", + "payAll": "Pay everything {{amount}}", + "cancel": "Cancel selected", + "selectAll": "Select all", + "selectNone": "Select none", + "close": "Close {{table}}", + "cancelTitle_one": "Cancel {{count}} item?", + "cancelTitle_other": "Cancel {{count}} items?", + "cancelBody": "They come off the bill and the kitchen gets a cancellation ticket. If you can't cancel sent items, a manager approves it with their PIN.", + "keep": "Keep them", + "cancelConfirm": "Cancel items", + "paidBy": { + "cash": "paid · cash", + "card": "paid · card" + }, + "readyItem": "ready" } } } diff --git a/terminal/src/apps/pos/CartLine.jsx b/terminal/src/apps/pos/CartLine.jsx new file mode 100644 index 0000000..a485d6c --- /dev/null +++ b/terminal/src/apps/pos/CartLine.jsx @@ -0,0 +1,40 @@ +// One cart line at the counter (plan steps 3.3a–c): name, chosen options, quantity buttons, +// a per-line discount, and the backend's price for it (POST /api/pos/quote). +import { Minus, Plus } from 'lucide-react' +import { useFormat, useTranslation } from '@xenia/i18n' +import { IconButton, Select } from '@xenia/ui' +import { DISCOUNTS, unitOf } from './logic/cart' + +export default function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) { + const { t } = useTranslation('terminal') + const { formatMoney } = useFormat() + const unit = product ? unitOf(product) : null + const step = unit ? unit.step : 1 + const qtyText = unit ? `${Number(line.quantity).toFixed(step < 1 ? 1 : 0)} ${unit.label}` : `${line.quantity}×` + return ( +
+
+ {product?.name ?? priced?.name} + {priced ? formatMoney(priced.total) : '…'} +
+ {priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && ( +
+ {priced.entries.map((e, i) => + {e.name}{e.price ? ` (${formatMoney(e.price)})` : ''})} + {priced.removed.map(n => − {n})} + {priced.notes && “{priced.notes}”} +
+ )} +
+ onQty(line.quantity - step)}> + {qtyText} + onQty(line.quantity + step)}> + {priced && line.quantity !== 1 && {t('pos.each', { price: formatMoney(priced.unit_price) })}} + + setQuery(e.target.value)} placeholder={t('pos.search')} className="pl-10" data-testid="pos-search" aria-label={t('pos.search')} /> -
- {query && setQuery('')}>} + - {/* cart */} - - - {paying && quote.quote && ( - byId.get(l.product_id)?.name ?? '')} - onClose={() => setPaying(false)} - onPaid={result => { - setPaying(false) - setLastSale({ lines: cart, orderType, result }) - setCart([]) - toast.success(result.change != null ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast')) - }} /> + {picking ? ( +
+ { setTableId(id); setTableCart([]) }} /> +
+ ) : ( + <> +
+
+
+ + setQuery(e.target.value)} placeholder={t('pos.search')} className="pl-10" data-testid="pos-search" aria-label={t('pos.search')} /> +
+ {query && setQuery('')}>} +
+
+ {shown.length === 0 ? ( + + ) : ( +
+ {shown.map(p => tap(p)} onInfo={() => setDialog(p)} />)} +
+ )} +
+
+ {atTable + ? + : } + )} {dialog && ( - setDialog(null)} + setDialog(null)} onAdd={line => setCart(c => addLine(c, line))} /> )}
) } -function CategoryButton({ active, colour, onClick, children, testId }) { +function ModeButton({ active, onClick, icon: Icon, badge, children, testId }) { + return ( + + ) +} + +function NavButton({ active, colour, onClick, children, testId, count }) { return ( ) } @@ -168,56 +171,3 @@ function ProductCard({ product, onTap, onInfo }) { ) } - -function SaleDone({ sale, onAgain }) { - const { t } = useTranslation('terminal') - const { formatMoney } = useFormat() - const r = sale.result - return ( -
-
{t('pos.done.paid', { total: formatMoney(r.total) })}
- {r.change != null &&
{t('pos.pay.change', { amount: formatMoney(r.change) })}
} -
- {r.payments.map(p => t(`pos.done.${p.method}`, { amount: formatMoney(p.amount) })).join(' · ')} - {r.drawer === 'opened' && ` · ${t('pos.done.drawerOpened')}`} - {r.drawer === 'failed' && · {t('pos.done.drawerFailed')}} - {r.fiscal === 'pending' && ` · ${t('pos.done.fiscal')}`} -
- -
- ) -} - -function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) { - const { t } = useTranslation('terminal') - const { formatMoney } = useFormat() - const unit = product ? unitOf(product) : null - const step = unit ? unit.step : 1 - const qtyText = unit ? `${Number(line.quantity).toFixed(step < 1 ? 1 : 0)} ${unit.label}` : `${line.quantity}×` - return ( -
-
- {product?.name ?? priced?.name} - {priced ? formatMoney(priced.total) : '…'} -
- {priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && ( -
- {priced.entries.map((e, i) => + {e.name}{e.price ? ` (${formatMoney(e.price)})` : ''})} - {priced.removed.map(n => − {n})} - {priced.notes && “{priced.notes}”} -
- )} -
- onQty(line.quantity - step)}> - {qtyText} - onQty(line.quantity + step)}> - {priced && line.quantity !== 1 && {t('pos.each', { price: formatMoney(priced.unit_price) })}} - -