From 94c10944ed639f819bc0ab7fffe2405e2a8651b3 Mon Sep 17 00:00:00 2001 From: bonamin Date: Fri, 20 Nov 2026 15:11:35 +0200 Subject: [PATCH] feat(backend): order channel prices: a product's price per sales point, per product / category / channel channel_prices rules (migration 0040, services/channel_prices.py): for one or more sales points, set the price (one product), add an amount or a percentage (with rounding), for listed products, the products of listed categories, or everything sold there. The most precise rule wins (product > category > channel, newest on a tie); resolve_price starts from it, so tills, phones, menus and the cloud's per-sales-point prices all follow. /api/pricing/channel-prices (CRUD) and /product/{id} (the product editor's quick edit of its own rules, with the fallback shown). Co-Authored-By: Claude Opus 5.5 --- local_backend/core/errors.py | 2 + .../versions/0040_channel_prices.py | 40 +++++ local_backend/models/pricing.py | 20 +++ local_backend/routers/pricing.py | 133 +++++++++++++++++ local_backend/services/channel_prices.py | 137 ++++++++++++++++++ local_backend/services/pricing.py | 10 +- local_backend/tests/test_channel_prices.py | 51 +++++++ packages/i18n/locales/el/errors.json | 4 + packages/i18n/locales/en/errors.json | 4 + 9 files changed, 400 insertions(+), 1 deletion(-) create mode 100644 local_backend/migrations/versions/0040_channel_prices.py create mode 100644 local_backend/services/channel_prices.py create mode 100644 local_backend/tests/test_channel_prices.py diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 3efcd1c..64443b4 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -199,6 +199,8 @@ CODES: dict[str, tuple[int, str]] = { "expense.over_due": (400, "That's more than what is still due ({due})."), "expense.below_paid": (400, "{paid} has been paid already: the total can't be less."), "expense.document_not_found": (404, "Document not found."), + "channel_price.not_found": (404, "Channel price not found."), + "channel_price.set_one_product": (400, "A set price is for one product: pick one product (and no categories), or change the price by an amount or a percentage."), "expense.document_type": (422, "Upload a PDF or a photo (JPG, PNG, WebP or HEIC)."), "expense.document_too_big": (413, "The file is too big (at most {max_mb} MB)."), "flag.not_found": (404, "Mark not found."), diff --git a/local_backend/migrations/versions/0040_channel_prices.py b/local_backend/migrations/versions/0040_channel_prices.py new file mode 100644 index 0000000..e7cf6da --- /dev/null +++ b/local_backend/migrations/versions/0040_channel_prices.py @@ -0,0 +1,40 @@ +"""Order channel prices (UI review 2026-11-20): a product's price at a sales point, set per +product, per category or for the whole channel (services/channel_prices.py). + +Revision ID: 0040_channel_prices +Revises: 0039_expense_lines_documents +Create Date: 2026-11-20 17:00:00 +""" +from alembic import op +import sqlalchemy as sa +from core.timeutil import UTCDateTime + +revision = '0040_channel_prices' +down_revision = '0039_expense_lines_documents' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + 'channel_prices', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('sales_points', sa.Text(), nullable=False), + sa.Column('product_ids', sa.Text(), nullable=False), + sa.Column('category_ids', sa.Text(), nullable=False), + sa.Column('action_type', sa.String(), nullable=False), + sa.Column('value', sa.Float(), nullable=False), + sa.Column('round_to', sa.String(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('created_at', UTCDateTime(), nullable=True), + sa.Column('updated_at', UTCDateTime(), nullable=True), + sa.Column('updated_by', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['updated_by'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_channel_prices_id', 'channel_prices', ['id']) + + +def downgrade() -> None: + op.drop_table('channel_prices') diff --git a/local_backend/models/pricing.py b/local_backend/models/pricing.py index 43cca3c..e794d67 100644 --- a/local_backend/models/pricing.py +++ b/local_backend/models/pricing.py @@ -280,3 +280,23 @@ class WaiterDiscountSettings(Base): max_items_per_order = Column(Integer, nullable=True) user = relationship("User", foreign_keys=[user_id]) + + +class ChannelPrice(Base): + """A price at one or more sales points (2026-11-20, services/channel_prices.py): for listed + products, the products of listed categories, or (neither) everything sold there. The most + precise rule wins: product > category > channel.""" + __tablename__ = "channel_prices" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String, nullable=True) + sales_points = Column(Text, nullable=False, default="[]") # JSON ["online_delivery", …] + product_ids = Column(Text, nullable=False, default="[]") # JSON [int] + category_ids = Column(Text, nullable=False, default="[]") # JSON [int] + action_type = Column(String, nullable=False) # 'set' | 'add_amount' | 'add_percent' + value = Column(Float, nullable=False) + round_to = Column(String, nullable=True) # as PriceModifier.round_to + is_active = Column(Boolean, nullable=False, default=True) + created_at = Column(UTCDateTime, default=utcnow) + updated_at = Column(UTCDateTime, nullable=True) + updated_by = Column(Integer, ForeignKey("users.id"), nullable=True) diff --git a/local_backend/routers/pricing.py b/local_backend/routers/pricing.py index d006ce4..a331081 100644 --- a/local_backend/routers/pricing.py +++ b/local_backend/routers/pricing.py @@ -763,3 +763,136 @@ def _sync_deal_targets(deal, targets_in, db: Session): target_ids=json.dumps(t.target_ids) if t.target_ids else None, target_tags=json.dumps(t.target_tags) if t.target_tags else None, )) + + + +# ============================================================================= +# ORDER CHANNEL PRICES (2026-11-20, services/channel_prices.py) +# ============================================================================= + +from pydantic import BaseModel as _Base # noqa: E402 + + +class ChannelPriceIn(_Base): + name: Optional[str] = None + sales_points: List[str] + product_ids: List[int] = [] + category_ids: List[int] = [] + action_type: str + value: float + round_to: Optional[str] = None + is_active: bool = True + + +class ProductChannelPriceIn(_Base): + """The product editor's quick edit: per sales point, its own rule or null (no own rule).""" + points: dict[str, Optional[dict]] + + +def _cp_fields(body: ChannelPriceIn) -> dict: + from services import channel_prices as cp + f = body.model_dump() + f["name"] = (f.get("name") or "").strip()[:120] or None + f["round_to"] = f.get("round_to") or None + cp.check(f) + return f + + +def _cp_store(row, f: dict, user) -> None: + from core.timeutil import utcnow as _now + row.name = f["name"] + row.sales_points = json.dumps(list(dict.fromkeys(f["sales_points"]))) + row.product_ids = json.dumps(sorted(set(f["product_ids"]))) + row.category_ids = json.dumps(sorted(set(f["category_ids"]))) + row.action_type = f["action_type"] + row.value = f["value"] + row.round_to = f["round_to"] + row.is_active = f["is_active"] + row.updated_at = _now() + row.updated_by = user.id + + +@router.get("/channel-prices") +def list_channel_prices(db: Session = Depends(get_db), user: User = Depends(require(MANAGE))): + from models.pricing import ChannelPrice + from services import channel_prices as cp + return [cp.out(r) for r in db.query(ChannelPrice).order_by(ChannelPrice.id).all()] + + +@router.post("/channel-prices", status_code=status.HTTP_201_CREATED) +def create_channel_price(body: ChannelPriceIn, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))): + from models.pricing import ChannelPrice + from services import channel_prices as cp + f = _cp_fields(body) + row = ChannelPrice() + _cp_store(row, f, user) + db.add(row) + db.commit() + _changed() + return cp.out(row) + + +@router.put("/channel-prices/{rule_id}") +def update_channel_price(rule_id: int, body: ChannelPriceIn, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))): + from models.pricing import ChannelPrice + from services import channel_prices as cp + row = db.query(ChannelPrice).filter(ChannelPrice.id == rule_id).first() + if not row: + raise XeniaError("channel_price.not_found") + _cp_store(row, _cp_fields(body), user) + db.commit() + _changed() + return cp.out(row) + + +@router.delete("/channel-prices/{rule_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_channel_price(rule_id: int, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))): + from models.pricing import ChannelPrice + row = db.query(ChannelPrice).filter(ChannelPrice.id == rule_id).first() + if not row: + raise XeniaError("channel_price.not_found") + db.delete(row) + db.commit() + _changed() + + +@router.get("/channel-prices/product/{product_id}") +def product_channel_prices(product_id: int, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))): + """Per sales point the product is sold at: the default price, the price there and why.""" + from models.product import Product + from services import channel_prices as cp + p = db.query(Product).filter(Product.id == product_id).first() + if not p: + raise XeniaError("product.not_found") + return {"product_id": p.id, "base_price": p.base_price, "points": cp.product_view(db, p)} + + +@router.put("/channel-prices/product/{product_id}") +def set_product_channel_prices(product_id: int, body: ProductChannelPriceIn, db: Session = Depends(get_db), + user: User = Depends(require(MANAGE))): + """The product's own price per sales point: {action_type, value, round_to} sets it, null + removes it (the category's or the channel's rule, or the default price, counts again).""" + from models.pricing import ChannelPrice + from models.product import Product + from services import channel_prices as cp + p = db.query(Product).filter(Product.id == product_id).first() + if not p: + raise XeniaError("product.not_found") + every = db.query(ChannelPrice).order_by(ChannelPrice.id).all() + for point, spec in body.points.items(): + own = cp.own_rule(every, p.id, point) + if spec is None: + if own is not None: + db.delete(own) + continue + f = {"name": None, "sales_points": [point], "product_ids": [p.id], "category_ids": [], + "action_type": spec.get("action_type"), "value": spec.get("value"), "round_to": spec.get("round_to") or None, + "is_active": True} + cp.check(f) + if own is None: + own = ChannelPrice() + db.add(own) + _cp_store(own, f, user) + db.commit() + _changed() + return {"product_id": p.id, "base_price": p.base_price, "points": cp.product_view(db, p)} diff --git a/local_backend/services/channel_prices.py b/local_backend/services/channel_prices.py new file mode 100644 index 0000000..b5a641b --- /dev/null +++ b/local_backend/services/channel_prices.py @@ -0,0 +1,137 @@ +"""Order channel prices (UI review 2026-11-20): a product's price at a sales point. + +A rule says, for one or more sales points (core/sales_points.py), what happens to the price: +`set` it (one product only), `add_amount` (± euros) or `add_percent` (± %), then optionally +rounds it (the price modifiers' rounding modes). It applies to the products it lists, to the +products of the categories it lists, or — listing neither — to everything sold there. + +The most precise rule wins, one per product and sales point: + the product's own rule > a rule of one of its categories > a rule for the whole channel +(on a tie, the newest). No rule: the default price. The channel price is the base that the price +modifiers and deals (services/pricing.py) then work on, so it reaches every till, phone, menu and +the cloud's ordering apps (cloud_sync prices each sales point through resolve_price). +""" +from __future__ import annotations + +import json + +from core import sales_points + +ACTIONS = ("set", "add_amount", "add_percent") +ROUNDING = ("0.05", "0.10", "0.20", "0.50", "x.99", "x.00") +LEVELS = {"product": 3, "category": 2, "channel": 1} + + +def _ids(raw) -> list: + try: + v = json.loads(raw) if isinstance(raw, str) else (raw or []) + except ValueError: + return [] + return [x for x in v if x is not None] + + +def points_of(rule) -> list[str]: + return [sp for sp in _ids(rule.sales_points) if sp in sales_points.ALL] + + +def products_of(rule) -> list[int]: + return [int(x) for x in _ids(rule.product_ids)] + + +def categories_of(rule) -> list[int]: + return [int(x) for x in _ids(rule.category_ids)] + + +def level_of(rule, product) -> int: + """How precisely the rule names this product (0 = not at all).""" + if product.id in products_of(rule): + return LEVELS["product"] + cats = set(categories_of(rule)) + if cats: + mine = set(product.category_ids or []) | ({product.primary_category_id} if product.primary_category_id else set()) + return LEVELS["category"] if cats & mine else 0 + return LEVELS["channel"] if not products_of(rule) else 0 + + +def active_rules(db) -> list: + from models.pricing import ChannelPrice + return db.query(ChannelPrice).filter(ChannelPrice.is_active == True).order_by(ChannelPrice.id).all() # noqa: E712 + + +def winner(rules, product, point: str): + """The rule that sets the product's price at this sales point, or None.""" + best, best_level = None, 0 + for r in rules: + if point not in points_of(r): + continue + lv = level_of(r, product) + if lv and lv >= best_level: # >=: the newest of the same precision + best, best_level = r, lv + return best + + +def apply(rule, price: float) -> float: + from services.pricing import _apply_action + return _apply_action(price, rule.action_type, rule.value, rule.round_to) + + +def price_at(db, product, point: str, rules=None) -> tuple[float, object | None]: + """(the product's price at the sales point before modifiers and deals, the rule or None).""" + rules = active_rules(db) if rules is None else rules + r = winner(rules, product, point) + return (round(apply(r, product.base_price), 4), r) if r else (product.base_price, None) + + +def check(fields: dict) -> None: + """Refuse a rule that can't work (XeniaError).""" + from core.errors import XeniaError + points = [sp for sp in fields.get("sales_points") or [] if sp in sales_points.ALL] + if not points: + raise XeniaError("validation.missing", field="sales_points") + if fields.get("action_type") not in ACTIONS: + raise XeniaError("validation.choice", field="action_type", value=fields.get("action_type")) + if fields.get("value") is None: + raise XeniaError("validation.missing", field="value") + if fields.get("round_to") not in (None, "", *ROUNDING): + raise XeniaError("validation.choice", field="round_to", value=fields.get("round_to")) + if fields["action_type"] == "set": + if fields["value"] < 0: + raise XeniaError("validation.positive", field="value") + if len(fields.get("product_ids") or []) != 1 or fields.get("category_ids"): + raise XeniaError("channel_price.set_one_product") + + +def out(rule) -> dict: + return { + "id": rule.id, "name": rule.name, "sales_points": points_of(rule), + "product_ids": products_of(rule), "category_ids": categories_of(rule), + "level": "product" if products_of(rule) else "category" if categories_of(rule) else "channel", + "action_type": rule.action_type, "value": rule.value, "round_to": rule.round_to or None, + "is_active": bool(rule.is_active), "created_at": rule.created_at, "updated_at": rule.updated_at, + } + + +def own_rule(rules, product_id: int, point: str): + """The product's own rule for one sales point (what the product editor edits), or None.""" + for r in rules: + if products_of(r) == [product_id] and points_of(r) == [point] and not categories_of(r): + return r + return None + + +def product_view(db, product) -> list[dict]: + """Per sales point the product is sold at: the default price, the price there, which rule + makes it, the product's own rule (to edit) and the rule that counts without it (fallback).""" + from models.pricing import ChannelPrice + rules = active_rules(db) + every = db.query(ChannelPrice).order_by(ChannelPrice.id).all() + rows = [] + for sp in sales_points.sold_at(product): + price, rule = price_at(db, product, sp, rules) + own = own_rule(every, product.id, sp) + # what counts without the product's own rule (the category's, the channel's or none) + fallback = winner([r for r in rules if own is None or r.id != own.id], product, sp) + rows.append({"sales_point": sp, "base_price": product.base_price, "price": round(price, 2), + "rule": out(rule) if rule else None, "own": out(own) if own else None, + "fallback": out(fallback) if fallback else None}) + return rows diff --git a/local_backend/services/pricing.py b/local_backend/services/pricing.py index 1628c52..88aa490 100644 --- a/local_backend/services/pricing.py +++ b/local_backend/services/pricing.py @@ -305,9 +305,17 @@ def resolve_price( order_id must be set on the PriceEvents before writing them; the caller does this. """ from models.pricing import PriceModifier + from services import channel_prices - base = product.base_price + options_extra events: list[PriceEvent] = [] + # the price at this sales point (order channel prices, 2026-11-20): the base for the rest + own, rule = channel_prices.price_at(db, product, ctx.channel) if ctx.channel else (product.base_price, None) + base = own + options_extra + if rule is not None: + events.append(PriceEvent(order_id=0, order_item_id=None, event_type="channel_price", + price_before=product.base_price + options_extra, price_after=base, + delta_amount=round(base - product.base_price - options_extra, 4), + conditions_snapshot={"channel_price_id": rule.id, "sales_point": ctx.channel})) # --- Load modifiers --- # Item-scoped modifiers for this product diff --git a/local_backend/tests/test_channel_prices.py b/local_backend/tests/test_channel_prices.py new file mode 100644 index 0000000..b42cf2a --- /dev/null +++ b/local_backend/tests/test_channel_prices.py @@ -0,0 +1,51 @@ +"""Order channel prices (UI review 2026-11-20): a product's price at a sales point, per product, +per category or for the whole channel; the most precise rule wins (product > category > channel), +and the channel price is the base the price modifiers work on, everywhere prices are made.""" +from services.pos_cart import unit_prices +from tests.test_live import owner_h # noqa: F401 (fixtures) +from tests.test_pos import menu # noqa: F401 (fixtures) + + +def _rule(client, h, **body): + r = client.post("/api/pricing/channel-prices", headers=h, json=body) + assert r.status_code == 201, r.text + return r.json() + + +def test_the_most_precise_rule_wins(client, db, owner_h, menu): + burger, coffee = menu["burger"], menu["coffee"] + on = lambda p, sp: round(unit_prices(db, [p], sp)[0], 2) # noqa: E731 + assert on(burger, "online_delivery") == 10.0 + # the whole delivery channel: +10 % + _rule(client, owner_h, sales_points=["online_delivery"], action_type="add_percent", value=10) + assert on(burger, "online_delivery") == 11.0 and on(coffee, "online_delivery") == 3.3 and on(burger, "in_store") == 10.0 + # the drinks' category: +0.50 on delivery and takeaway (beats the channel rule) + _rule(client, owner_h, sales_points=["online_delivery", "online_takeaway"], category_ids=[coffee.primary_category_id], + action_type="add_amount", value=0.5) + assert on(coffee, "online_delivery") == 3.5 and on(coffee, "online_takeaway") == 3.5 and on(burger, "online_delivery") == 11.0 + # the coffee itself: set to 2.80 on delivery (beats the category) + _rule(client, owner_h, sales_points=["online_delivery"], product_ids=[coffee.id], action_type="set", value=2.8) + assert on(coffee, "online_delivery") == 2.8 and on(coffee, "online_takeaway") == 3.5 + + +def test_a_set_price_is_for_one_product(client, owner_h, menu): + r = client.post("/api/pricing/channel-prices", headers=owner_h, json={ + "sales_points": ["qr_table"], "category_ids": [menu["coffee"].primary_category_id], "action_type": "set", "value": 2}) + assert r.status_code == 400 and r.json()["error"]["code"] == "channel_price.set_one_product" + r = client.post("/api/pricing/channel-prices", headers=owner_h, json={"sales_points": [], "action_type": "add_amount", "value": 1}) + assert r.status_code == 400 + + +def test_the_product_editor_quick_edit(client, db, owner_h, menu): + burger = menu["burger"] + _rule(client, owner_h, sales_points=["online_takeaway"], action_type="add_amount", value=1) + r = client.put(f"/api/pricing/channel-prices/product/{burger.id}", headers=owner_h, json={"points": { + "in_store_takeaway": {"action_type": "add_percent", "value": -10, "round_to": "0.50"}}}) + assert r.status_code == 200, r.text + rows = {x["sales_point"]: x for x in r.json()["points"]} + assert rows["in_store_takeaway"]["price"] == 9.0 and rows["in_store_takeaway"]["own"]["action_type"] == "add_percent" + assert rows["online_takeaway"]["price"] == 11.0 and rows["online_takeaway"]["rule"]["level"] == "channel" and rows["online_takeaway"]["own"] is None + assert rows["in_store"]["price"] == 10.0 and rows["in_store"]["rule"] is None + # removed: back to the default + r = client.put(f"/api/pricing/channel-prices/product/{burger.id}", headers=owner_h, json={"points": {"in_store_takeaway": None}}) + assert {x["sales_point"]: x for x in r.json()["points"]}["in_store_takeaway"]["price"] == 10.0 diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 8082614..f27fc63 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -354,5 +354,9 @@ "print": { "printer_off": "Ο εκτυπωτής {{printer}} είναι απενεργοποιημένος στις ρυθμίσεις.", "redirect_failed": "Ούτε ο {{printer}} το τύπωσε ({{error}}). Το δελτίο περιμένει ακόμα." + }, + "channel_price": { + "not_found": "Η τιμή καναλιού δεν βρέθηκε.", + "set_one_product": "Η σταθερή τιμή είναι για ένα προϊόν: επιλέξτε ένα προϊόν (χωρίς κατηγορίες) ή αλλάξτε την τιμή κατά ποσό ή ποσοστό." } } diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 1dff0a2..398c919 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -354,5 +354,9 @@ "print": { "printer_off": "The printer {{printer}} is turned off in the settings.", "redirect_failed": "{{printer}} didn't print it either ({{error}}). The ticket is still waiting." + }, + "channel_price": { + "not_found": "Channel price not found.", + "set_one_product": "A set price is for one product: pick one product (and no categories), or change the price by an amount or a percentage." } }