diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 46d55db..c03aa2f 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -221,6 +221,9 @@ CODES: dict[str, tuple[int, str]] = { "order.item_not_found": (404, "That item isn't on the order any more."), "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.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."), "order.cannot_close": (400, "This order can't be closed now ({status})."), "order.no_active_items": (400, "None of these items are on the order any more."), diff --git a/local_backend/migrations/versions/0047_price_changes.py b/local_backend/migrations/versions/0047_price_changes.py new file mode 100644 index 0000000..379cb30 --- /dev/null +++ b/local_backend/migrations/versions/0047_price_changes.py @@ -0,0 +1,45 @@ +"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3). + +- price_event_log: approved_by_user_id, stage (cart | sent | served), quantity, for the new + event type manual_price (services/price_changes.py). +- The keys ordering.prices.modify_sent (everyone who holds ordering.prices.modify today: nobody + loses what they could do) and ordering.prices.view_changes (owners and store managers). + +Revision ID: 0047_price_changes +Revises: 0046_media_folders +Create Date: 2026-11-23 12:00:00 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0047_price_changes' +down_revision = '0046_media_folders' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table('price_event_log') as b: + b.add_column(sa.Column('approved_by_user_id', sa.Integer(), nullable=True)) + b.add_column(sa.Column('stage', sa.String(), nullable=True)) + b.add_column(sa.Column('quantity', sa.Float(), nullable=True)) + b.create_foreign_key('fk_price_event_approved_by', 'users', ['approved_by_user_id'], ['id']) + bind = op.get_bind() + bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) " + "select user_id, 'ordering.prices.modify_sent' from user_permissions where key = 'ordering.prices.modify'")) + # a venue that changed a role's default for modify gets the same for modify_sent + bind.execute(sa.text("insert or ignore into role_permissions (role, key, granted) " + "select role, 'ordering.prices.modify_sent', granted from role_permissions where key = 'ordering.prices.modify'")) + bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) " + "select id, 'ordering.prices.view_changes' from users where role in ('owner', 'store_manager')")) + + +def downgrade() -> None: + bind = op.get_bind() + bind.execute(sa.text("delete from user_permissions where key in ('ordering.prices.modify_sent', 'ordering.prices.view_changes')")) + bind.execute(sa.text("delete from role_permissions where key = 'ordering.prices.modify_sent'")) + with op.batch_alter_table('price_event_log') as b: + b.drop_constraint('fk_price_event_approved_by', type_='foreignkey') + b.drop_column('quantity') + b.drop_column('stage') + b.drop_column('approved_by_user_id') diff --git a/local_backend/models/pricing.py b/local_backend/models/pricing.py index c6a1a91..c4a3976 100644 --- a/local_backend/models/pricing.py +++ b/local_backend/models/pricing.py @@ -227,6 +227,7 @@ class PriceEventLog(Base): # deal_offer_dismissed — waiter dismissed the deal offer # waiter_discount — manual waiter discount applied # free_item_added — free item added to order as result of a deal + # manual_price — a price changed by hand (6F.3, services/price_changes.py) modifier_id = Column(Integer, ForeignKey("price_modifiers.id"), nullable=True) deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True) @@ -236,10 +237,15 @@ class PriceEventLog(Base): price_after = Column(Float, nullable=True) delta_amount = Column(Float, nullable=True) # price_after - price_before; negative = discount - # Waiter discount fields + # Waiter discount fields (also manual_price: who changed it, and the reason) applied_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True) waiter_note = Column(Text, nullable=True) + # manual_price (6F.3, services/price_changes.py): a price changed by hand + approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True) # a manager's PIN (D-10) + stage = Column(String, nullable=True) # cart | sent | served + quantity = Column(Float, nullable=True) # the line's quantity at the time + # Snapshot of the conditions that evaluated to True when the event fired. # JSON object: {"condition_type": evaluated_value, ...} # e.g. {"day_of_week": 5, "time_range": "21:45", "price_group_active": true} @@ -255,6 +261,7 @@ class PriceEventLog(Base): modifier = relationship("PriceModifier", foreign_keys=[modifier_id]) deal = relationship("Deal", foreign_keys=[deal_id]) applied_by = relationship("User", foreign_keys=[applied_by_user_id]) + approved_by = relationship("User", foreign_keys=[approved_by_user_id]) class WaiterDiscountSettings(Base): diff --git a/local_backend/modules/ordering/manifest.py b/local_backend/modules/ordering/manifest.py index ceedf34..d234467 100644 --- a/local_backend/modules/ordering/manifest.py +++ b/local_backend/modules/ordering/manifest.py @@ -11,7 +11,9 @@ MODULE = Module( Perm('ordering.orders.open', 'Open orders and add items', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')), Perm('ordering.orders.close', 'Take payments and close orders', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')), Perm('ordering.orders.cancel', 'Cancel items already sent', roles=('owner', 'store_manager'), overridable=True), - Perm('ordering.prices.modify', "Change an item's price", roles=('owner',), 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.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), Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')), @@ -22,6 +24,9 @@ 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.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'), 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'), SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'), diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index c14122f..8bd222e 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -584,20 +584,27 @@ def add_items(order_id: int, body: AddLinesRequest, request: Request, db: Sessio raise XeniaError("order.not_yours") lines, manual = _resolve_lines(db, body.lines, of_order(order)) approval = None + reasons = [None] * len(lines) if any(manual) or any(line.discount_pct for line in lines): + from services import price_changes # the venue's switch and the reason first (6F.3) + reasons = [price_changes.check(db, sent=False, reason=(raw or {}).get("price_reason") if isinstance(raw, dict) else None, + by_hand=bool(hand)) if hand or line.discount_pct else None + for raw, line, hand in zip(body.lines, lines, manual)] approval = _need(request, db, user, "ordering.prices.modify", target=f"order {order_id} new items") discounts = [0.0] * len(lines) if any(line.discount_pct for line in lines): priced = pos_cart.price_lines(db, lines, order.order_type or "here", pos_cart.order_cart(order), point=of_order(order)) discounts = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)] items = [] - for raw, line, hand, disc in zip(body.lines, lines, manual, discounts): + for raw, line, hand, disc, reason in zip(body.lines, lines, manual, discounts, reasons): adj = round(hand + disc, 2) items.append(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, is_service_item=raw.get("is_service_item") is True, course_id=raw.get("course_id"), + price_reason=reason if adj else None, + price_approved_by=approval.approved_by if approval is not None and adj else None, )) result = add_priced_items(order_id, AddItemsRequest(items=items, order_note=body.order_note, customer_count=body.customer_count), db, user) @@ -708,6 +715,11 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us db.add(item) db.flush() new_item_ids.append(item.id) + if item.price_adjustment: # a price changed by hand in the cart (6F.3) + from services import price_changes + price_changes.record(db, item=item, before=unit_price, after=unit_price + item.price_adjustment, + user_id=user.id, stage="cart", reason=item_in.price_reason, + approved_by=item_in.price_approved_by) # Stamp order_id on events and queue them — written after commit if price_events: @@ -1627,6 +1639,7 @@ def split_item( class PriceAdjustRequest(BaseModel): price_adjustment: float # delta from unit_price (can be negative) + reason: Optional[str] = Field(default=None, max_length=200) # 6F.3: needed when the venue asks for one @router.patch("/{order_id}/items/{item_id}/price-adjust", response_model=OrderItemOut) @@ -1638,8 +1651,10 @@ def adjust_item_price( db: Session = Depends(get_db), user: User = Depends(get_current_user), ): - """Apply an on-the-fly price adjustment to an active order item. Without - ordering.prices.modify a manager can approve it once (X-Xenia-Override, D-10).""" + """Change a sent line's price by hand (6F.3): the venue must allow it after sending + (orders.price_change = anytime), it needs ordering.prices.modify_sent (a manager can approve it + once, X-Xenia-Override, D-10) and, when the venue asks, a reason. Recorded as a manual_price + event (before → after, who, the approver, the stage, the reason).""" item = db.query(OrderItem).filter( OrderItem.id == item_id, OrderItem.order_id == order_id ).first() @@ -1651,15 +1666,37 @@ def adjust_item_price( order = db.query(Order).filter(Order.id == order_id).first() if not _can_access_order(order, user, db): raise XeniaError("order.not_yours") - _need(request, db, user, "ordering.prices.modify", target=f"order:{order_id} item:{item_id}") + from services import price_changes + reason = price_changes.check(db, sent=True, reason=body.reason) + approval = _need(request, db, user, "ordering.prices.modify_sent", target=f"order:{order_id} item:{item_id}") + if not -10000 <= body.price_adjustment <= 10000 or item.unit_price + body.price_adjustment < 0: + raise XeniaError("order.line.price", line=1, name=item.product_name) - item.price_adjustment = body.price_adjustment + before = item.unit_price + (item.price_adjustment or 0.0) + item.price_adjustment = round(body.price_adjustment, 2) + price_changes.record(db, item=item, before=before, after=item.unit_price + item.price_adjustment, user_id=user.id, + stage=price_changes.stage_of(item), reason=reason, + approved_by=approval.approved_by if approval is not None else None) db.commit() db.refresh(item) broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "item_price_adjusted"}) return item +@router.get("/{order_id}/price-changes") +def order_price_changes(order_id: int, db: Session = Depends(get_db), + user: User = Depends(require("ordering.prices.view_changes"))): + """The prices changed by hand on an order (6F.3), oldest first, for the waiter app and the + counter: [{id, item_id, product_name, before, after, delta, quantity, stage, reason, by, approved_by, at}].""" + from models.pricing import PriceEventLog + from services import price_changes + order = db.get(Order, order_id) + if order is None: + raise XeniaError("order.not_found", order_id=order_id) + return [price_changes.event_out(ev, db) for ev in db.query(PriceEventLog).filter( + PriceEventLog.order_id == order_id, PriceEventLog.event_type == price_changes.EVENT).order_by(PriceEventLog.id)] + + # ─── Waiter-applied manual discount ───────────────────────────────────────── from schemas.pricing import ApplyDiscountRequest, ApplyDiscountResponse diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index 029bfb5..ce0a737 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -140,8 +140,10 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi by_point = {sp: pos_cart.unit_prices(db, products, sp) for sp in sales_points.IN_PERSON} default = pos_cart.point_for(settings["default_order_type"]) cats = db.query(Category).order_by(Category.sort_order, Category.name).all() + from services import price_changes return { - "settings": settings, + # + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount + "settings": {**settings, "price_change": price_changes.mode(db)}, "categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order} for c in cats], "products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON}) @@ -209,7 +211,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key 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)) - _check_discounts(request, db, user, lines) + approved_by = _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)] @@ -218,7 +220,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us _check_cash(body.cash_given, cash_due) order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user) - added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user) + added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), 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: @@ -247,9 +249,16 @@ def _require_shift(db, user): def _check_discounts(request, db, user, lines): + """A % discount at the counter is a price change in the cart (6F.3): the venue's switch, then + the key (or a manager's PIN). Returns the approving manager's id, else None. The reason isn't + asked: the discount itself says what it is.""" from core.access.context import authorize + from services import price_changes if any(line.discount_pct for line in lines): - authorize(request, db, user, "ordering.prices.modify", target="pos sale discount") + price_changes.check(db, sent=False, by_hand=False) + approval = authorize(request, db, user, "ordering.prices.modify", target="pos sale discount") + return approval.approved_by if approval is not None else None + return None def _check_fiscal(db, products): @@ -265,14 +274,17 @@ def _check_cash(cash_given, cash_due): raise XeniaError("pos.payment_invalid", reason="cash_short") -def _items_in(lines, adjs): +def _items_in(lines, adjs, approved_by=None): """Resolved lines as orders.add_priced_items takes them (selected_options entries with the - database's prices; a discount as the item's price_adjustment).""" + database's prices; a discount as the item's price_adjustment, recorded as a manual_price event + with "−N %" as its reason, 6F.3).""" 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, source="counter", + price_reason=f"−{line.discount_pct:g} %" if adj and line.discount_pct else None, + price_approved_by=approved_by if adj else None, ) for line, adj in zip(lines, adjs)] @@ -407,13 +419,13 @@ def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: S 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) + approved_by = _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_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user) + added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user) return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])} diff --git a/local_backend/routers/pricing.py b/local_backend/routers/pricing.py index f7ef4ac..4d93c6b 100644 --- a/local_backend/routers/pricing.py +++ b/local_backend/routers/pricing.py @@ -527,12 +527,11 @@ def get_order_price_events( db: Session = Depends(get_db), user: User = Depends(get_current_user), ): - events = ( - db.query(PriceEventLog) - .filter(PriceEventLog.order_id == order_id) - .order_by(PriceEventLog.applied_at) - .all() - ) + from services import price_changes + q = db.query(PriceEventLog).filter(PriceEventLog.order_id == order_id) + if not price_changes.can_view(user): # prices changed by hand: ordering.prices.view_changes (6F.3) + q = q.filter(PriceEventLog.event_type != price_changes.EVENT) + events = q.order_by(PriceEventLog.applied_at).all() result = [] for ev in events: out = PriceEventOut.model_validate(ev) @@ -541,7 +540,9 @@ def get_order_price_events( if ev.deal: out.deal_name = ev.deal.name if ev.applied_by: - out.applied_by_username = ev.applied_by.username + out.applied_by_username = ev.applied_by.nickname or ev.applied_by.username + if ev.approved_by: + out.approved_by_username = ev.approved_by.nickname or ev.approved_by.username result.append(out) return result diff --git a/local_backend/routers/reports.py b/local_backend/routers/reports.py index 3802904..756733e 100644 --- a/local_backend/routers/reports.py +++ b/local_backend/routers/reports.py @@ -1872,6 +1872,67 @@ def print_prep_zone( # Phase 2L — Discount audit report # --------------------------------------------------------------------------- +@router.get("/price-changes") +def price_changes_report( + from_dt: Optional[str] = Query(default=None, alias="from"), + to_dt: Optional[str] = Query(default=None, alias="to"), + business_day_id: Optional[int] = None, + applied_by: Optional[int] = None, + db: Session = Depends(get_db), + user: User = Depends(require_reports), +): + """Prices changed by hand (6F.3) in a period or a business day: each change (the line, before → + after, the difference for its quantity, the stage, who, the approving manager, why, the table), + totals per person. Needs ordering.prices.view_changes besides the reports key.""" + from core.access.check import holds + from models.pricing import PriceEventLog + from services import price_changes + if not holds(user, "ordering.prices.view_changes"): + raise XeniaError("access.denied", key="ordering.prices.view_changes") + q = db.query(PriceEventLog).filter(PriceEventLog.event_type == price_changes.EVENT) + if business_day_id: + q = q.join(Order, Order.id == PriceEventLog.order_id).filter(Order.business_day_id == business_day_id) + elif from_dt and to_dt: + q = q.filter(PriceEventLog.applied_at >= history_since(from_dt, 'reports'), + PriceEventLog.applied_at <= parse_api_datetime(to_dt)) + if applied_by: + q = q.filter(PriceEventLog.applied_by_user_id == applied_by) + events = q.order_by(PriceEventLog.applied_at.desc()).all() + tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} + orders_map = {o.id: o for o in db.query(Order).filter(Order.id.in_({e.order_id for e in events})).all()} if events else {} + rows, by_person, total = [], {}, 0.0 + for ev in events: + row = price_changes.event_out(ev, db) + row["at"] = _dt(ev.applied_at) + order = orders_map.get(ev.order_id) + row["table_name"] = tables_map.get(order.table_id) if order is not None and order.table_id else None + row["value"] = round((ev.delta_amount or 0.0) * (ev.quantity or 1.0), 2) + total += row["value"] + p = by_person.setdefault(ev.applied_by_user_id, {"user_id": ev.applied_by_user_id, "name": row["by"], "count": 0, "total_value": 0.0}) + p["count"] += 1 + p["total_value"] = round(p["total_value"] + row["value"], 2) + rows.append(row) + return {"changes": rows, "total_value": round(total, 2), "count": len(rows), + "by_person": sorted(by_person.values(), key=lambda x: x["total_value"])} + + +@router.get("/price-changes/export") +def price_changes_export( + from_dt: Optional[str] = Query(default=None, alias="from"), + to_dt: Optional[str] = Query(default=None, alias="to"), + business_day_id: Optional[int] = None, + applied_by: Optional[int] = None, + db: Session = Depends(get_db), + user: User = Depends(require_reports), +): + data = price_changes_report(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, applied_by=applied_by, db=db, user=user) + rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table_name"] or "", "product": c["product_name"] or "", + "quantity": c["quantity"], "before": c["before"], "after": c["after"], "value": c["value"], "stage": c["stage"] or "", + "by": c["by"] or "", "approved_by": c["approved_by"] or "", "reason": c["reason"] or "", "at": c["at"]} for c in data["changes"]] + fields = ["id", "order_id", "table", "product", "quantity", "before", "after", "value", "stage", "by", "approved_by", "reason", "at"] + return csv_export.response(db, rows, fields, f"price-changes-{(from_dt or '')[:10]}.csv", times=("at",)) + + @router.get("/discounts") def discounts_report( from_dt: Optional[str] = Query(default=None, alias="from"), diff --git a/local_backend/schemas/order.py b/local_backend/schemas/order.py index 33fcbf9..ce0e117 100644 --- a/local_backend/schemas/order.py +++ b/local_backend/schemas/order.py @@ -26,6 +26,9 @@ class OrderItemInput(BaseModel): 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 + # a price changed by hand (6F.3), set by the server: the reason and the approving manager + price_reason: Optional[str] = None + price_approved_by: Optional[int] = None class AddItemsRequest(BaseModel): diff --git a/local_backend/schemas/pricing.py b/local_backend/schemas/pricing.py index 4317b21..bdd7564 100644 --- a/local_backend/schemas/pricing.py +++ b/local_backend/schemas/pricing.py @@ -308,10 +308,15 @@ class PriceEventOut(BaseModel): conditions_snapshot: Optional[dict] selected_item_ids: Optional[List[int]] applied_at: datetime + # manual_price (6F.3) + approved_by_user_id: Optional[int] = None + stage: Optional[str] = None + quantity: Optional[float] = None # Resolved names (joined at query time) modifier_name: Optional[str] = None deal_name: Optional[str] = None applied_by_username: Optional[str] = None + approved_by_username: Optional[str] = None model_config = {"from_attributes": True} diff --git a/local_backend/services/price_changes.py b/local_backend/services/price_changes.py new file mode 100644 index 0000000..e00e8a0 --- /dev/null +++ b/local_backend/services/price_changes.py @@ -0,0 +1,124 @@ +"""Prices changed by hand, on the record (owner 2026-11-23, plan step 6F.3). + +Who may change a line's price, in three levels like every permission: +- the venue (setting `orders.price_change`): `off` | `before_sending` (only in the cart, before + the line is sent) | `anytime` (also a line already sent or served; the default, as before 6F.3); +- the keys: `ordering.prices.modify` (in the cart; the counter's % discount too) and + `ordering.prices.modify_sent` (a line already sent), role defaults per venue, changed per person; + both may be approved once by a manager's PIN (D-10); +- `orders.price_change_reason`: when on, a by-hand price needs a reason (the venue's quick + reasons, `orders.price_change_reasons`, or typed). + +Every change writes one `PriceEventLog` row, `event_type = "manual_price"`: the line, its unit price +before and after, the change, the quantity, who, the approving manager, the stage +(cart | sent | served) and the reason (`waiter_note`), plus an `OrderAuditLog` `PRICE_CHANGED`. +Rows are never deleted; combining lines moves them to the kept line (orders.combine_items). +Who sees them: `ordering.prices.view_changes` (GET /api/pricing/events/order/{id}, +GET /api/orders/{id}/items/{item}/price-changes, Reports → Cancellations, discounts and price changes). +""" +from __future__ import annotations + +import json + +from core.errors import XeniaError + +EVENT = "manual_price" +MODES = ("off", "before_sending", "anytime") +STAGES = ("cart", "sent", "served") +REASON_MAX = 200 + + +def _setting(db, key: str, default: str) -> str: + from models.settings import PosSettings + row = db.query(PosSettings).filter(PosSettings.key == key).first() + return row.value if row is not None and row.value not in (None, "") else default + + +def mode(db) -> str: + v = _setting(db, "orders.price_change", "anytime") + return v if v in MODES else "anytime" + + +def reason_required(db) -> bool: + return _setting(db, "orders.price_change_reason", "false") == "true" + + +def quick_reasons(db) -> list[str]: + try: + v = json.loads(_setting(db, "orders.price_change_reasons", "[]")) + except ValueError: + return [] + return [str(x).strip() for x in v if isinstance(x, str) and x.strip()] if isinstance(v, list) else [] + + +def clean_reason(reason) -> str | None: + text = " ".join(str(reason or "").split())[:REASON_MAX] + return text or None + + +def check(db, *, sent: bool, reason=None, by_hand: bool = True) -> str | None: + """Refuse a price change the venue doesn't allow (order.price_change_off / + order.price_change_sent_off) or one without its reason (order.price_reason_required, only for + a price typed by hand: the counter's % discount has none). Returns the cleaned reason.""" + m = mode(db) + if m == "off": + raise XeniaError("order.price_change_off") + if sent and m != "anytime": + raise XeniaError("order.price_change_sent_off") + text = clean_reason(reason) + if by_hand and text is None and reason_required(db): + raise XeniaError("order.price_reason_required") + return text + + +def stage_of(item) -> str: + """Where a line is when its price changes: in the cart (being added), sent, or served.""" + if item is None or getattr(item, "id", None) is None: + return "cart" + return "served" if getattr(item, "kds_status", None) == "served" else "sent" + + +def record(db, *, item, before: float, after: float, user_id: int | None, stage: str, + reason: str | None = None, approved_by: int | None = None, audit: bool = True): + """One manual_price event for `item` (flushed with the caller's commit) and its audit row.""" + from models.order import OrderAuditLog + from models.pricing import PriceEventLog + before, after = round(float(before), 2), round(float(after), 2) + if abs(after - before) < 0.005: + return None + ev = PriceEventLog( + order_id=item.order_id, order_item_id=item.id, event_type=EVENT, + price_before=before, price_after=after, delta_amount=round(after - before, 2), + applied_by_user_id=user_id, approved_by_user_id=approved_by, waiter_note=reason, + stage=stage if stage in STAGES else "cart", quantity=item.quantity, + ) + db.add(ev) + if audit: + db.add(OrderAuditLog(order_id=item.order_id, event_type="PRICE_CHANGED", waiter_id=user_id, + item_ids=json.dumps([item.id]), + note=f"{before:.2f} → {after:.2f}" + (f" · {reason}" if reason else "") + + (f" · approved by user {approved_by}" if approved_by else ""))) + return ev + + +def _name(user) -> str | None: + return (user.nickname or user.full_name or user.username) if user is not None else None + + +def event_out(ev, db) -> dict: + """One manual_price event for the apps and the reports.""" + item = ev.order_item + return { + "id": ev.id, "order_id": ev.order_id, "item_id": ev.order_item_id, + "product_name": item.product_name if item is not None else None, + "before": ev.price_before, "after": ev.price_after, "delta": ev.delta_amount, + "quantity": ev.quantity, "stage": ev.stage, "reason": ev.waiter_note, + "by_id": ev.applied_by_user_id, "by": _name(ev.applied_by), + "approved_by_id": ev.approved_by_user_id, "approved_by": _name(ev.approved_by), + "at": ev.applied_at, + } + + +def can_view(user) -> bool: + from core.access.check import holds + return holds(user, "ordering.prices.view_changes") diff --git a/local_backend/tests/test_override.py b/local_backend/tests/test_override.py index 0b378eb..1803a1f 100644 --- a/local_backend/tests/test_override.py +++ b/local_backend/tests/test_override.py @@ -94,7 +94,7 @@ def test_waiter_cancels_after_manager_pin(client, db, venue, login): def test_token_is_bound_to_its_key(client, db, venue, make_user, login): v = venue - token = approve(client, v["waiter_h"], "ordering.prices.modify", make_user(role="owner").username).json()["override_token"] + token = approve(client, v["waiter_h"], "ordering.prices.modify_sent", make_user(role="owner").username).json()["override_token"] # used for another key: refused, and NOT burned r = cancel(client, v, v["items"][0], token) assert err(r) == "access.override_invalid" diff --git a/local_backend/tests/test_price_changes.py b/local_backend/tests/test_price_changes.py new file mode 100644 index 0000000..2625df1 --- /dev/null +++ b/local_backend/tests/test_price_changes.py @@ -0,0 +1,170 @@ +"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3, services/price_changes.py). + +- The venue's switch `orders.price_change`: off refuses every by-hand price, before_sending refuses + a sent line's, anytime allows both. +- A sent line needs ordering.prices.modify_sent (modify alone is the cart); a manager's PIN is + recorded as the approver. +- `orders.price_change_reason`: a typed price needs a reason; the counter's % discount doesn't. +- Every change is one manual_price event (before → after, quantity, who, stage, reason) and a + PRICE_CHANGED audit row; only holders of ordering.prices.view_changes see them. +""" +import pytest + +from conftest import TEST_PIN +from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures) +from tests.test_order_lines import items_of, open_order +from tests.test_pos import burger_line, menu, on_shift, till # noqa: F401 (fixtures) +from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures) +from tests.test_waiter_keys import shop # noqa: F401 (fixture) + + +@pytest.fixture(autouse=True) +def _no_printing(monkeypatch): + import routers.orders as orders + monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: []) + + +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 manual_events(db, order_id=None): + from models.pricing import PriceEventLog + db.expire_all() + q = db.query(PriceEventLog).filter(PriceEventLog.event_type == "manual_price") + if order_id is not None: + q = q.filter(PriceEventLog.order_id == order_id) + return q.order_by(PriceEventLog.id).all() + + +def test_a_sent_line_changed_by_hand_is_recorded(client, db, shop, login): + o, item = shop["order"], shop["items"][0] + item.kds_status = "served" + db.commit() + h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter") + r = client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, + json={"price_adjustment": -1.5, "reason": " regular customer "}) + assert r.status_code == 200, r.text + [ev] = manual_events(db, o.id) + assert (ev.order_item_id, ev.price_before, ev.price_after, ev.delta_amount) == (item.id, 4.0, 2.5, -1.5) + assert ev.stage == "served" and ev.quantity == 1 and ev.waiter_note == "regular customer" and ev.approved_by_user_id is None + # a second change records from the changed price, the first stays + r = client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": 0}) + assert r.status_code == 200 + evs = manual_events(db, o.id) + assert [(e.price_before, e.price_after) for e in evs] == [(4.0, 2.5), (2.5, 4.0)] + from models.order import OrderAuditLog + assert db.query(OrderAuditLog).filter(OrderAuditLog.order_id == o.id, OrderAuditLog.event_type == "PRICE_CHANGED").count() == 2 + + +def test_the_venue_switch(client, db, shop, login): + o, item = shop["order"], shop["items"][0] + url = f"/api/orders/{o.id}/items/{item.id}/price-adjust" + boss = login(shop["owner"]) + setting(db, "orders.price_change", "before_sending") + assert err(client.patch(url, headers=boss, json={"price_adjustment": -1})) == "order.price_change_sent_off" + setting(db, "orders.price_change", "off") + assert err(client.patch(url, headers=boss, json={"price_adjustment": -1})) == "order.price_change_off" + setting(db, "orders.price_change", "anytime") + assert client.patch(url, headers=boss, json={"price_adjustment": -1}).status_code == 200 + assert len(manual_events(db, o.id)) == 1 + + +def test_a_reason_when_the_venue_asks(client, db, shop, login): + o, item = shop["order"], shop["items"][0] + url = f"/api/orders/{o.id}/items/{item.id}/price-adjust" + h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter") + setting(db, "orders.price_change_reason", "true") + assert err(client.patch(url, headers=h, json={"price_adjustment": -1})) == "order.price_reason_required" + assert err(client.patch(url, headers=h, json={"price_adjustment": -1, "reason": " "})) == "order.price_reason_required" + assert client.patch(url, headers=h, json={"price_adjustment": -1, "reason": "Burnt a bit"}).status_code == 200 + assert manual_events(db, o.id)[0].waiter_note == "Burnt a bit" + + +def test_a_managers_pin_is_the_approver(client, db, shop, make_user, login): + o, item = shop["order"], shop["items"][0] + boss = make_user(role="owner") + approved = client.post("/api/access/override", headers=shop["h"], + json={"key": "ordering.prices.modify_sent", "username": boss.username, "pin": TEST_PIN}) + assert approved.status_code == 200, approved.text + h = dict(shop["h"], **{"X-Xenia-Override": approved.json()["override_token"]}) + assert client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": 1}).status_code == 200 + [ev] = manual_events(db, o.id) + assert ev.approved_by_user_id == boss.id and ev.applied_by_user_id == shop["waiter"].id + + +def test_a_price_typed_in_the_cart(client, db, menu, phone, floor, make_user, login): + oid = open_order(client, phone["h"], floor["t1"]) + line = {"product_id": menu["coffee"].id, "quantity": 2, "price_adjustment": -0.5, "price_reason": "Friend of the house"} + from models.user import WaiterZone + w = make_user(role="waiter", add=("ordering.prices.modify",)) + db.add(WaiterZone(waiter_id=w.id, group_id=None)) + db.commit() + h = login(w, "waiter") + r = client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [line]}) + assert r.status_code == 200, r.text + [item] = items_of(db, oid) + [ev] = manual_events(db, oid) + assert ev.order_item_id == item.id and ev.stage == "cart" and ev.quantity == 2 + assert (ev.price_before, ev.price_after) == (item.unit_price, item.unit_price - 0.5) and ev.waiter_note == "Friend of the house" + # the venue asks for a reason: a typed price without one is refused, nothing is added + setting(db, "orders.price_change_reason", "true") + assert err(client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [{**line, "price_reason": None}]})) == "order.price_reason_required" + assert len(items_of(db, oid)) == 1 + setting(db, "orders.price_change", "off") + assert err(client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [line]})) == "order.price_change_off" + + +def test_the_counters_discount_is_recorded_without_a_reason(client, db, menu, pair, make_user): + from core.timeutil import business_date_of, utcnow + from models.business_day import BusinessDay + from models.shift import WaiterShift + from tests.test_live import terminal_login + token, _ = pair("pos_counter", "Till 2") + boss = make_user(role="owner") + h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"} + day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() or BusinessDay( + status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id) + db.add(day) + db.flush() + db.add(WaiterShift(waiter_id=boss.id, business_day_id=day.id)) + db.commit() + setting(db, "orders.price_change_reason", "true") + r = client.post("/api/pos/sales", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "discount_pct": 10}], "payments": [{"method": "card"}]}) + assert r.status_code == 201, r.text + [ev] = manual_events(db, r.json()["order_id"]) + assert ev.stage == "cart" and ev.waiter_note == "−10 %" and ev.delta_amount < 0 + + +def test_only_holders_see_the_changes(client, db, shop, make_user, login): + o, item = shop["order"], shop["items"][0] + h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter") + client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": -1, "reason": "x"}) + seer = login(make_user(role="store_manager")) + blind = login(make_user(role="store_manager", remove=("ordering.prices.view_changes",))) + assert [e["event_type"] for e in client.get(f"/api/pricing/events/order/{o.id}", headers=seer).json()] == ["manual_price"] + assert client.get(f"/api/pricing/events/order/{o.id}", headers=blind).json() == [] + got = client.get(f"/api/orders/{o.id}/price-changes", headers=seer).json() + assert len(got) == 1 and got[0]["before"] == 4.0 and got[0]["after"] == 3.0 and got[0]["reason"] == "x" and got[0]["product_name"] + assert client.get(f"/api/orders/{o.id}/price-changes", headers=blind).status_code == 403 + rep = client.get(f"/api/reports/price-changes?business_day_id={o.business_day_id}" if o.business_day_id else + "/api/reports/price-changes", headers=seer).json() + assert rep["count"] >= 1 and rep["total_value"] <= -1.0 and rep["by_person"][0]["count"] >= 1 + assert client.get("/api/reports/price-changes", headers=blind).status_code == 403 + + +def test_combining_lines_keeps_their_changes(client, db, shop, login): + o, items = shop["order"], shop["items"] + h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter") + for it in items[:2]: + assert client.patch(f"/api/orders/{o.id}/items/{it.id}/price-adjust", headers=h, json={"price_adjustment": -1}).status_code == 200 + r = client.post(f"/api/orders/{o.id}/items/combine", headers=h, json={"item_ids": [items[0].id, items[1].id]}) + assert r.status_code == 200, r.text + assert {e.order_item_id for e in manual_events(db, o.id)} == {items[0].id} + assert len(manual_events(db, o.id)) == 2 diff --git a/local_backend/tests/test_waiter_keys.py b/local_backend/tests/test_waiter_keys.py index 505063b..10ac0ff 100644 --- a/local_backend/tests/test_waiter_keys.py +++ b/local_backend/tests/test_waiter_keys.py @@ -98,10 +98,13 @@ def test_revert_payment_is_a_key_a_manager_can_approve(client, db, shop): def test_price_change_needs_only_the_key_no_venue_switch(client, shop, login): + """A sent line's price: ordering.prices.modify_sent since 6F.3 (modify alone is for the cart).""" o, item = shop["order"], shop["items"][0] url = f"/api/orders/{o.id}/items/{item.id}/price-adjust" assert err(client.patch(url, headers=shop["h"], json={"price_adjustment": -1})) == "access.override_possible" h = login(shop["new_waiter"](add=("ordering.prices.modify",)), client="waiter") + assert err(client.patch(url, headers=h, json={"price_adjustment": -1})) == "access.override_possible" + h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter") r = client.patch(url, headers=h, json={"price_adjustment": -1}) assert r.status_code == 200, r.text diff --git a/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx b/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx index 0c475e9..c7a5e7b 100644 --- a/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx +++ b/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx @@ -4,14 +4,14 @@ // table flags, quick messages to the staff, and sending the digital menu to the cloud now. // Each part shows only with its app on. Dropped from v1: "automatic store schedule" (its switches // were kept in the browser only and nothing ever read them). -import { useState } from 'react' +import { useId, useState } from 'react' import { useMutation } from '@tanstack/react-query' import toast from 'react-hot-toast' import { ArrowDown, ArrowUp, Plus, RefreshCw, Trash2 } from 'lucide-react' import { useModule } from '@xenia/access' import { errorMessage } from '@xenia/api' import { useTranslation } from '@xenia/i18n' -import { Button, Columns, IconButton, InfoTip, Input, Spinner, Switch } from '@xenia/ui' +import { Button, Columns, IconButton, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui' import client from '../../../api/client' import QuickMessages from './QuickMessages' import RolePermissions from './RolePermissions' @@ -64,11 +64,36 @@ function OrderingSettings() { {s.get('orders.courses_enabled') === 'true' && } - + + ) } +/** Prices changed by hand (6F.3): the venue's switch, the reason, the quick reasons. Who may: the + * keys ordering.prices.modify / modify_sent ("What each role may do", a person's permissions). */ +function PriceChangeSettings({ s }) { + const { t } = useTranslation('manager') + const p = k => t(`settings.prices.${k}`) + const id = useId() + const reasonOn = s.get('orders.price_change_reason', 'false') === 'true' + return ( + + + setEdits(x => ({ ...x, [i]: e.target.value }))} + setEdits(x => ({ ...x, [i]: e.target.value }))} onBlur={() => { if (edits[i] != null && edits[i] !== n) save(notes.map((x, j) => (j === i ? edits[i] : x))); setEdits({}) }} /> save(notes.filter((_, j) => j !== i))}> ))}
- setTyped(e.target.value)} - onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid="quick-note-new" /> - + setTyped(e.target.value)} + onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid={`${newTestId}-new`} /> +
) diff --git a/manager_dashboard/src/pages/orders/OrderHistory.jsx b/manager_dashboard/src/pages/orders/OrderHistory.jsx index 7cebf52..6718a05 100644 --- a/manager_dashboard/src/pages/orders/OrderHistory.jsx +++ b/manager_dashboard/src/pages/orders/OrderHistory.jsx @@ -59,6 +59,8 @@ export function PriceEventList({ events }) { {(ev.modifier_name || ev.deal_name) && {ev.modifier_name || ev.deal_name}} {ev.applied_by_username && {t('orders.history.by', { name: ev.applied_by_username })}} + {ev.approved_by_username && {t('orders.history.approvedBy', { name: ev.approved_by_username })}} + {ev.stage && {t(`orders.history.stage.${ev.stage}`)}} {ev.delta_amount != null && ( {formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })} diff --git a/manager_dashboard/src/pages/orders/OrderLines.jsx b/manager_dashboard/src/pages/orders/OrderLines.jsx index 7a84bda..3fcd27c 100644 --- a/manager_dashboard/src/pages/orders/OrderLines.jsx +++ b/manager_dashboard/src/pages/orders/OrderLines.jsx @@ -15,7 +15,7 @@ import { Pill } from '../overview/parts' import { lineAmount, lineDetails, nameOf, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic' const STATUS_TONE = { paid: 'success', cancelled: 'danger', tabbed: 'info', closed: 'warning' } -const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink' } +const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink', manual_price: 'text-warning-ink' } export default function OrderLines({ order, open, priceEvents, onPay, onChanged }) { const { t } = useTranslation('manager') @@ -79,6 +79,12 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged {ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)} {ev.delta_amount != null && {formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}} + {ev.event_type === 'manual_price' && ( + + {formatMoney(ev.price_before)} → {formatMoney(ev.price_after)} + {ev.applied_by_username && ` · ${ev.applied_by_username}`}{ev.waiter_note && ` · ${ev.waiter_note}`} + + )} ))} diff --git a/manager_dashboard/src/pages/overview/OrderDialog.jsx b/manager_dashboard/src/pages/overview/OrderDialog.jsx index c71db6e..f5127e0 100644 --- a/manager_dashboard/src/pages/overview/OrderDialog.jsx +++ b/manager_dashboard/src/pages/overview/OrderDialog.jsx @@ -142,7 +142,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull }) {evs.map((ev, i) => (
- {ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)} + {ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}{ev.event_type === 'manual_price' && ev.waiter_note ? ` · ${ev.waiter_note}` : ''} {ev.delta_amount != null && {formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}} {ev.price_after != null && → {formatMoney(ev.price_after)}}
diff --git a/manager_dashboard/src/pages/reports/misc/MiscReport.jsx b/manager_dashboard/src/pages/reports/misc/MiscReport.jsx index 4fc1569..2230b06 100644 --- a/manager_dashboard/src/pages/reports/misc/MiscReport.jsx +++ b/manager_dashboard/src/pages/reports/misc/MiscReport.jsx @@ -2,6 +2,7 @@ // cancelled line (what, how much, who sent it, who cancelled it, why) and every discount given // (on what, how much, by whom, why), with totals per person; exports for Excel. import { useState } from 'react' +import { useCan } from '@xenia/access' import { useFormat, useTranslation } from '@xenia/i18n' import client from '../../../api/client' import { useLiveQuery } from '../../../live/useLiveQuery' @@ -12,9 +13,11 @@ import { defaultPeriod, periodParams, periodSlug } from '../kit/reportLogic' export default function MiscReport() { const { t } = useTranslation('manager') + const seesChanges = useCan('ordering.prices.view_changes') const tabs = [ { id: 'cancellations', label: t('reports.misc.cancellations'), Component: CancellationsTab }, { id: 'discounts', label: t('reports.misc.discounts'), Component: DiscountsTab }, + ...(seesChanges ? [{ id: 'price-changes', label: t('reports.misc.priceChanges'), Component: PriceChangesTab }] : []), ] return } @@ -102,3 +105,46 @@ function DiscountsTab() { ) } + + +/** Prices changed by hand (6F.3): each change, before → after, its value for the line's quantity, + * where (cart / sent / served), who, the approving manager, why; totals per person. */ +function PriceChangesTab() { + const { t } = useTranslation('manager') + const fmt = useFormat() + const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday())) + const params = periodParams(period) + const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-price-changes', params], queryFn: () => client.get('/api/reports/price-changes', { params }).then(r => r.data) }) + const rows = data?.changes ?? [] + const columns = [ + { key: 'at', label: t('reports.misc.when'), render: c => fmt.formatDateTime(c.at, 'datetimeShort') }, + { key: 'product_name', label: t('reports.prod.product'), render: c => {c.product_name} }, + { key: 'table_name', label: t('reports.place'), render: c => c.table_name || t('reports.noTable') }, + { key: 'before', label: t('reports.misc.priceWas'), align: 'right', render: c => fmt.formatMoney(c.before) }, + { key: 'after', label: t('reports.misc.priceNow'), align: 'right', render: c => fmt.formatMoney(c.after) }, + { key: 'value', label: t('reports.misc.value'), align: 'right', render: c => {fmt.formatMoney(c.value, { signDisplay: 'exceptZero' })} }, + { key: 'stage', label: t('reports.misc.stage'), render: c => (c.stage ? t(`orders.history.stage.${c.stage}`) : '') }, + { key: 'by', label: t('reports.misc.changedBy'), render: c => c.by || '' }, + { key: 'approved_by', label: t('reports.misc.approvedBy'), render: c => c.approved_by || '' }, + { key: 'reason', label: t('reports.misc.reason'), render: c => c.reason || '' }, + ] + return ( +
+ } /> + {isPending ? : error ? : (<> +
+ + +
+ {data.by_person.length > 1 && ( + + fmt.formatMoney(v, { signDisplay: 'exceptZero' })} rows={data.by_person.map(p => ({ key: p.user_id ?? '—', label: p.name ?? '—', value: p.total_value, sub: t('reports.misc.changesCount', { count: p.count }) }))} /> + + )} + + + + )} + + ) +} diff --git a/packages/api/src/lines.js b/packages/api/src/lines.js index e58aa93..b5970ff 100644 --- a/packages/api/src/lines.js +++ b/packages/api/src/lines.js @@ -1,7 +1,7 @@ // Order lines: what POST /api/orders/{id}/items and POST /api/orders/quote take (plan step 4.4). // // An app never sends a price. A line says what was chosen, by id (sub-choices by name): -// { product_id, quantity, notes?, course_id?, price_adjustment?, is_service_item?, +// { product_id, quantity, notes?, course_id?, price_adjustment?, price_reason?, is_service_item?, // quick: [{id, qty?}], options: [{id, qty?, subs: [name]}], // prefs: [{set_id, choices: [{id, qty?, sub?}], shared?}], removed: [ingredient_id] } // and the server prices it (local_backend/services/pos_cart.py; the counter POS builds the @@ -108,6 +108,7 @@ export function wireLine(item, product) { if (item.notes?.trim()) line.notes = item.notes.trim() if (item.course_id != null) line.course_id = item.course_id if (item.price_adjustment) line.price_adjustment = cents(item.price_adjustment) + if (item.price_adjustment && item.price_reason) line.price_reason = String(item.price_reason).slice(0, 200) // 6F.3 if (item.is_service_item) line.is_service_item = true return line } diff --git a/packages/api/tests/lines.test.mjs b/packages/api/tests/lines.test.mjs index 2c0d30c..5b31c34 100644 --- a/packages/api/tests/lines.test.mjs +++ b/packages/api/tests/lines.test.mjs @@ -64,6 +64,12 @@ test('a price changed by hand and a service item travel with the line; nothing e assert.deepEqual(line, { product_id: 1, quantity: 1, price_adjustment: -1, is_service_item: true }) }) +test('the reason for a price changed by hand travels with it, never alone (6F.3)', () => { + assert.deepEqual(wireLine({ product_id: 1, quantity: 1, price_adjustment: -0.5, price_reason: 'Regular customer' }, burger), + { product_id: 1, quantity: 1, price_adjustment: -0.5, price_reason: 'Regular customer' }) + assert.deepEqual(wireLine({ product_id: 1, quantity: 1, price_reason: 'nothing changed' }, burger), { product_id: 1, quantity: 1 }) +}) + test('what is not on the menu any more is refused, not dropped', () => { assert.throws(() => lineFromOptions(burger, { selected_options: [e('extra', 99, 'Truffle')] }), LineError) assert.throws(() => lineFromOptions(burger, { selected_options: [e('quick', null, 'Bacon')] }), LineError) diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 77e8864..7ea98a9 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -102,7 +102,10 @@ "discounts_off": "Οι εκπτώσεις είναι απενεργοποιημένες σε αυτό το κατάστημα.", "no_customer": "Ορίστε πρώτα πελάτη στην παραγγελία.", "item_not_tabbable": "Αυτό το είδος είναι ήδη {{status}}: δεν μπαίνει σε καρτέλα.", - "product_unavailable": "Το προϊόν {{product_id}} δεν είναι διαθέσιμο." + "product_unavailable": "Το προϊόν {{product_id}} δεν είναι διαθέσιμο.", + "price_change_off": "Η αλλαγή τιμής με το χέρι είναι κλειστή σε αυτό το κατάστημα.", + "price_change_sent_off": "Οι τιμές αλλάζουν μόνο πριν σταλούν τα είδη.", + "price_reason_required": "Γράψτε γιατί αλλάζει η τιμή." }, "notification": { "not_found": "Η ειδοποίηση {{notification_id}} δεν βρέθηκε." diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 6c793cc..fd121ea 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -739,6 +739,25 @@ "spoof": "Προσποιητή εκτύπωση", "spoofHint": "Κάθε εκτύπωση απορρίπτεται· οι εφαρμογές συμπεριφέρονται σαν να τυπώθηκε.", "spoofOn": "Ενεργό: οι εκτυπωτές δεν τυπώνουν τίποτα." + }, + "prices": { + "title": "Τιμές που αλλάζουν με το χέρι", + "intro": "Πότε το προσωπικό γράφει δική του τιμή σε μια γραμμή και αν πρέπει να πει γιατί. Κάθε αλλαγή κρατιέται: ποιος, πότε, από πόσο σε πόσο, γιατί.", + "when": "Το προσωπικό αλλάζει τιμή", + "whenHint": "Ποιος: «Τι επιτρέπεται σε κάθε ρόλο» και τα δικαιώματα κάθε ατόμου.", + "whenTip": "Ποτέ: κανείς δεν γράφει τιμή, ούτε οι ιδιοκτήτες. Πριν την αποστολή: μόνο στο καλάθι, πριν πάει η παραγγελία στην κουζίνα. Οποτεδήποτε: και σε γραμμή που έχει σταλεί ή σερβιριστεί (θέλει δικό του δικαίωμα, «ήδη σταλμένο ή σερβιρισμένο»).", + "modes": { + "off": "Ποτέ", + "before_sending": "Μόνο πριν την αποστολή", + "anytime": "Οποτεδήποτε" + }, + "reason": "Να ζητείται αιτία", + "reasonHint": "Μια τιμή που αλλάζει με το χέρι δεν αποθηκεύεται χωρίς αιτία.", + "reasonTip": "Η αιτία κρατιέται με την αλλαγή και φαίνεται στο ιστορικό της παραγγελίας και στις Αναφορές → Ακυρώσεις, εκπτώσεις και αλλαγές τιμών. Οι εκπτώσεις % του ταμείου δεν ζητούν: η έκπτωση λέει τι είναι.", + "reasons": "Γρήγορες αιτίες", + "reasonsHint": "Με ένα πάτημα· το προσωπικό μπορεί και να γράψει δική του. Καμία: οι έτοιμες.", + "reasonItem": "Γρήγορη αιτία", + "newReason": "Νέα γρήγορη αιτία…" } }, "logs": { @@ -2290,7 +2309,8 @@ "event": { "waiter_discount": "Έκπτωση", "free_item_added": "Δωρεάν", - "modifier_applied": "Τροποποιητής" + "modifier_applied": "Τροποποιητής", + "manual_price": "Τιμή με το χέρι" } }, "orderStatus": { @@ -3368,7 +3388,9 @@ "PAYMENT_OFFLINE": "Πληρωμή (offline)", "ORDER_CLOSED": "Κλείσιμο", "ORDER_CANCELLED": "Ακύρωση", - "ITEM_CANCELLED": "Ακύρωση γραμμής" + "ITEM_CANCELLED": "Ακύρωση γραμμής", + "PRICE_CHANGED": "Αλλαγή τιμής", + "PRICE_SET_BY_HAND": "Τιμή με το χέρι (εγκρίθηκε)" }, "price": { "modifier_applied": "Κανόνας τιμής", @@ -3377,7 +3399,14 @@ "deal_offer_accepted": "Προσφορά (αποδεκτή)", "deal_offer_dismissed": "Προσφορά (απορρίφθηκε)", "waiter_discount": "Έκπτωση", - "free_item_added": "Δωρεάν προϊόν" + "free_item_added": "Δωρεάν προϊόν", + "manual_price": "Τιμή με το χέρι" + }, + "approvedBy": "με έγκριση {{name}}", + "stage": { + "cart": "πριν την αποστολή", + "sent": "μετά την αποστολή", + "served": "μετά το σερβίρισμα" } }, "add": { @@ -4069,7 +4098,7 @@ } }, "misc": { - "title": "Ακυρώσεις και εκπτώσεις", + "title": "Ακυρώσεις, εκπτώσεις και αλλαγές τιμών", "cancellations": "Ακυρώσεις", "discounts": "Εκπτώσεις", "when": "Πότε", @@ -4093,7 +4122,18 @@ "discountTotal": "Σύνολο εκπτώσεων", "alreadyOff": "έχουν ήδη αφαιρεθεί από τα έσοδα", "times_one": "{{count}} φορά", - "times_other": "{{count}} φορές" + "times_other": "{{count}} φορές", + "priceChanges": "Αλλαγές τιμών", + "priceWas": "Ήταν", + "priceNow": "Έγινε", + "stage": "Πότε", + "changedBy": "Άλλαξε από", + "approvedBy": "Ενέκρινε", + "changes": "Αλλαγές τιμών", + "changesValue": "Διαφορά", + "changesValueTip": "Τι πρόσθεσαν (+) ή αφαίρεσαν (−) οι αλλαγές, για την ποσότητα κάθε γραμμής τη στιγμή της αλλαγής.", + "changesCount_one": "{{count}} αλλαγή", + "changesCount_other": "{{count}} αλλαγές" }, "tech": { "title": "Τεχνικά", diff --git a/packages/i18n/locales/el/modules.json b/packages/i18n/locales/el/modules.json index e476c8e..0eeaf17 100644 --- a/packages/i18n/locales/el/modules.json +++ b/packages/i18n/locales/el/modules.json @@ -454,7 +454,9 @@ "cancel": "Ακύρωση ειδών που έχουν σταλεί" }, "prices": { - "modify": "Αλλαγή τιμής είδους" + "modify": "Αλλαγή τιμής είδους πριν σταλεί", + "modify_sent": "Αλλαγή τιμής είδους που έχει ήδη σταλεί ή σερβιριστεί", + "view_changes": "Προβολή τιμών που άλλαξαν με το χέρι (ποιος, πότε, γιατί)" }, "business_day": { "manage": "Άνοιγμα και κλείσιμο της εργάσιμης ημέρας" diff --git a/packages/i18n/locales/el/waiter.json b/packages/i18n/locales/el/waiter.json index 1694245..560c907 100644 --- a/packages/i18n/locales/el/waiter.json +++ b/packages/i18n/locales/el/waiter.json @@ -528,7 +528,8 @@ "merge": "Σφάλμα συγχώνευσης", "moveItems": "Σφάλμα μεταφοράς αντικειμένων", "flags": "Σφάλμα αποθήκευσης σημαιών", - "combine": "Σφάλμα συνδυασμού" + "combine": "Σφάλμα συνδυασμού", + "price": "Η τιμή δεν άλλαξε." }, "openOrder": "Άνοιγμα Παραγγελίας", "noPaid": "Δεν υπάρχουν πληρωμένα αντικείμενα", @@ -857,5 +858,27 @@ "accepted": "Στάλθηκε στην κουζίνα", "declined": "Απορρίφθηκε", "note": "Σημείωση: {{note}}" + }, + "price": { + "reason": "Γιατί αλλάζει η τιμή;", + "reasonMissing": "Γράψτε γιατί αλλάζει η τιμή", + "reasons": { + "regular": "Τακτικός πελάτης", + "mistake": "Λάθος τιμή στο μενού", + "compensation": "Αποζημίωση για πρόβλημα", + "manager": "Απόφαση υπευθύνου", + "happyHour": "Προσφορά ημέρας", + "other": "Άλλο" + }, + "history": "Ιστορικό τιμής", + "historySub": "Ποιος την άλλαξε, πότε και γιατί", + "historyNone": "Καμία αλλαγή τιμής σε αυτή τη γραμμή.", + "historyFailed": "Το ιστορικό τιμής δεν φόρτωσε.", + "stage": { + "cart": "πριν την αποστολή", + "sent": "μετά την αποστολή", + "served": "μετά το σερβίρισμα" + }, + "approvedBy": "με έγκριση {{name}}" } } diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index ee1aea3..ba4b8af 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -102,7 +102,10 @@ "discounts_off": "Discounts are turned off for this venue.", "no_customer": "Give the order a customer first.", "item_not_tabbable": "This item is already {{status}}: it can't go on a tab.", - "product_unavailable": "Product {{product_id}} isn't available." + "product_unavailable": "Product {{product_id}} isn't available.", + "price_change_off": "Changing prices by hand is turned off for this venue.", + "price_change_sent_off": "Prices can only be changed before the items are sent.", + "price_reason_required": "Say why the price changes." }, "notification": { "not_found": "Notification {{notification_id}} not found." diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 5d3b788..acaa11e 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -739,6 +739,25 @@ "spoof": "Pretend to print", "spoofHint": "Every print job is dropped; the apps behave as if it printed.", "spoofOn": "On: the printers print nothing." + }, + "prices": { + "title": "Prices changed by hand", + "intro": "When staff may type a line's own price, and whether they must say why. Every change is kept: who, when, from what to what, why.", + "when": "Staff may change a price", + "whenHint": "Who may: \"What each role may do\" and each person's permissions.", + "whenTip": "Never: nobody types a price, owners included. Before sending: only in the cart, before the order goes to the kitchen. Any time: also a line already sent or served (needs its own permission, \"already sent or served\").", + "modes": { + "off": "Never", + "before_sending": "Before sending only", + "anytime": "Any time" + }, + "reason": "Ask for a reason", + "reasonHint": "A price changed by hand can't be saved without one.", + "reasonTip": "The reason is kept with the change and shown in the order's history and in Reports → Cancellations, discounts and price changes. The counter's % discounts don't ask: the discount says what it is.", + "reasons": "Quick reasons", + "reasonsHint": "Offered with one tap; staff can still type their own. None: the built-in ones.", + "reasonItem": "Quick reason", + "newReason": "A new quick reason…" } }, "logs": { @@ -2290,7 +2309,8 @@ "event": { "waiter_discount": "Discount", "free_item_added": "Free", - "modifier_applied": "Price change" + "modifier_applied": "Price change", + "manual_price": "Price changed by hand" } }, "orderStatus": { @@ -3368,7 +3388,9 @@ "PAYMENT_OFFLINE": "Payment (offline)", "ORDER_CLOSED": "Closed", "ORDER_CANCELLED": "Cancelled", - "ITEM_CANCELLED": "Line cancelled" + "ITEM_CANCELLED": "Line cancelled", + "PRICE_CHANGED": "Price changed", + "PRICE_SET_BY_HAND": "Price set by hand (approved)" }, "price": { "modifier_applied": "Price rule", @@ -3377,7 +3399,14 @@ "deal_offer_accepted": "Deal accepted", "deal_offer_dismissed": "Deal declined", "waiter_discount": "Discount", - "free_item_added": "Free item" + "free_item_added": "Free item", + "manual_price": "Price changed by hand" + }, + "approvedBy": "approved by {{name}}", + "stage": { + "cart": "before sending", + "sent": "after sending", + "served": "after serving" } }, "add": { @@ -4069,7 +4098,7 @@ } }, "misc": { - "title": "Cancellations and discounts", + "title": "Cancellations, discounts and price changes", "cancellations": "Cancellations", "discounts": "Discounts", "when": "When", @@ -4093,7 +4122,18 @@ "discountTotal": "Total off", "alreadyOff": "already taken off the revenue", "times_one": "{{count}} time", - "times_other": "{{count}} times" + "times_other": "{{count}} times", + "priceChanges": "Price changes", + "priceWas": "Was", + "priceNow": "Became", + "stage": "When", + "changedBy": "Changed by", + "approvedBy": "Approved by", + "changes": "Prices changed", + "changesValue": "Difference", + "changesValueTip": "What the changes added (+) or took off (−), for each line's quantity at the time of the change.", + "changesCount_one": "{{count}} change", + "changesCount_other": "{{count}} changes" }, "tech": { "title": "Technical", diff --git a/packages/i18n/locales/en/modules.json b/packages/i18n/locales/en/modules.json index 54ff792..967a58e 100644 --- a/packages/i18n/locales/en/modules.json +++ b/packages/i18n/locales/en/modules.json @@ -454,7 +454,9 @@ "cancel": "Cancel items already sent" }, "prices": { - "modify": "Change an item's price" + "modify": "Change an item's price before it is sent", + "modify_sent": "Change the price of an item already sent or served", + "view_changes": "See prices changed by hand (who, when, why)" }, "business_day": { "manage": "Open and close the business day" diff --git a/packages/i18n/locales/en/waiter.json b/packages/i18n/locales/en/waiter.json index 5d6d6b3..59e0d27 100644 --- a/packages/i18n/locales/en/waiter.json +++ b/packages/i18n/locales/en/waiter.json @@ -528,7 +528,8 @@ "merge": "Couldn't merge", "moveItems": "Couldn't move the items", "flags": "Couldn't save the flags", - "combine": "Couldn't combine the lines" + "combine": "Couldn't combine the lines", + "price": "The price didn't change." }, "openOrder": "Open an order", "noPaid": "No paid items", @@ -857,5 +858,27 @@ "accepted": "Sent to the kitchen", "declined": "Declined", "note": "Note: {{note}}" + }, + "price": { + "reason": "Why does the price change?", + "reasonMissing": "Say why the price changes", + "reasons": { + "regular": "Regular customer", + "mistake": "Wrong price on the menu", + "compensation": "Making up for a problem", + "manager": "Manager's decision", + "happyHour": "Offer of the day", + "other": "Other" + }, + "history": "Price history", + "historySub": "Who changed it, when and why", + "historyNone": "No price changes on this line.", + "historyFailed": "The price history didn't load.", + "stage": { + "cart": "before sending", + "sent": "after sending", + "served": "after serving" + }, + "approvedBy": "approved by {{name}}" } } diff --git a/terminal/src/apps/pos/CartLine.jsx b/terminal/src/apps/pos/CartLine.jsx index a485d6c..7784d83 100644 --- a/terminal/src/apps/pos/CartLine.jsx +++ b/terminal/src/apps/pos/CartLine.jsx @@ -30,9 +30,9 @@ export default function CartLine({ line, priced, product, canDiscount, onQty, on onQty(line.quantity + step)}> {priced && line.quantity !== 1 && {t('pos.each', { price: formatMoney(priced.unit_price) })}} - onDiscount(Number(e.target.value))} aria-label={t('pos.discount')} title={canDiscount ? undefined : t('pos.discountNeedsApproval')} data-testid="line-discount" className="w-36" - options={DISCOUNTS.map(d => ({ value: String(d), label: d ? `−${d}%` : t('pos.noDiscount') }))} /> + options={DISCOUNTS.map(d => ({ value: String(d), label: d ? `−${d}%` : t('pos.noDiscount') }))} />} {priced?.discount ? {t('pos.discountLine', { pct: priced.discount_pct, amount: formatMoney(priced.discount) })} : null} diff --git a/terminal/src/apps/pos/PosScreen.jsx b/terminal/src/apps/pos/PosScreen.jsx index bfa26ae..85b7432 100644 --- a/terminal/src/apps/pos/PosScreen.jsx +++ b/terminal/src/apps/pos/PosScreen.jsx @@ -62,7 +62,9 @@ function Counter({ menu, t }) { const [tableCart, setTableCart] = useState([]) const [dialog, setDialog] = useState(null) // product const tables = useTables() - const canDiscount = useCan('ordering.prices.modify') + // a discount is a price changed in the cart (6F.3): none when the venue turned that off + const mayDiscount = useCan('ordering.prices.modify') + const canDiscount = menu.settings.price_change === 'off' ? null : mayDiscount // null: no discount at all const toast = useToast() const onlineModule = useModule('connect_orders') const handlesOnline = useCan('connect_orders.manage') diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index c2bd5f7..60a1236 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -737,6 +737,20 @@ try { let notesNow = [] for (let i = 0; i < 30 && !notesNow.includes('E2E: well done'); i++) { await sleep(150); notesNow = JSON.parse(await settingValue2('orders.quick_notes') || '[]') } r.check(`${st6} Operation: a quick note added`, notesNow.includes('E2E: well done'), JSON.stringify(notesNow)) + // 6F.3: prices changed by hand: the venue's switch, then the reason and its quick reasons + await page.getByTestId('setting-orders.price_change').selectOption('before_sending') + let pcMode = '' + for (let i = 0; i < 30 && pcMode !== 'before_sending'; i++) { await sleep(150); pcMode = await settingValue2('orders.price_change') } + await page.getByTestId('settings-price-changes').getByRole('switch').first().click() + await page.getByTestId('price-reason-new').fill('E2E: birthday') + await page.getByTestId('price-reason-add').click() + let reasonsNow = [] + for (let i = 0; i < 30 && !reasonsNow.includes('E2E: birthday'); i++) { await sleep(150); reasonsNow = JSON.parse(await settingValue2('orders.price_change_reasons') || '[]') } + r.check(`${st6} Operation: prices by hand "before sending only", a reason asked, a quick reason added`, + pcMode === 'before_sending' && await settingValue2('orders.price_change_reason') === 'true' && reasonsNow.includes('E2E: birthday')) + await page.getByTestId('setting-orders.price_change').selectOption('anytime') + await page.getByTestId('settings-price-changes').getByRole('switch').first().click() + await sleep(500) await page.getByTestId('flag-new').click() await page.getByTestId('flag-save').click() r.check(`${st6} a table flag needs a name`, (await page.getByTestId('flag-dialog').textContent()).includes('Enter a name')) @@ -1421,6 +1435,8 @@ try { await opens('/reports/misc', 'cancellations-count', 'Cancellations') await page.getByTestId('report-tab-discounts').click() r.check(`${rp} Discounts opens`, await page.getByTestId('report-period').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) + await page.getByTestId('report-tab-price-changes').click() + r.check(`${rp} Price changes opens (6F.3)`, await page.getByTestId('price-changes-count').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) await opens('/reports/technical', 'printing-total', 'Technical → Printing') await opens('/reports/prep-zones', 'report-period', 'Prep zones') await opens('/reports/expenses', 'expenses-total', 'Expenses') diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index c5176d9..8e27f7f 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -303,6 +303,50 @@ try { await a.getByTestId('menu-language-en').click() await waitFor(async () => (await navText()).includes('Tables'), 8000, 300) + // ── 6F.3: a sent line's price changed by hand, with the reason the venue asks for ────── + { + const mariaKeys = (await api('GET', `/api/waiters/${maria.id}/permissions`, { token: boss })).keys + await api('PUT', `/api/waiters/${maria.id}/permissions`, { token: boss, + body: { keys: [...new Set([...mariaKeys, 'ordering.prices.modify_sent', 'ordering.prices.view_changes'])] } }) + await setting(boss, 'orders.price_change_reason', 'true') + const tp = free.find(t => t.id !== t4.id && t.id !== t5.id && t.id !== (free.find(x => x.id !== t4.id && x.id !== t5.id)?.id)) || free[free.length - 1] + const op = await api('POST', '/api/orders/', { token: tokenA, body: { table_id: tp.id } }) + await api('POST', `/api/orders/${op.id}/items`, { token: tokenA, body: { lines: [{ product_id: plain.id, quantity: 1 }] } }) + await a.goto(`${APP}/tables/${tp.id}`) + await a.reload() // the keys were changed after sign-in: the bootstrap comes again + await a.locator('.order-item').first().waitFor({ timeout: 10_000 }) + await a.locator('.order-item').first().click() + await a.getByRole('button', { name: 'ACTIONS', exact: true }).last().click() + await a.getByText('Change the price').first().click({ timeout: 10_000 }) + await a.getByRole('button', { name: '-1 €' }).first().click() + r.check('6F.3: the venue asks why: the reason picker shows with a changed price', await shown(a, 'price-reason', 5000)) + await a.getByRole('button', { name: 'Apply' }).click() + await sleep(600) + const unchanged = (await api('GET', `/api/orders/${op.id}`, { token: boss })).items[0].price_adjustment || 0 + r.check('6F.3: without a reason nothing is saved', unchanged === 0 && await a.getByText('Say why the price changes').isVisible().catch(() => false)) + await a.getByText('Regular customer').first().click() + await a.getByRole('button', { name: 'Apply' }).click() + const changed = await waitFor(async () => { + const ev = (await api('GET', `/api/orders/${op.id}/price-changes`, { token: boss })) + return ev.length === 1 && ev[0] + }, 10_000, 500) + r.check('6F.3: saved with its reason, who and the stage', !!changed && Math.abs(changed.after - (changed.before - 1)) < 0.001 + && changed.reason === 'Regular customer' && changed.stage === 'sent' && changed.by_id === maria.id, JSON.stringify(changed)) + await a.goto(`${APP}/tables/${tp.id}`) + await a.locator('.order-item').first().waitFor({ timeout: 10_000 }) + await a.locator('.order-item').first().click() + await a.getByRole('button', { name: 'ACTIONS', exact: true }).last().click() + await a.getByText('Price history').first().click({ timeout: 10_000 }) + r.check('6F.3: the price history on the phone (who, from → to, why)', await shown(a, 'price-history-row', 8000) + && (await a.getByTestId('price-history-row').first().textContent()).includes('Regular customer')) + await a.keyboard.press('Escape').catch(() => {}) + await setting(boss, 'orders.price_change_reason', 'false') + await api('PUT', `/api/waiters/${maria.id}/permissions`, { token: boss, body: { keys: mariaKeys } }) + await setting(boss, 'orders.close_with_unpaid', 'true') + await api('POST', `/api/orders/${op.id}/close`, { token: boss }) + await setting(boss, 'orders.close_with_unpaid', 'false') + } + // ── 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 } }) diff --git a/waiter_pwa/src/components/OrderDrawer.jsx b/waiter_pwa/src/components/OrderDrawer.jsx index 944c7c9..401f30a 100644 --- a/waiter_pwa/src/components/OrderDrawer.jsx +++ b/waiter_pwa/src/components/OrderDrawer.jsx @@ -4,6 +4,9 @@ import useWaiterFavoritesStore from '../store/waiterFavoritesStore' import { assetUrl } from '../config/server' import { money } from '../i18n' import { parseNumber, useTranslation } from '@xenia/i18n' +import PriceReason from './PriceReason' +import { priceReasonText } from '../logic/priceRules' +import { usePriceRules } from '../hooks/usePriceRules' // ── Helpers ────────────────────────────────────────────────────────────────── @@ -815,7 +818,7 @@ function QuantityTab({ unitCfg, qty, setQty }) { const PRICE_DELTAS = [-5, -3, -2, -1, -0.5, -0.2, +0.2, +0.5, +1, +2, +3, +5] -function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) { +function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj, rules, reason, setReason, reasonMissing }) { const { t } = useTranslation('waiter') const [editing, setEditing] = useState(false) const [rawInput, setRawInput] = useState('') @@ -904,6 +907,8 @@ function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) { ))} + {/* 6F.3: the venue asks why a price changes */} + {rules?.reasonRequired && priceAdj !== 0 && } ) } @@ -1069,7 +1074,9 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt const itemFavorites = useWaiterFavoritesStore(s => s.itemFavorites) // A price set before sending needs the key itself (plan 4.3); the manager-approval path for // it comes with server-priced orders (4.4). After sending, the item's actions offer it. - const priceAdjAllowed = useCan('ordering.prices.modify') + // 6F.3: and the venue allows prices typed before sending (orders.price_change) + const priceRulesNow = usePriceRules() + const priceAdjAllowed = useCan('ordering.prices.modify') && priceRulesNow.inCart const preferenceSets = product?.preference_sets || [] const quickOptions = product?.quick_options || [] @@ -1136,6 +1143,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt const [sharedSubs, setSharedSubs] = useState({}) const [note, setNote] = useState('') const [priceAdj, setPriceAdj] = useState(0) + const [priceReason, setPriceReason] = useState({ choice: '', other: '' }) // 6F.3 const [addAttempted, setAddAttempted] = useState(false) const [courseId, setCourseId] = useState(initialState?.courseId ?? null) @@ -1153,6 +1161,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt setSharedSubs(initialState.sharedSubs ?? base.sharedSubs) setNote(initialState.note ?? '') setPriceAdj(initialState.priceAdj ?? 0) + setPriceReason(initialState.priceReason ?? { choice: '', other: '' }) setCourseId(initialState.courseId ?? null) } else { setQty(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1) @@ -1164,6 +1173,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt setSharedSubs(base.sharedSubs) setNote('') setPriceAdj(0) + setPriceReason({ choice: '', other: '' }) setCourseId(null) } setExpandedExtra(null) @@ -1265,6 +1275,12 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt const favTabAlert = favHasIncompletePref && (addAttempted || prefsHasMandatory) function handleAdd() { + const reasonTxt = priceAdj !== 0 ? priceReasonText(priceRulesNow, t, priceReason) : '' + if (priceAdj !== 0 && priceRulesNow.reasonRequired && !reasonTxt) { // 6F.3: why the price changes + setAddAttempted(true) + setActiveTab('price_adjust') + return + } if (!canAdd) { setAddAttempted(true) if (!allPrefsOk) { @@ -1341,8 +1357,9 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt removed_ingredients: removedNames, notes: note, price_adjustment: priceAdj !== 0 ? priceAdj : undefined, + price_reason: reasonTxt || undefined, course_id: courseId ?? undefined, - _drawerState: { qty, quickState, extrasState, removedState, prefs, subChoices, sharedSubs, note, priceAdj, courseId }, + _drawerState: { qty, quickState, extrasState, removedState, prefs, subChoices, sharedSubs, note, priceAdj, priceReason, courseId }, }) onClose() } @@ -1507,7 +1524,9 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt {activeTab === 'quantity' && isDecimal && } {activeTab === 'courses' && courses?.length > 0 && } {activeTab === 'notes' && } - {activeTab === 'price_adjust' && } + {activeTab === 'price_adjust' && } {activeTab === 'summary' && } diff --git a/waiter_pwa/src/components/PriceHistory.jsx b/waiter_pwa/src/components/PriceHistory.jsx new file mode 100644 index 0000000..6f42fe5 --- /dev/null +++ b/waiter_pwa/src/components/PriceHistory.jsx @@ -0,0 +1,49 @@ +// A line's price changes (plan 6F.3), for people with ordering.prices.view_changes: each change, +// from → to, where it happened (before sending / after sending / after serving), who, the +// manager who approved it, why. GET /api/orders/{id}/price-changes. +import { useEffect, useState } from 'react' +import { useFormat, useTranslation } from '@xenia/i18n' +import client from '../api/client' +import { apiError } from '../api/errors' + +export default function PriceHistory({ orderId, item, onClose }) { + const { t } = useTranslation('waiter') + const { formatDateTime, formatMoney } = useFormat() + const [rows, setRows] = useState(null) + const [error, setError] = useState('') + useEffect(() => { + let alive = true + client.get(`/api/orders/${orderId}/price-changes`) + .then(r => { if (alive) setRows(r.data.filter(c => c.item_id === item.id)) }) + .catch(err => { if (alive) setError(apiError(err, t('price.historyFailed'))) }) + return () => { alive = false } + }, [orderId, item.id, t]) + return ( +
+
e.stopPropagation()} data-testid="price-history"> +
+

