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 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 15:11:35 +02:00
co-authored by Claude Opus 5.5
parent f3fc3340d2
commit 94c10944ed
9 changed files with 400 additions and 1 deletions
+133
View File
@@ -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)}