"""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")