{t('price.history')}

+

{item.product_name || item.product?.name}

+ {error &&

{error}

} + {!error && rows === null &&

…

} + {rows?.length === 0 &&

{t('price.historyNone')}

} +
+ {rows?.map(c => ( +
+
+ {formatMoney(c.before)} → {formatMoney(c.after)} + {formatMoney(c.delta, { signDisplay: 'exceptZero' })} +
+
+ {formatDateTime(c.at, 'datetimeShort')} · {t(`price.stage.${c.stage || 'cart'}`)}{c.by ? ` · ${c.by}` : ''} + {c.approved_by ? ` · ${t('price.approvedBy', { name: c.approved_by })}` : ''} +
+ {c.reason &&
{c.reason}
} +
+ ))} +
+ +
+
+ ) +} diff --git a/waiter_pwa/src/components/PriceReason.jsx b/waiter_pwa/src/components/PriceReason.jsx new file mode 100644 index 0000000..da6fcf7 --- /dev/null +++ b/waiter_pwa/src/components/PriceReason.jsx @@ -0,0 +1,20 @@ +// Why a price changes (plan 6F.3): the venue's quick reasons (or the built-in ones) or a typed one. +// Shown when the venue asks for a reason; the parent keeps { choice, other } and sends +// priceReasonText(rules, t, state) (logic/priceRules.js). +import { useTranslation } from '@xenia/i18n' +import { ReasonPicker } from '@xenia/ui' +import { priceReasonOptions } from '../logic/priceRules' + +export default function PriceReason({ rules, state, onChange, missing = false }) { + const { t } = useTranslation('waiter') + return ( +
+
+ {missing ? t('price.reasonMissing') : t('price.reason')} +
+ onChange({ ...state, choice })} + other={state.other} onOther={other => onChange({ ...state, other })} otherLabel={t('price.reasons.other')} + ariaLabel={t('price.reason')} testIdPrefix="price-reason" /> +
+ ) +} diff --git a/waiter_pwa/src/hooks/usePriceRules.js b/waiter_pwa/src/hooks/usePriceRules.js new file mode 100644 index 0000000..98d2f04 --- /dev/null +++ b/waiter_pwa/src/hooks/usePriceRules.js @@ -0,0 +1,14 @@ +// The venue's price-change rules (6F.3, logic/priceRules.js), from the shared settings request. +import { useEffect, useState } from 'react' +import { getVenueSettings } from '../api/venueSettings' +import { priceRules } from '../logic/priceRules' + +export function usePriceRules() { + const [rules, setRules] = useState(() => priceRules(null)) + useEffect(() => { + let alive = true + getVenueSettings().then(r => { if (alive) setRules(priceRules(r.data)) }).catch(() => {}) + return () => { alive = false } + }, []) + return rules +} diff --git a/waiter_pwa/src/logic/priceRules.js b/waiter_pwa/src/logic/priceRules.js new file mode 100644 index 0000000..12256a1 --- /dev/null +++ b/waiter_pwa/src/logic/priceRules.js @@ -0,0 +1,37 @@ +// The venue's rules for prices changed by hand (plan 6F.3), from its settings: +// orders.price_change off | before_sending | anytime (default anytime) +// orders.price_change_reason 'true' → a typed price needs a reason +// orders.price_change_reasons JSON list of quick reasons ([] → the built-in ones) +// Plain JS so Node tests can import it. +export const BUILT_IN_REASONS = ['regular', 'mistake', 'compensation', 'manager', 'happyHour'] + +export function priceRules(settings) { + const v = k => settings?.[k]?.value + const mode = ['off', 'before_sending', 'anytime'].includes(v('orders.price_change')) ? v('orders.price_change') : 'anytime' + let reasons = [] + try { + const list = JSON.parse(v('orders.price_change_reasons') || '[]') + if (Array.isArray(list)) reasons = list.filter(x => typeof x === 'string' && x.trim()).map(x => x.trim()) + } catch { /* a broken list: the built-in ones */ } + return { + mode, + inCart: mode !== 'off', // a price typed before sending + afterSending: mode === 'anytime', // a sent or served line + reasonRequired: v('orders.price_change_reason') === 'true', + reasons, + } +} + +/** The choices of the reason picker: the venue's own quick reasons, else the built-in ones. */ +export function priceReasonOptions(rules, t) { + return rules.reasons.length + ? rules.reasons.map((r, i) => ({ value: `v${i}`, label: r })) + : BUILT_IN_REASONS.map(k => ({ value: k, label: t(`price.reasons.${k}`) })) +} + +/** The reason to send for { choice, other } ('' = none): a quick reason's text or what was typed. */ +export function priceReasonText(rules, t, state) { + if (!state?.choice) return '' + if (state.choice === 'other') return (state.other || '').trim() + return priceReasonOptions(rules, t).find(o => o.value === state.choice)?.label ?? '' +} diff --git a/waiter_pwa/src/pages/TableDetailPage.jsx b/waiter_pwa/src/pages/TableDetailPage.jsx index 9071030..0729141 100644 --- a/waiter_pwa/src/pages/TableDetailPage.jsx +++ b/waiter_pwa/src/pages/TableDetailPage.jsx @@ -16,6 +16,10 @@ import { TransferIcon, MergeIcon, FlagsIcon, WaiterIcon, PrintIcon } from '../co import usePaymentSettingsStore from '../store/paymentSettingsStore' import useTableViewStore from '../store/tableViewStore' import { parseNumber, useTranslation } from '@xenia/i18n' +import PriceReason from '../components/PriceReason' +import { priceReasonText } from '../logic/priceRules' +import PriceHistory from '../components/PriceHistory' +import { usePriceRules } from '../hooks/usePriceRules' import { fade } from '../logic/colour' import SeatsHint from '../components/SeatsHint' @@ -119,8 +123,10 @@ function SplitModal({ item, onConfirm, onClose }) { // ─── Price adjust modal ─────────────────────────────────────────────────────── -function PriceAdjustModal({ item, onConfirm, onClose }) { +function PriceAdjustModal({ item, rules, error, onConfirm, onClose }) { const { t } = useTranslation('waiter') + const [reason, setReason] = useState({ choice: '', other: '' }) // 6F.3 + const [tried, setTried] = useState(false) const basePrice = item.unit_price ?? 0 const [adj, setAdj] = useState(item.price_adjustment ?? 0) const [editing, setEditing] = useState(false) @@ -225,6 +231,13 @@ function PriceAdjustModal({ item, onConfirm, onClose }) { ))}
+ {rules.reasonRequired && adj !== (item.price_adjustment ?? 0) && ( +
+ +
+ )} + {error &&

{error}

} + {/* Reset */} {adj !== 0 && ( - @@ -252,7 +265,7 @@ function PriceAdjustModal({ item, onConfirm, onClose }) { // ─── Item action modal (long-press) ────────────────────────────────────────── -function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, onClose }) { +function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, canSeePriceHistory, onPriceHistory, onClose }) { const { t } = useTranslation('waiter') const { items, singleStacked, multiSelect } = target const label = multiSelect @@ -260,6 +273,22 @@ function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCance : items[0]?.product?.name || `#${items[0]?.product_id}` const actionRows = [ + // 6F.3: who changed this line's price, when, from what, why (ordering.prices.view_changes) + ...(!multiSelect && canSeePriceHistory && items[0]?.price_adjustment ? [{ + key: 'price_history', + color: 'var(--x-warning)', + iconBg: 'rgb(var(--x-warning-rgb) / 0.15)', + label: t('price.history'), + sub: t('price.historySub'), + icon: ( + + + + + ), + onClick: onPriceHistory, + enabled: true, + }] : []), ...(!multiSelect && priceAdjAllowed ? [{ key: 'adjust_price', color: 'var(--x-warning)', @@ -1097,10 +1126,15 @@ export default function TableDetailPage() { // manager's PIN on the phone, the approval dialog opens by itself) or 'no' const cancelAccess = useAllowed('ordering.orders.cancel') const revertAccess = useAllowed('ordering.payments.revert') - const priceAccess = useAllowed('ordering.prices.modify') + // a sent line's price (6F.3): its own key, and the venue allows changes after sending + const priceAccess = useAllowed('ordering.prices.modify_sent') + const priceRulesNow = usePriceRules() + const seesPriceChanges = useCan('ordering.prices.view_changes') + const [priceError, setPriceError] = useState('') + const [historyItem, setHistoryItem] = useState(null) const canCancel = cancelAccess !== 'no' const revertAllowed = revertAccess !== 'no' - const priceAdjAllowed = priceAccess !== 'no' + const priceAdjAllowed = priceAccess !== 'no' && priceRulesNow.afterSending const canDiscount = useCan('pricing.discounts.apply') const canPay = useCan('ordering.orders.close') const canMove = useCan('ordering.orders.open') @@ -2201,6 +2235,12 @@ export default function TableDetailPage() { setItemActionTarget(null) setPriceAdjustItem(item) }} + canSeePriceHistory={seesPriceChanges && !isOffline} + onPriceHistory={() => { + const item = itemActionTarget.items[0] + setItemActionTarget(null) + setHistoryItem(item) + }} onCancel={() => { const ids = itemActionTarget.items.map(i => i.id) setItemActionTarget(null) @@ -2226,22 +2266,26 @@ export default function TableDetailPage() { {priceAdjustItem && ( { + rules={priceRulesNow} + error={priceError} + onConfirm={async (adj, reason) => { try { + setPriceError('') await client.patch(`/api/orders/${order.id}/items/${priceAdjustItem.id}/price-adjust`, { - price_adjustment: adj, + price_adjustment: adj, reason: reason || undefined, }) setPriceAdjustItem(null) await load() } catch (err) { - console.error('[price-adjust] failed:', err) - setPriceAdjustItem(null) + setPriceError(apiError(err, t('detail.err.price'))) // stays open: the reason or a manager's PIN } }} - onClose={() => setPriceAdjustItem(null)} + onClose={() => { setPriceAdjustItem(null); setPriceError('') }} /> )} + {historyItem && setHistoryItem(null)} />} + {/* Cancel confirmation */} {cancelConfirm && ( Object.fromEntries(Object.entries(o).map(([k, value]) => [k, { value }])) + +test('the venue rules for prices changed by hand (6F.3)', () => { + assert.deepEqual(priceRules(null), { mode: 'anytime', inCart: true, afterSending: true, reasonRequired: false, reasons: [] }) + const off = priceRules(set({ 'orders.price_change': 'off' })) + assert.equal(off.inCart, false); assert.equal(off.afterSending, false) + const cart = priceRules(set({ 'orders.price_change': 'before_sending', 'orders.price_change_reason': 'true' })) + assert.equal(cart.inCart, true); assert.equal(cart.afterSending, false); assert.equal(cart.reasonRequired, true) + assert.deepEqual(priceRules(set({ 'orders.price_change_reasons': '[" Friend ", "", 3]' })).reasons, ['Friend']) + assert.deepEqual(priceRules(set({ 'orders.price_change_reasons': 'not json' })).reasons, []) + assert.equal(priceRules(set({ 'orders.price_change': 'weird' })).mode, 'anytime') +}) + +test('the reason sent: a quick reason, a typed one, or none', async () => { + const { priceReasonText } = await import('../src/logic/priceRules.js') + const t = k => `T:${k}` + const builtIn = priceRules(null) + assert.equal(priceReasonText(builtIn, t, { choice: 'regular', other: '' }), 'T:price.reasons.regular') + assert.equal(priceReasonText(builtIn, t, { choice: 'other', other: ' burnt ' }), 'burnt') + assert.equal(priceReasonText(builtIn, t, { choice: '', other: 'x' }), '') + const own = priceRules(set({ 'orders.price_change_reasons': '["Friend"]' })) + assert.equal(priceReasonText(own, t, { choice: 'v0' }), 'Friend') +})