feat(backend,waiter,manager): prices changed by hand are on the record

Owner 2026-11-23 (plan 6F.3). services/price_changes.py: the venue's switch orders.price_change
(off | before_sending | anytime, default anytime as before), orders.price_change_reason and its
quick reasons; keys ordering.prices.modify (the cart), new modify_sent (a sent or served line) and
view_changes (who sees them). Every by-hand price (waiter cart, a sent line, the counter's %
discount) writes a manual_price PriceEventLog row (before, after, quantity, who, approving manager,
stage, reason) plus a PRICE_CHANGED audit row; before, the sent-line change overwrote the price with
no record. Alembic 0047: event columns; modify_sent for everyone holding modify (and the venues'
role overrides), view_changes for owners and store managers.
Waiter: the reason picker when the venue asks, a sent line's price on modify_sent and the venue's
switch, the line's price history. Manager: Settings -> Operation 'Prices changed by hand', the
changes on the order's lines and history, Reports -> Cancellations, discounts and price changes
(+ export). Counter: no discount when the venue turned price changes off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 07:41:43 +02:00
co-authored by Claude Opus 5.5
parent e3f4f3eeee
commit f87f9ff23c
40 changed files with 1044 additions and 73 deletions
+3
View File
@@ -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."),
@@ -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')
+8 -1
View File
@@ -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):
+6 -1
View File
@@ -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'),
+42 -5
View File
@@ -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
+20 -8
View File
@@ -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", [])}
+8 -7
View File
@@ -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
+61
View File
@@ -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"),
+3
View File
@@ -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):
+5
View File
@@ -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}
+124
View File
@@ -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")
+1 -1
View File
@@ -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"
+170
View File
@@ -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
+3
View File
@@ -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