From 72e175ab73fb5f87bfb41454a00faee6e6c4b170 Mon Sep 17 00:00:00 2001 From: bonamin Date: Mon, 23 Nov 2026 08:26:46 +0200 Subject: [PATCH] feat(backend,waiter,terminal,manager): +1 on a sent line and changing a line's quantity Owner 2026-11-23 (plan 6F.5). Product flag one_more_enabled (off by default; product editor). POST /api/orders/{id}/items/{item}/again: a new line like the old one (choices, removed, note, course), priced now, sent to the kitchen like any new line. Waiter app and the counter's table panel: +1 beside such lines; the first tap arms it, more taps count up, 'Send +N' sends, 4 s idle disarms (no stray sends). POST /api/orders/{id}/items/{item}/quantity: venue setting orders.quantity_change (off | add_only | add_and_remove, default off), key ordering.items.change_quantity (owner, store manager; Alembic 0049 grants it); up only changes the line, down cuts a cancelled part ('quantity lowered', split_from_id) and prints a cancellation only when asked (the dialog presets yes while the kitchen hasn't finished). Waiter: 'Change quantity' in a line's actions (now -> new, -/+). cut_part() now shared with split. GET /api/orders/{id} items carry the product's one_more_enabled / unit_type, deal ids, split_from_id, cancel_reason. Co-Authored-By: Claude Opus 5.5 --- local_backend/core/errors.py | 6 + .../migrations/versions/0049_one_more.py | 30 ++++ local_backend/models/product.py | 2 + local_backend/modules/ordering/manifest.py | 2 + local_backend/routers/orders.py | 157 +++++++++++++++--- local_backend/routers/pos.py | 1 + local_backend/schemas/order.py | 2 + local_backend/schemas/product.py | 3 + local_backend/tests/test_one_more.py | 123 ++++++++++++++ .../Settings/sections/OperationSettings.jsx | 18 ++ .../src/pages/products/editor/InfoTabs.jsx | 1 + .../src/pages/products/editor/formLogic.js | 2 + manager_dashboard/tests/products.test.mjs | 8 + packages/i18n/locales/el/errors.json | 8 +- packages/i18n/locales/el/manager.json | 21 ++- packages/i18n/locales/el/modules.json | 3 + packages/i18n/locales/el/terminal.json | 5 + packages/i18n/locales/el/waiter.json | 24 ++- packages/i18n/locales/en/errors.json | 8 +- packages/i18n/locales/en/manager.json | 21 ++- packages/i18n/locales/en/modules.json | 3 + packages/i18n/locales/en/terminal.json | 5 + packages/i18n/locales/en/waiter.json | 24 ++- terminal/src/apps/pos/OneMore.jsx | 34 ++++ terminal/src/apps/pos/TablePanel.jsx | 14 +- terminal/src/apps/pos/logic/tables.js | 2 + tests/e2e/manager.mjs | 6 + tests/e2e/waiter.mjs | 69 ++++++++ waiter_pwa/src/components/OneMore.jsx | 45 +++++ waiter_pwa/src/components/OrderSummary.jsx | 11 +- waiter_pwa/src/components/QuantityModal.jsx | 57 +++++++ waiter_pwa/src/hooks/useQuantityMode.js | 14 ++ waiter_pwa/src/logic/lines.js | 31 ++++ waiter_pwa/src/pages/TableDetailPage.jsx | 58 ++++++- waiter_pwa/tests/lines.test.mjs | 30 ++++ 35 files changed, 813 insertions(+), 35 deletions(-) create mode 100644 local_backend/migrations/versions/0049_one_more.py create mode 100644 local_backend/tests/test_one_more.py create mode 100644 terminal/src/apps/pos/OneMore.jsx create mode 100644 waiter_pwa/src/components/OneMore.jsx create mode 100644 waiter_pwa/src/components/QuantityModal.jsx create mode 100644 waiter_pwa/src/hooks/useQuantityMode.js create mode 100644 waiter_pwa/src/logic/lines.js create mode 100644 waiter_pwa/tests/lines.test.mjs diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index c03aa2f..afe91ca 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -222,6 +222,12 @@ CODES: dict[str, tuple[int, str]] = { "order.item_paid": (400, "This item is already paid."), "order.item_not_active": (400, "Only items still on the order can be changed."), "order.price_change_off": (403, "Changing prices by hand is turned off for this venue."), + "order.one_more_off": (400, "\"One more\" isn't turned on for this product."), + "order.one_more_line": (400, "This line can't be ordered again with one tap."), + "order.quantity_change_off": (403, "Changing quantities is turned off for this venue."), + "order.quantity_remove_off": (403, "Quantities can only go up at this venue."), + "order.quantity_invalid": (400, "Choose a whole number from 1 to {max}."), + "order.quantity_line": (400, "This line's quantity can't be changed here."), "order.price_change_sent_off": (403, "Prices can only be changed before the items are sent."), "order.price_reason_required": (400, "Say why the price changes."), "order.nothing_paid": (404, "There are no paid items to undo."), diff --git a/local_backend/migrations/versions/0049_one_more.py b/local_backend/migrations/versions/0049_one_more.py new file mode 100644 index 0000000..adc6677 --- /dev/null +++ b/local_backend/migrations/versions/0049_one_more.py @@ -0,0 +1,30 @@ +"""One more and quantity changes (owner 2026-11-23, plan 6F.5). + +- products.one_more_enabled (off: the owner turns it on per product). +- The key ordering.items.change_quantity for owners and store managers (the venue's setting + orders.quantity_change starts 'off'). + +Revision ID: 0049_one_more +Revises: 0048_order_moves +Create Date: 2026-11-23 18:00:00 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0049_one_more' +down_revision = '0048_order_moves' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table('products') as b: + b.add_column(sa.Column('one_more_enabled', sa.Boolean(), nullable=False, server_default='0')) + op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) " + "select id, 'ordering.items.change_quantity' from users where role in ('owner', 'store_manager')")) + + +def downgrade() -> None: + op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.items.change_quantity'")) + with op.batch_alter_table('products') as b: + b.drop_column('one_more_enabled') diff --git a/local_backend/models/product.py b/local_backend/models/product.py index 939d5be..0f97e8a 100644 --- a/local_backend/models/product.py +++ b/local_backend/models/product.py @@ -82,6 +82,8 @@ class Product(Base): # Quick Add: allow adding 1 unit directly from product list without opening config modal quick_add_enabled = Column(Boolean, default=True, nullable=False) + # "One more" (6F.5): a sent line of this product shows +1 (re-order the same, printed as new) + one_more_enabled = Column(Boolean, default=False, nullable=False, server_default="0") # Service item: non-inventoried table-service items (cutlery, glasses, etc.) is_service_item = Column(Boolean, default=False, nullable=False) diff --git a/local_backend/modules/ordering/manifest.py b/local_backend/modules/ordering/manifest.py index d234467..ff0d724 100644 --- a/local_backend/modules/ordering/manifest.py +++ b/local_backend/modules/ordering/manifest.py @@ -13,6 +13,7 @@ MODULE = Module( Perm('ordering.orders.cancel', 'Cancel items already sent', roles=('owner', 'store_manager'), overridable=True), Perm('ordering.prices.modify', "Change an item's price before it is sent", roles=('owner',), overridable=True), Perm('ordering.prices.modify_sent', "Change the price of an item already sent or served", roles=('owner',), overridable=True), + Perm('ordering.items.change_quantity', "Change a sent line's quantity (no new ticket)", roles=('owner', 'store_manager'), overridable=True), Perm('ordering.prices.view_changes', 'See the prices changed by hand (who, when, why)', roles=('owner', 'store_manager')), Perm('ordering.refunds', 'Refund payments from other shifts', roles=('owner', 'store_manager'), overridable=True), Perm('ordering.payments.revert', 'Turn paid items back to unpaid', roles=('owner', 'store_manager'), overridable=True), @@ -24,6 +25,7 @@ MODULE = Module( 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.quantity_change', 'off', "Changing a sent line's quantity without sending it again (6F.5): 'off' | 'add_only' | 'add_and_remove' (lowering cancels the difference; also needs ordering.orders.cancel). Who may: ordering.items.change_quantity.", type='enum', choices=('off', 'add_only', 'add_and_remove')), SettingDef('orders.price_change', 'anytime', "Changing a line's price by hand (6F.3): 'off' | 'before_sending' (only in the cart) | 'anytime' (also a sent or served line). Who may: the keys ordering.prices.modify / modify_sent.", type='enum', choices=('off', 'before_sending', 'anytime')), SettingDef('orders.price_change_reason', 'false', "A price changed by hand needs a reason: 'true' | 'false' (6F.3).", type='bool'), SettingDef('orders.price_change_reasons', '[]', 'JSON array of quick reasons offered when a price is changed by hand (6F.3); [] = the built-in ones.', type='json'), diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index a2b601d..f246761 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -343,7 +343,8 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends "id": i.id, "order_id": i.order_id, "product_id": i.product_id, - "product": {"id": i.product.id, "name": i.product.name} if i.product else None, + "product": {"id": i.product.id, "name": i.product.name, "unit_type": i.product.unit_type or "piece", + "one_more_enabled": bool(i.product.one_more_enabled)} if i.product else None, # 6F.5: +1 "product_name": i.product_name, "category_id": i.category_id, "category_name": i.category_name, "added_by": i.added_by, "added_by_name": name_map.get(i.added_by), @@ -366,6 +367,9 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends "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, + "deal_id": i.deal_id, "linked_item_id": i.linked_item_id, + "split_from_id": i.split_from_id, # 6F.4: the line it was cut from + "cancel_reason": i.cancel_reason, } def fmt_log(l): @@ -1618,26 +1622,7 @@ def split_item( # Reduce original item item.quantity -= body.quantity - - # Create split-off item - new_item = OrderItem( - source=item.source, - order_id=order_id, - product_id=item.product_id, - added_by=item.added_by, - quantity=body.quantity, - unit_price=item.unit_price, - selected_options=item.selected_options, - removed_ingredients=item.removed_ingredients, - notes=item.notes, - status="active", - printed=item.printed, - split_from_id=item.id, # 6F.4: the moves the line had come with this part - # the rest of what the line was (kitchen, course, price, names, cost) goes with the part - kds_status=item.kds_status, course_id=item.course_id, price_adjustment=item.price_adjustment, - unit_cost=item.unit_cost, product_name=item.product_name, category_id=item.category_id, - category_name=item.category_name, - ) + new_item = cut_part(item, body.quantity) db.add(new_item) db.commit() db.refresh(item) @@ -1645,6 +1630,136 @@ def split_item( return [item, new_item] +def cut_part(item, quantity, **changes): + """A new line cut from `item` (a split, a lowered quantity, 6F.4/6F.5): everything the line was + (product, price and its change, choices, note, kitchen state, course, cost, names, source) for + `quantity`, linked by split_from_id so its moves follow it. Not added to the session.""" + fields = dict( + source=item.source, order_id=item.order_id, product_id=item.product_id, added_by=item.added_by, + quantity=quantity, unit_price=item.unit_price, selected_options=item.selected_options, + removed_ingredients=item.removed_ingredients, notes=item.notes, status="active", printed=item.printed, + split_from_id=item.id, kds_status=item.kds_status, course_id=item.course_id, + price_adjustment=item.price_adjustment, unit_cost=item.unit_cost, product_name=item.product_name, + category_id=item.category_id, category_name=item.category_name, + ) # added_at = now: the moment it was cut (services/moves.py reads it) + fields.update(changes) + return OrderItem(**fields) + + +# ─── One more of a line, and a line's quantity (6F.5) ──────────────────────── + +class AgainRequest(BaseModel): + quantity: int = Field(default=1, ge=1, le=50) + + +@router.post("/{order_id}/items/{item_id}/again", response_model=AddItemsResponse) +def order_again(order_id: int, item_id: int, body: AgainRequest, request: Request, db: Session = Depends(get_db), + user: User = Depends(get_current_user)): + """"One more" (6F.5): a new line just like this one (product, choices, removed ingredients, note, + course) for `quantity`, priced by the server now and sent like any new line (kitchen ticket, + KDS). Only for products with one_more_enabled, counted in pieces, from an active, paid or + tabbed line that isn't a deal's or the system's. Needs ordering.orders.open.""" + from core.access.context import current_device + from schemas.order import OrderItemInput, SelectedOptionInput + _need(request, db, user, "ordering.orders.open", target=f"order:{order_id}") + order = db.get(Order, order_id) + if order is None: + raise XeniaError("order.not_found", order_id=order_id) + if not _can_access_order(order, user, db): + raise XeniaError("order.not_yours") + item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first() + if item is None: + raise XeniaError("order.item_not_found") + product = item.product + if product is None or not product.one_more_enabled: + raise XeniaError("order.one_more_off") + if item.status not in ("active", "paid", "tabbed") or item.deal_id or item.linked_item_id \ + or product.system_key or (product.unit_type or "piece") != "piece": + raise XeniaError("order.one_more_line") + try: + options = [SelectedOptionInput(**o) for o in json.loads(item.selected_options or "[]") if isinstance(o, dict)] + removed = [str(x) for x in json.loads(item.removed_ingredients or "[]")] + except (ValueError, TypeError): + options, removed = [], [] + device = current_device(request, db) + source = "counter" if device is not None and device.app_key == "pos_counter" else "waiter" + result = add_priced_items(order_id, AddItemsRequest(items=[OrderItemInput( + product_id=item.product_id, quantity=body.quantity, selected_options=options or None, + removed_ingredients=removed or None, notes=item.notes, course_id=item.course_id, source=source, + )]), db, user) + _audit(db, order_id, "ITEM_REORDERED", waiter_id=user.id, item_ids=[item.id], + note=f"{body.quantity:g} more of #{item.id}") + db.commit() + return result + + +class QuantityRequest(BaseModel): + quantity: int = Field(ge=1, le=999) + print_cancellation: bool = False # lowering: send a cancellation to the kitchen (the app asks) + + +@router.post("/{order_id}/items/{item_id}/quantity") +def change_quantity(order_id: int, item_id: int, body: QuantityRequest, request: Request, background_tasks: BackgroundTasks, + db: Session = Depends(get_db), user: User = Depends(get_current_user)): + """Change a sent line's quantity without sending it again (6F.5). The venue + (orders.quantity_change: off | add_only | add_and_remove) and ordering.items.change_quantity + decide; lowering also needs ordering.orders.cancel (or a manager's PIN each). Up: the line + grows, nothing is printed. Down: the removed part becomes its own cancelled line ("quantity + lowered", split_from_id = the line) and, when asked, a cancellation ticket goes to the kitchen. + Only unpaid lines counted in pieces, not a deal's or the system's.""" + from models.settings import PosSettings + order = db.get(Order, order_id) + if order is None: + raise XeniaError("order.not_found", order_id=order_id) + if not _can_access_order(order, user, db): + raise XeniaError("order.not_yours") + row = db.query(PosSettings).filter(PosSettings.key == "orders.quantity_change").first() + mode = row.value if row is not None and row.value in ("off", "add_only", "add_and_remove") else "off" + if mode == "off": + raise XeniaError("order.quantity_change_off") + item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first() + if item is None: + raise XeniaError("order.item_not_found") + product = item.product + if item.status != "active" or item.deal_id or item.linked_item_id or (product is not None and product.system_key) \ + or (item.unit_type or "piece") != "piece" or item.quantity != int(item.quantity): + raise XeniaError("order.quantity_line") + old = int(item.quantity) + if body.quantity == old: + return {"item_id": item.id, "quantity": old, "cancelled_item_id": None} + lowering = body.quantity < old + if lowering and mode != "add_and_remove": + raise XeniaError("order.quantity_remove_off") + approval = _need(request, db, user, "ordering.items.change_quantity", target=f"order:{order_id} item:{item_id}") + cancel_approval = None + if lowering and not holds(user, "core.dashboard.access") and not _waiter_can_cancel(user, db): + cancel_approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}") + note = f"{old} → {body.quantity}" + (f" · {_approval_note(approval)}" if approval is not None else "") + part = None + if lowering: + now = utcnow() + part = cut_part(item, old - body.quantity, status="cancelled", cancelled_by=user.id, cancelled_at=now, + cancel_reason="quantity lowered") + db.add(part) + item.quantity = body.quantity + db.flush() + _audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=[part.id], + note=("quantity lowered" + (f" · {_approval_note(cancel_approval)}" if cancel_approval is not None else "") + + ("" if body.print_cancellation else " · no kitchen ticket"))) + else: + item.quantity = body.quantity + _audit(db, order_id, "QUANTITY_CHANGED", waiter_id=user.id, item_ids=[item.id], note=note) + db.commit() + broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, + "action": "quantity_changed", "item_ids": [item.id]}) + if part is not None: + broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, + "action": "items_cancelled", "item_ids": [part.id]}) + if body.print_cancellation: + background_tasks.add_task(print_cancellation_ticket, order_id, [part.id]) + return {"item_id": item.id, "quantity": item.quantity, "cancelled_item_id": part.id if part is not None else None} + + # ─── Adjust price on an existing item ──────────────────────────────────────── class PriceAdjustRequest(BaseModel): diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index ce0a737..d32c71b 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -89,6 +89,7 @@ def _product_out(p, price: float, prices: dict | None = None) -> dict: "price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()}, "sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON], "base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece", + "one_more": bool(p.one_more_enabled), # 6F.5 "tags": _tags(p.tags), "allergens": allergens.of(p), "primary_category_id": p.primary_category_id, diff --git a/local_backend/schemas/order.py b/local_backend/schemas/order.py index 46213a3..91a1787 100644 --- a/local_backend/schemas/order.py +++ b/local_backend/schemas/order.py @@ -40,6 +40,8 @@ class AddItemsRequest(BaseModel): class ProductNameOut(BaseModel): id: int name: str + one_more_enabled: bool = False # 6F.5: the line shows +1 + unit_type: Optional[str] = None model_config = {"from_attributes": True} diff --git a/local_backend/schemas/product.py b/local_backend/schemas/product.py index 3fb316f..9bb2baf 100644 --- a/local_backend/schemas/product.py +++ b/local_backend/schemas/product.py @@ -386,6 +386,7 @@ class ProductBase(BaseModel): cost_breakdown: Optional[List[CostBreakdownItem]] = None # Quick Add quick_add_enabled: bool = True + one_more_enabled: bool = False # 6F.5 # Tags tags: Optional[List[str]] = None # The EU allergens (plan step 6.3): {key: "contains" | "may_contain"}, core/allergens.py @@ -437,6 +438,7 @@ class ProductUpdate(BaseModel): cost_breakdown: Optional[List[CostBreakdownItem]] = None # Quick Add quick_add_enabled: Optional[bool] = None + one_more_enabled: Optional[bool] = None # 6F.5 # Tags tags: Optional[List[str]] = None allergens: Optional[Dict[str, str]] = None # None = unchanged, {} = none @@ -510,6 +512,7 @@ class ProductOut(ProductBase): 'cost_simple': data.cost_simple, 'cost_breakdown': parsed, 'quick_add_enabled': getattr(data, 'quick_add_enabled', True), + 'one_more_enabled': bool(getattr(data, 'one_more_enabled', False)), 'tags': json.loads(data.tags) if isinstance(getattr(data, 'tags', None), str) else (getattr(data, 'tags', None) or []), 'allergens': _allergens_of(data), 'translations': _menu_tr_of(data), diff --git a/local_backend/tests/test_one_more.py b/local_backend/tests/test_one_more.py new file mode 100644 index 0000000..80ba321 --- /dev/null +++ b/local_backend/tests/test_one_more.py @@ -0,0 +1,123 @@ +"""One more, and a sent line's quantity (owner 2026-11-23, plan 6F.5). + +- POST /api/orders/{id}/items/{item}/again: a new line like the old one, priced now, printed as new; + only with the product's one_more_enabled, from active / paid / tabbed lines in pieces. +- POST /api/orders/{id}/items/{item}/quantity: the venue's switch (off | add_only | add_and_remove), + the key ordering.items.change_quantity; up changes the line only (no ticket); down cuts a + cancelled part ("quantity lowered") and prints a cancellation only when asked. +""" +import json + +import pytest + +from tests.test_live import err +from tests.test_waiter_keys import shop # noqa: F401 (fixture) + + +@pytest.fixture +def printed(monkeypatch): + """What went to the kitchen: new lines (route_and_print_sync) and cancellations.""" + import routers.orders as orders + got = {"tickets": [], "cancellations": []} + monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: (got["tickets"].append(a), [])[1]) + monkeypatch.setattr(orders, "print_cancellation_ticket", lambda order_id, ids: got["cancellations"].append(list(ids))) + return got + + +def setting(db, key, value): + from models.settings import PosSettings + row = db.query(PosSettings).filter(PosSettings.key == key).first() + if row is None: + db.add(PosSettings(key=key, value=value)) + else: + row.value = value + db.commit() + + +def lines(db, order_id): + from models.order import OrderItem + db.expire_all() + return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all() + + +def test_one_more_needs_the_products_switch(client, db, shop, printed): + o, item = shop["order"], shop["items"][0] + url = f"/api/orders/{o.id}/items/{item.id}/again" + assert err(client.post(url, headers=shop["h"], json={})) == "order.one_more_off" + item.product.one_more_enabled = True + item.notes = "no ice" + item.selected_options = json.dumps([{"id": None, "name": "Sweet", "price_delta": 0.0, "type": "quick"}]) + db.commit() + before = len(lines(db, o.id)) + r = client.post(url, headers=shop["h"], json={"quantity": 2}) + assert r.status_code == 200, r.text + new = lines(db, o.id)[-1] + assert len(lines(db, o.id)) == before + 1 and new.id != item.id + assert (new.product_id, new.quantity, new.notes, new.status) == (item.product_id, 2, "no ice", "active") + assert json.loads(new.selected_options)[0]["name"] == "Sweet" and new.unit_price == 4.0 + assert len(printed["tickets"]) == 1 # sent to the kitchen like any new line + # from a paid line too; never from a cancelled one + paid = shop["items"][2] + assert client.post(f"/api/orders/{o.id}/items/{paid.id}/again", headers=shop["h"], json={}).status_code == 200 + paid.status = "cancelled" + db.commit() + assert err(client.post(f"/api/orders/{o.id}/items/{paid.id}/again", headers=shop["h"], json={})) == "order.one_more_line" + + +def test_one_more_needs_ordering_orders_open(client, db, shop, login, printed): + o, item = shop["order"], shop["items"][0] + item.product.one_more_enabled = True + db.commit() + h = login(shop["new_waiter"](remove=("ordering.orders.open",)), client="waiter") + assert err(client.post(f"/api/orders/{o.id}/items/{item.id}/again", headers=h, json={})) == "access.denied" + + +def test_quantity_follows_the_venue_and_the_key(client, db, shop, login, printed): + o, item = shop["order"], shop["items"][0] + url = f"/api/orders/{o.id}/items/{item.id}/quantity" + assert err(client.post(url, headers=shop["h"], json={"quantity": 3})) == "order.quantity_change_off" + setting(db, "orders.quantity_change", "add_only") + # a waiter without the key: a manager may approve it + assert err(client.post(url, headers=shop["h"], json={"quantity": 3})) == "access.override_possible" + h = login(shop["new_waiter"](add=("ordering.items.change_quantity",)), client="waiter") + r = client.post(url, headers=h, json={"quantity": 3}) + assert r.status_code == 200, r.text + assert lines(db, o.id)[0].quantity == 3 and printed["tickets"] == [] and printed["cancellations"] == [] + assert err(client.post(url, headers=h, json={"quantity": 2})) == "order.quantity_remove_off" + from models.order import OrderAuditLog + log = db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "QUANTITY_CHANGED").one() + assert log.note.startswith("1 → 3") + + +def test_lowering_cancels_the_difference_and_asks_about_the_ticket(client, db, shop, login, printed): + o, item = shop["order"], shop["items"][0] + item.quantity = 5 + db.commit() + setting(db, "orders.quantity_change", "add_and_remove") + url = f"/api/orders/{o.id}/items/{item.id}/quantity" + # the key, but not the cancel key: a manager's approval for the cancel part + h = login(shop["new_waiter"](add=("ordering.items.change_quantity",), remove=("ordering.orders.cancel",)), client="waiter") + assert err(client.post(url, headers=h, json={"quantity": 3})) == "access.override_possible" + h = login(shop["new_waiter"](add=("ordering.items.change_quantity", "ordering.orders.cancel")), client="waiter") + r = client.post(url, headers=h, json={"quantity": 3, "print_cancellation": False}) + assert r.status_code == 200, r.text + part_id = r.json()["cancelled_item_id"] + rows = {i.id: i for i in lines(db, o.id)} + assert rows[item.id].quantity == 3 and rows[item.id].status == "active" + part = rows[part_id] + assert (part.quantity, part.status, part.cancel_reason, part.split_from_id) == (2, "cancelled", "quantity lowered", item.id) + assert printed["cancellations"] == [] + r = client.post(url, headers=h, json={"quantity": 2, "print_cancellation": True}) + assert printed["cancellations"] == [[r.json()["cancelled_item_id"]]] + + +def test_only_unpaid_lines_in_pieces(client, db, shop, printed, login): + setting(db, "orders.quantity_change", "add_and_remove") + o = shop["order"] + paid = shop["items"][2] + boss = login(shop["owner"]) + assert err(client.post(f"/api/orders/{o.id}/items/{paid.id}/quantity", headers=boss, json={"quantity": 2})) == "order.quantity_line" + item = shop["items"][0] + item.product.unit_type = "kg" + db.commit() + assert err(client.post(f"/api/orders/{o.id}/items/{item.id}/quantity", headers=boss, json={"quantity": 2})) == "order.quantity_line" diff --git a/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx b/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx index c7a5e7b..16daa0a 100644 --- a/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx +++ b/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx @@ -68,9 +68,27 @@ function OrderingSettings() { itemLabel={o('quickNote')} placeholder={o('newQuickNote')} testId="settings-quick-notes" newTestId="quick-note" /> + ) } +/** A sent line's quantity changed without a new ticket (6F.5). Who may: ordering.items.change_quantity; + * lowering also needs ordering.orders.cancel ("What each role may do", a person's permissions). */ +function QuantitySettings({ s }) { + const { t } = useTranslation('manager') + const q = k => t(`settings.quantity.${k}`) + const id = useId() + return ( + + + setTicket(e.target.checked)} data-testid="quantity-ticket" style={{ width: 20, height: 20 }} /> + {t('quantity.sendCancel')} + + )} + {error &&

