feat: pricing on v2 (platform-v2 step 6.7)

- manager src/pages/pricing: price rules, price groups, deals, discounts on the tokens,
  English and Greek; the rules as data in pricingLogic.js (tests/pricing.test.mjs)
- routers/pricing: set-up needs pricing.manage, broadcasts pricing.changed; incomplete
  conditions refused (pricing.bad_condition); venue discount settings saved again (the
  date-as-text bug) with empty = no limit (pricing.bad_limit), old "None" tolerated
- nav: Offers & pricing needs pricing.manage
- tests: test_pricing_setup.py (a happy-hour rule prices a counter quote), manager.mjs e2e

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 15:40:51 +02:00
co-authored by Claude Opus 5.5
parent c1af7770cf
commit fd3254aa31
28 changed files with 2040 additions and 2118 deletions
+2
View File
@@ -233,6 +233,8 @@ CODES: dict[str, tuple[int, str]] = {
"price_group.not_found": (404, "Price group not found."),
"modifier.not_found": (404, "Price rule not found."),
"deal.not_found": (404, "Deal not found."),
"pricing.bad_condition": (422, "A condition is incomplete: fill in all its values."),
"pricing.bad_limit": (422, "A discount limit must be a number of 0 or more, or empty for no limit."),
"catalog.category_not_found": (404, "Category not found."),
"catalog.parent_not_found": (404, "The parent category doesn't exist."),
"catalog.nest_has_children": (400, "A category with sub-categories can't go under another one."),
+103 -22
View File
@@ -20,12 +20,21 @@ from schemas.pricing import (
WaiterDiscountSettingsIn, WaiterDiscountSettingsOut,
PriceEventOut,
)
from routers.deps import get_current_user, require_manager
from routers.deps import get_current_user
from core.access.deps import require
from models.user import User
from core.errors import XeniaError
router = APIRouter()
MANAGE = "pricing.manage" # setting up price groups, modifiers, deals and the discount limits (6.7)
def _changed() -> None:
"""Tell the manager's pricing pages (and the counters' quotes) that the rules changed."""
from services.ws_bus import broadcast_sync
broadcast_sync("pricing.changed", {})
@@ -45,7 +54,7 @@ def list_price_groups(
def create_price_group(
body: PriceGroupCreate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
pg = PriceGroup(
name=body.name,
@@ -59,6 +68,7 @@ def create_price_group(
)
db.add(pg)
db.commit()
_changed()
db.refresh(pg)
return pg
@@ -68,7 +78,7 @@ def update_price_group(
group_id: int,
body: PriceGroupUpdate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
if not pg:
@@ -81,6 +91,7 @@ def update_price_group(
pg.auto_disable_time = body.auto_disable_time
pg.auto_days = json.dumps(body.auto_days) if body.auto_days is not None else None
db.commit()
_changed()
db.refresh(pg)
return pg
@@ -89,13 +100,14 @@ def update_price_group(
def toggle_price_group(
group_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
if not pg:
raise XeniaError("price_group.not_found")
pg.is_active = 0 if pg.is_active else 1
db.commit()
_changed()
db.refresh(pg)
return pg
@@ -104,13 +116,14 @@ def toggle_price_group(
def delete_price_group(
group_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
if not pg:
raise XeniaError("price_group.not_found")
db.delete(pg)
db.commit()
_changed()
# =============================================================================
@@ -150,7 +163,7 @@ def list_favorite_modifiers(
def create_modifier(
body: PriceModifierCreate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
m = PriceModifier(
name=body.name,
@@ -172,6 +185,7 @@ def create_modifier(
_sync_conditions(m, body.conditions, db, model="modifier")
_sync_modifier_targets(m, body.targets, db)
db.commit()
_changed()
db.refresh(m)
return m
@@ -181,7 +195,7 @@ def update_modifier(
modifier_id: int,
body: PriceModifierUpdate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
if not m:
@@ -209,6 +223,7 @@ def update_modifier(
_sync_conditions(m, body.conditions, db, model="modifier")
_sync_modifier_targets(m, body.targets, db)
db.commit()
_changed()
db.refresh(m)
return m
@@ -217,7 +232,7 @@ def update_modifier(
def toggle_modifier(
modifier_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
if not m:
@@ -226,6 +241,7 @@ def toggle_modifier(
m.updated_at = utcnow()
m.updated_by = user.id
db.commit()
_changed()
db.refresh(m)
return m
@@ -234,13 +250,14 @@ def toggle_modifier(
def reorder_modifiers(
body: PriceModifierReorderRequest,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
for item in body.items:
db.query(PriceModifier).filter(PriceModifier.id == item.id).update(
{"sort_order": item.sort_order}
)
db.commit()
_changed()
return {"ok": True}
@@ -248,13 +265,14 @@ def reorder_modifiers(
def delete_modifier(
modifier_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
if not m:
raise XeniaError("modifier.not_found")
db.delete(m)
db.commit()
_changed()
# =============================================================================
@@ -273,7 +291,7 @@ def list_deals(
def create_deal(
body: DealCreate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
d = Deal(
name=body.name,
@@ -298,6 +316,7 @@ def create_deal(
_sync_conditions(d, body.conditions, db, model="deal")
_sync_deal_targets(d, body.targets, db)
db.commit()
_changed()
db.refresh(d)
return d
@@ -307,7 +326,7 @@ def update_deal(
deal_id: int,
body: DealUpdate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
d = db.query(Deal).filter(Deal.id == deal_id).first()
if not d:
@@ -335,6 +354,7 @@ def update_deal(
_sync_conditions(d, body.conditions, db, model="deal")
_sync_deal_targets(d, body.targets, db)
db.commit()
_changed()
db.refresh(d)
return d
@@ -343,13 +363,14 @@ def update_deal(
def toggle_deal(
deal_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
d = db.query(Deal).filter(Deal.id == deal_id).first()
if not d:
raise XeniaError("deal.not_found")
d.is_active = 0 if d.is_active else 1
db.commit()
_changed()
db.refresh(d)
return d
@@ -358,13 +379,14 @@ def toggle_deal(
def delete_deal(
deal_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
d = db.query(Deal).filter(Deal.id == deal_id).first()
if not d:
raise XeniaError("deal.not_found")
db.delete(d)
db.commit()
_changed()
# =============================================================================
@@ -374,7 +396,7 @@ def delete_deal(
@router.get("/discount-settings/global")
def get_global_discount_settings(
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
from models.settings import PosSettings
keys = [
@@ -387,33 +409,48 @@ def get_global_discount_settings(
row_map = {r.key.split(".", 1)[1]: r.value for r in rows}
# Coerce types so frontend toggle/number fields work correctly
def _coerce(k, v):
if v is None:
return None
if v is None or v == "" or v == "None":
return None if k != "enabled" else True
if k == "enabled":
return v.lower() in ("true", "1", "yes")
try:
return float(v) if "." in str(v) else int(v)
except Exception:
return v
return {k: _coerce(k, v) for k, v in row_map.items()}
out = {k: None for k in ("max_total_value_workday", "max_total_value_shift", "max_items_per_shift")}
out["enabled"] = True
out.update({k: _coerce(k, v) for k, v in row_map.items()})
return out
@router.put("/discount-settings/global")
def set_global_discount_settings(
body: dict,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
from models.settings import PosSettings
allowed = {
"enabled", "max_total_value_workday",
"max_total_value_shift", "max_items_per_shift",
}
now = utcnow().isoformat()
now = utcnow() # was .isoformat(): saving failed on platform v2
for k, v in body.items():
if k not in allowed:
continue
full_key = f"discounts.{k}"
if k == "enabled":
v = "true" if v in (True, "true", "1", 1) else "false"
elif v is None or v == "":
v = "" # no limit
else:
try:
v = float(v)
except (TypeError, ValueError):
raise XeniaError("pricing.bad_limit", key=k)
if v < 0:
raise XeniaError("pricing.bad_limit", key=k)
v = int(v) if k == "max_items_per_shift" or v.is_integer() else v
row = db.query(PosSettings).filter(PosSettings.key == full_key).first()
if row:
row.value = str(v)
@@ -421,6 +458,7 @@ def set_global_discount_settings(
else:
db.add(PosSettings(key=full_key, value=str(v), updated_at=now))
db.commit()
_changed()
return {"ok": True}
@@ -441,7 +479,7 @@ def get_my_discount_settings(
def get_waiter_discount_settings(
user_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
s = db.query(WaiterDiscountSettings).filter(
WaiterDiscountSettings.user_id == user_id
@@ -457,7 +495,7 @@ def set_waiter_discount_settings(
user_id: int,
body: WaiterDiscountSettingsIn,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(require("pricing.manage")),
):
s = db.query(WaiterDiscountSettings).filter(
WaiterDiscountSettings.user_id == user_id
@@ -474,6 +512,7 @@ def set_waiter_discount_settings(
s.max_items_per_workday = body.max_items_per_workday
s.max_items_per_order = body.max_items_per_order
db.commit()
_changed()
db.refresh(s)
return s
@@ -643,8 +682,50 @@ def dismiss_deal_offer(
# Internal helpers
# =============================================================================
def _condition_ok(ctype: str, p: dict) -> bool:
"""A condition the price engine can evaluate (an incomplete one used to break the POS)."""
import re
from datetime import date
def hhmm(v):
return isinstance(v, str) and re.fullmatch(r"([01]\d|2[0-3]):[0-5]\d", v) is not None
def day(v):
try:
date.fromisoformat(v)
return True
except (TypeError, ValueError):
return False
def num(v, low):
return isinstance(v, (int, float)) and not isinstance(v, bool) and v >= low
if ctype == "time_range":
return hhmm(p.get("from")) and hhmm(p.get("to")) and p["from"] != p["to"]
if ctype == "date_range":
return day(p.get("from")) and day(p.get("to")) and p["from"] <= p["to"]
if ctype == "specific_date":
return bool(p.get("dates")) and all(day(d) for d in p["dates"])
if ctype == "day_of_week":
return bool(p.get("days")) and all(isinstance(d, int) and 0 <= d <= 6 for d in p["days"])
if ctype == "min_item_quantity":
return num(p.get("min", 1), 1)
if ctype == "min_category_qty":
return isinstance(p.get("category_id"), int) and num(p.get("min", 1), 1)
if ctype == "min_order_value":
return num(p.get("min", 0), 0)
if ctype == "order_channel":
return bool(p.get("channels"))
if ctype == "price_group_active":
return isinstance(p.get("price_group_id"), int)
return ctype in ("user_tier", "low_stock") # old placeholders: kept, never added
def _sync_conditions(parent, conditions_in, db: Session, model: str):
"""Write condition rows for a modifier or deal."""
for c in conditions_in:
if not _condition_ok(c.condition_type, c.params or {}):
raise XeniaError("pricing.bad_condition", type=c.condition_type)
for c in conditions_in:
if model == "modifier":
db.add(PriceModifierCondition(
+4 -1
View File
@@ -654,7 +654,10 @@ def check_waiter_discount_limits(
# --- Global limits from pos_settings ---
def _gs(key):
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return float(row.value) if row and row.value else None
try:
return float(row.value) if row and row.value else None
except ValueError: # an old "None" (fixed in 6.7): no limit
return None
g_max_wd_value = _gs("discounts.max_total_value_workday")
g_max_shift_val = _gs("discounts.max_total_value_shift")
+71
View File
@@ -0,0 +1,71 @@
"""Pricing set-up on platform v2 (plan step 6.7): who may change it, conditions the price engine
can evaluate, the venue's discount limits, live changes, and a happy-hour rule pricing a sale."""
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import menu, till # noqa: F401 (fixtures)
def happy_hour(**extra):
return {"name": "Happy hour", "action_type": "add_percent", "action_value": -20, "scope": "global",
"targets": [{"target_type": "all"}],
"conditions": [{"condition_type": "time_range", "params": {"from": "00:00", "to": "23:59"}}], **extra}
def test_only_pricing_managers_change_the_rules(client, owner_h, make_user, login):
waiter = login(make_user(role="waiter"), client="waiter")
assert client.get("/api/pricing/modifiers", headers=waiter).status_code == 200 # the phones read them
assert client.post("/api/pricing/modifiers", headers=waiter, json=happy_hour()).status_code == 403
assert client.put("/api/pricing/discount-settings/global", headers=waiter, json={"enabled": False}).status_code == 403
assert client.post("/api/pricing/modifiers", headers=owner_h, json=happy_hour()).status_code == 201
def test_incomplete_conditions_are_refused(client, owner_h):
for cond in ({"condition_type": "time_range", "params": {"from": "17:00"}},
{"condition_type": "date_range", "params": {"from": "2026-12-01", "to": "2026-11-01"}},
{"condition_type": "day_of_week", "params": {"days": []}},
{"condition_type": "price_group_active", "params": {}},
{"condition_type": "min_category_qty", "params": {"min": 2}}):
r = client.post("/api/pricing/modifiers", headers=owner_h, json=happy_hour(conditions=[cond]))
assert err(r) == "pricing.bad_condition", cond
deal = {"name": "Beer", "action_type": "free_item", "conditions": [{"condition_type": "order_channel", "params": {"channels": []}}]}
assert err(client.post("/api/pricing/deals", headers=owner_h, json=deal)) == "pricing.bad_condition"
def test_the_venue_discount_limits(client, owner_h, db):
from models.settings import PosSettings
assert client.get("/api/pricing/discount-settings/global", headers=owner_h).json() == {
"enabled": True, "max_total_value_workday": None, "max_total_value_shift": None, "max_items_per_shift": None}
r = client.put("/api/pricing/discount-settings/global", headers=owner_h,
json={"enabled": False, "max_total_value_workday": 50, "max_total_value_shift": 12.5, "max_items_per_shift": None})
assert r.status_code == 200
assert client.get("/api/pricing/discount-settings/global", headers=owner_h).json() == {
"enabled": False, "max_total_value_workday": 50, "max_total_value_shift": 12.5, "max_items_per_shift": None}
# "no limit" is stored empty (it used to be "None", which broke every later discount)
row = db.query(PosSettings).filter(PosSettings.key == "discounts.max_items_per_shift").first()
assert row is None or row.value == ""
assert err(client.put("/api/pricing/discount-settings/global", headers=owner_h, json={"max_items_per_shift": -1})) == "pricing.bad_limit"
def test_changes_are_announced(client, owner_h, monkeypatch):
import services.ws_bus as bus
sent = []
monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, **kw: sent.append(t))
g = client.post("/api/pricing/groups", headers=owner_h, json={"name": "Summer"}).json()
client.patch(f"/api/pricing/groups/{g['id']}/toggle", headers=owner_h)
assert sent.count("pricing.changed") == 2
def test_a_happy_hour_rule_prices_a_counter_sale(client, owner_h, till, menu):
"""The done-when: a happy-hour modifier made in the manager prices a POS sale."""
line = {"product_id": menu["coffee"].id, "quantity": 2}
before = client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()
assert before["total"] == 6.0
r = client.post("/api/pricing/modifiers", headers=owner_h, json=happy_hour(targets=[{"target_type": "item", "target_ids": [menu["coffee"].id]}]))
assert r.status_code == 201, r.text
after = client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()
assert after["lines"][0]["unit_price"] == 2.4 and after["total"] == 4.8
# the burger isn't a target: its price stays
burger = client.post("/api/pos/quote", headers=till["h"], json={"lines": [{"product_id": menu["burger"].id, "quantity": 1,
"prefs": [{"set_id": menu["cook"].id, "choices": [{"id": menu["rare"].id}], "shared": "Fries"}]}]}).json()
assert burger["total"] == 10.0
client.patch(f"/api/pricing/modifiers/{r.json()['id']}/toggle", headers=owner_h) # off: back to the menu price
assert client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()["total"] == 6.0