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