{error}

} +
+ + +
+ + + ) +} diff --git a/waiter_pwa/src/hooks/useQuantityMode.js b/waiter_pwa/src/hooks/useQuantityMode.js new file mode 100644 index 0000000..4bac1ef --- /dev/null +++ b/waiter_pwa/src/hooks/useQuantityMode.js @@ -0,0 +1,14 @@ +// The venue's orders.quantity_change (6F.5, logic/lines.js), from the shared settings request. +import { useEffect, useState } from 'react' +import { getVenueSettings } from '../api/venueSettings' +import { quantityMode } from '../logic/lines' + +export function useQuantityMode() { + const [mode, setMode] = useState('off') + useEffect(() => { + let alive = true + getVenueSettings().then(r => { if (alive) setMode(quantityMode(r.data)) }).catch(() => {}) + return () => { alive = false } + }, []) + return mode +} diff --git a/waiter_pwa/src/logic/lines.js b/waiter_pwa/src/logic/lines.js new file mode 100644 index 0000000..d821494 --- /dev/null +++ b/waiter_pwa/src/logic/lines.js @@ -0,0 +1,31 @@ +// A sent line's "one more" and quantity rules (plan 6F.5). Plain JS so Node tests can import it. + +/** The venue's orders.quantity_change: 'off' | 'add_only' | 'add_and_remove'. */ +export function quantityMode(settings) { + const v = settings?.['orders.quantity_change']?.value + return ['off', 'add_only', 'add_and_remove'].includes(v) ? v : 'off' +} + +const PIECE = item => (item?.unit_type || item?.product?.unit_type || 'piece') === 'piece' + +/** A line that shows +1: its product allows it, counted in pieces, not cancelled, not a deal's. */ +export function canOneMore(item) { + return !!item?.product?.one_more_enabled && PIECE(item) && ['active', 'paid', 'tabbed'].includes(item.status) + && !item.deal_id && !item.linked_item_id +} + +/** A line whose quantity may change: unpaid, in whole pieces, not a deal's. */ +export function canChangeQuantity(item, mode) { + return mode !== 'off' && item?.status === 'active' && PIECE(item) && Number.isInteger(item.quantity) + && !item.deal_id && !item.linked_item_id +} + +/** Lowering a line: send a cancellation to the kitchen? Yes while it is still waiting or being made. */ +export function cancelByDefault(item) { + return ['pending', 'preparing'].includes(item?.kds_status || 'pending') +} + +/** The lowest quantity the dialog allows. */ +export function lowestQuantity(item, mode) { + return mode === 'add_and_remove' ? 1 : item.quantity +} diff --git a/waiter_pwa/src/pages/TableDetailPage.jsx b/waiter_pwa/src/pages/TableDetailPage.jsx index 85886f1..6df077d 100644 --- a/waiter_pwa/src/pages/TableDetailPage.jsx +++ b/waiter_pwa/src/pages/TableDetailPage.jsx @@ -20,6 +20,9 @@ import PriceReason from '../components/PriceReason' import { priceReasonText } from '../logic/priceRules' import PriceHistory from '../components/PriceHistory' import MoveHistory, { MovedOrderBanner } from '../components/MoveHistory' +import QuantityModal from '../components/QuantityModal' +import { useQuantityMode } from '../hooks/useQuantityMode' +import { canChangeQuantity } from '../logic/lines' import { usePriceRules } from '../hooks/usePriceRules' import { fade } from '../logic/colour' import SeatsHint from '../components/SeatsHint' @@ -266,7 +269,7 @@ function PriceAdjustModal({ item, rules, error, onConfirm, onClose }) { // ─── Item action modal (long-press) ────────────────────────────────────────── -function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, canSeePriceHistory, onPriceHistory, movedLine, onMoveHistory, onClose }) { +function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, canSeePriceHistory, onPriceHistory, movedLine, onMoveHistory, canChangeQty, onChangeQty, onClose }) { const { t } = useTranslation('waiter') const { items, singleStacked, multiSelect } = target const label = multiSelect @@ -274,6 +277,22 @@ function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCance : items[0]?.product?.name || `#${items[0]?.product_id}` const actionRows = [ + // 6F.5: correct how many there are, without sending it to the kitchen again + ...(!multiSelect && canChangeQty ? [{ + key: 'change_quantity', + color: 'var(--x-accent)', + iconBg: 'rgb(var(--x-accent-rgb) / 0.15)', + label: t('quantity.title'), + sub: t('quantity.actionSub'), + icon: ( + + + + + ), + onClick: onChangeQty, + enabled: true, + }] : []), // 6F.4: where this line has been (tables, orders), however many moves ...(!multiSelect && movedLine ? [{ key: 'move_history', @@ -1184,6 +1203,12 @@ export default function TableDetailPage() { const [priceEventsMap, setPriceEventsMap] = useState({}) const [moves, setMoves] = useState({ order: [], items: {} }) // 6F.4: where the order and its lines came from const [moveSheet, setMoveSheet] = useState(null) // { title, subtitle, moves, itemId } + // 6F.5: a line's quantity (no new ticket) and "+1" (one more, sent as new) + const quantityMode = useQuantityMode() + const quantityAccess = useAllowed('ordering.items.change_quantity') + const [qtyItem, setQtyItem] = useState(null) + const [qtyError, setQtyError] = useState('') + const [qtyBusy, setQtyBusy] = useState(false) const [cancelConfirm, setCancelConfirm] = useState(null) // null | { mode: 'items', ids: [...] } | { mode: 'order' } const [paidSelectedIds, setPaidSelectedIds] = useState([]) @@ -1938,6 +1963,12 @@ export default function TableDetailPage() { waiterMap={waiterMap} priceEventsMap={priceEventsMap} movedItems={moves.items} + onOneMore={canInteract && !paying && !isOffline ? async (item, qty) => { + try { + await client.post(`/api/orders/${order.id}/items/${item.id}/again`, { quantity: qty }) + await load() + } catch (err) { setError(apiError(err, t('detail.err.again'))) } + } : undefined} onLongPressItem={(item) => { if (selectedIds.length > 1) { const items = displayActiveItems.filter(i => selectedIds.includes(i.id)) @@ -2027,6 +2058,12 @@ export default function TableDetailPage() { <> { // 6F.5: the beer already paid for + try { + await client.post(`/api/orders/${order.id}/items/${item.id}/again`, { quantity: qty }) + await load() + } catch (err) { setError(apiError(err, t('detail.err.again'))) } + } : undefined} selectable={canInteract} selectedIds={paidSelectedIds} waiterMap={waiterMap} @@ -2265,6 +2302,13 @@ export default function TableDetailPage() { }} canSeePriceHistory={seesPriceChanges && !isOffline} movedLine={!!moves.items[itemActionTarget.items[0]?.id]} + canChangeQty={quantityAccess !== 'no' && !isOffline && canChangeQuantity(itemActionTarget.items[0], quantityMode)} + onChangeQty={() => { + const item = itemActionTarget.items[0] + setItemActionTarget(null) + setQtyError('') + setQtyItem(item) + }} onMoveHistory={() => { const item = itemActionTarget.items[0] setItemActionTarget(null) @@ -2320,6 +2364,18 @@ export default function TableDetailPage() { {historyItem && setHistoryItem(null)} />} {moveSheet && setMoveSheet(null)} />} + {qtyItem && ( + { setQtyItem(null); setQtyError('') }} + onSave={async (quantity, ticket) => { + setQtyBusy(true); setQtyError('') + try { + await client.post(`/api/orders/${order.id}/items/${qtyItem.id}/quantity`, { quantity, print_cancellation: ticket }) + setQtyItem(null) + await load() + } catch (err) { setQtyError(apiError(err, t('detail.err.quantity'))) } finally { setQtyBusy(false) } + }} /> + )} {/* Cancel confirmation */} {cancelConfirm && ( diff --git a/waiter_pwa/tests/lines.test.mjs b/waiter_pwa/tests/lines.test.mjs new file mode 100644 index 0000000..46991de --- /dev/null +++ b/waiter_pwa/tests/lines.test.mjs @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { cancelByDefault, canChangeQuantity, canOneMore, lowestQuantity, quantityMode } from '../src/logic/lines.js' + +const beer = (o = {}) => ({ status: 'active', quantity: 3, unit_type: 'piece', product: { one_more_enabled: true }, kds_status: 'pending', ...o }) + +test('one more: the product allows it, pieces, a line still there (6F.5)', () => { + assert.equal(canOneMore(beer()), true) + assert.equal(canOneMore(beer({ status: 'paid' })), true) + assert.equal(canOneMore(beer({ status: 'cancelled' })), false) + assert.equal(canOneMore(beer({ product: { one_more_enabled: false } })), false) + assert.equal(canOneMore(beer({ unit_type: 'kg' })), false) + assert.equal(canOneMore(beer({ deal_id: 4 })), false) +}) + +test('changing a quantity: the venue, unpaid whole pieces; how low; the ticket question', () => { + const s = v => ({ 'orders.quantity_change': { value: v } }) + assert.equal(quantityMode(null), 'off') + assert.equal(quantityMode(s('add_only')), 'add_only') + assert.equal(quantityMode(s('nonsense')), 'off') + assert.equal(canChangeQuantity(beer(), 'off'), false) + assert.equal(canChangeQuantity(beer(), 'add_only'), true) + assert.equal(canChangeQuantity(beer({ status: 'paid' }), 'add_and_remove'), false) + assert.equal(canChangeQuantity(beer({ quantity: 1.5 }), 'add_and_remove'), false) + assert.equal(lowestQuantity(beer(), 'add_only'), 3) + assert.equal(lowestQuantity(beer(), 'add_and_remove'), 1) + assert.equal(cancelByDefault(beer({ kds_status: 'preparing' })), true) + assert.equal(cancelByDefault(beer({ kds_status: 'served' })), false) + assert.equal(cancelByDefault(beer({ kds_status: 'done' })), false) +})