feat: sales points, offerings and prices per sales point (platform-v2 phase 3S, step S.1)

- core/sales_points.py: in_store, in_store_takeaway, qr_table, online_takeaway,
  online_delivery, online_preorder (+ old channel names mapped).
- Alembic 0017: orders.sales_point (backfilled), products.sold_at (from digital_visible),
  digital_price/digital_discount -> item price modifiers for the QR menu and online,
  order_channel conditions -> sales points; drops the three digital columns.
- Every order records its sales point; the pricing engine's channel is it; items not sold
  there are refused (order.not_sold_here, pos.line_invalid not_sold_here).
- POS menu: only what the counter sells, prices per counter sales point; the screen shows
  the order type's products and prices. Waiter app asks for in-person products.
- Cloud snapshot: products sold by the customer apps, priced by the engine.
- Manager: product "Where it's sold" tab; pricing condition shows sales points.
- Products API, catalogue export/import carry sold_at.
- Tests: test_sales_points.py (8, incl. the migration), access +1, terminal +1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 11:00:40 +02:00
co-authored by Claude Opus 5.5
parent f2182dcb37
commit 1b468fe44b
30 changed files with 700 additions and 156 deletions
+5
View File
@@ -1,5 +1,6 @@
from core.timeutil import venue_date, utcnow
import json
from core import sales_points
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
@@ -57,6 +58,7 @@ def _serialize_product(p: Product) -> dict:
return {
"name": p.name, "base_price": p.base_price, "is_available": p.is_available,
"lifecycle_status": p.lifecycle_status, "sort_order": p.sort_order,
"sold_at": sales_points.sold_at(p),
"quick_options": quick_options, "options": options,
"ingredients": ingredients, "preference_sets": preference_sets,
}
@@ -183,6 +185,8 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
existing.is_available = prod_data.get("is_available", True)
existing.lifecycle_status = prod_data.get("lifecycle_status", "active")
existing.sort_order = prod_data.get("sort_order", 0)
if "sold_at" in prod_data: # phase 3S; older bundles: unchanged
existing.sold_at = sales_points.dump(prod_data["sold_at"])
db.flush()
product = existing
else:
@@ -192,6 +196,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
is_available=prod_data.get("is_available", True),
lifecycle_status=prod_data.get("lifecycle_status", "active"),
sort_order=prod_data.get("sort_order", 0),
sold_at=sales_points.dump(prod_data.get("sold_at", sales_points.ALL)),
)
db.add(product)
db.flush()
+8 -6
View File
@@ -468,7 +468,9 @@ def open_order(body: OrderCreate, db: Session = Depends(get_db), user: User = De
if existing:
raise HTTPException(status_code=400, detail="Table already has an open order")
order = Order(table_id=body.table_id, order_type=order_type, opened_by=user.id, business_day_id=active_day.id)
from core.sales_points import for_order
order = Order(table_id=body.table_id, order_type=order_type, opened_by=user.id, business_day_id=active_day.id,
sales_point=for_order(order_type))
db.add(order)
db.flush()
db.add(OrderWaiter(order_id=order.id, waiter_id=user.id))
@@ -505,11 +507,9 @@ def add_items(
# Build pricing context once for the whole batch
now = utcnow()
active_pg_ids = build_active_price_group_ids(db, now)
# Determine order channel
_channel_map = {"online": "online", "takeaway": "takeaway", "delivery": "takeaway"}
order_channel = _channel_map.get(order.order_type, "pos")
if order.source == "online":
order_channel = "online"
# The order's sales point (phase 3S): what the pricing engine's channel condition sees
from core.sales_points import is_sold_at, of_order
order_channel = of_order(order)
# Snapshot existing cart items for condition evaluation
from services.pos_cart import order_cart
existing_cart = order_cart(order) # the counter's table quote starts from the same (3.3c)
@@ -518,6 +518,8 @@ def add_items(
product = db.query(Product).filter(Product.id == item_in.product_id).first()
if not product or not product.is_available:
raise HTTPException(status_code=400, detail=f"Product {item_in.product_id} not available")
if not is_sold_at(product, order_channel):
raise XeniaError("order.not_sold_here", name=product.name)
# Priceless service items: print-once, NOT persisted (ephemeral)
# Priced service items: saved as real order items AND printed in a SERVICE section
+14 -6
View File
@@ -81,11 +81,14 @@ def _subs_out(raw):
for s in pos_cart._subs(raw)]
def _product_out(p, price: float) -> dict:
def _product_out(p, price: float, prices: dict | None = None) -> dict:
shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731
from core import sales_points
return {
"id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url,
"price": round(price, 2), "base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
"price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()},
"sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON],
"base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
"tags": _tags(p.tags),
"primary_category_id": p.primary_category_id,
"categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships],
@@ -117,7 +120,10 @@ def _tags(raw):
@router.get("/menu")
def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Categories and the products a cashier can sell (available, active, not service
items), each with its price right now for one unit without options (pricing engine)."""
items, sold at the counter: eating in or to take away, phase 3S), each with its price right
now for one unit without options (pricing engine): `price` for the screen's default order
type, `prices` per counter sales point, `sold_at` (which of the two)."""
from core import sales_points
from models.product import Category, Product, ProductPreferenceSet
from core.access.context import current_device
from core.modules import device_config
@@ -129,14 +135,16 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi
selectinload(Product.preference_sets).selectinload(ProductPreferenceSet.choices),
selectinload(Product.memberships))
.order_by(Product.sort_order, Product.name).all())
lines = [pos_cart.Line(product=p, quantity=1) for p in products]
prices = pos_cart.price_lines(db, lines, settings["default_order_type"]) if lines else []
products = [p for p in products if set(sales_points.sold_at(p)) & set(sales_points.IN_PERSON)]
by_point = {sp: pos_cart.unit_prices(db, products, sp) for sp in sales_points.IN_PERSON}
default = pos_cart.point_for(settings["default_order_type"])
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
return {
"settings": settings,
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
for c in cats],
"products": [_product_out(p, unit) for p, (unit, _) in zip(products, prices)],
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON})
for i, p in enumerate(products)],
}
+17 -6
View File
@@ -7,6 +7,7 @@ from pydantic import BaseModel
from sqlalchemy.orm import Session
from typing import List
from core import sales_points
from database import get_db
from models.product import Product, Category, ProductCategory, ProductOption, ProductQuickOption, ProductIngredient, ProductPreferenceSet, ProductPreferenceChoice, ProductModifierGroup
from models.prep_zone import PrepZone
@@ -263,10 +264,12 @@ def delete_category(category_id: int, db: Session = Depends(get_db), user: User
# ── Products ──────────────────────────────────────────────────────────────────
@router.get("/", response_model=List[ProductOut])
def list_products(all: bool = False, category_id: int | None = None, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
def list_products(all: bool = False, category_id: int | None = None, sold_at: str | None = None,
db: Session = Depends(get_db), user: User = Depends(get_current_user)):
"""Every product once, with `category_ids` / `categories` (D-23). With `category_id`:
the products LISTED in that category (primary or not), in that category's order."""
the products LISTED in that category (primary or not), in that category's order. With
`sold_at` (comma-separated): only products sold at one of those sales points (phase 3S; the
waiter app asks for in_store,in_store_takeaway)."""
from sqlalchemy.orm import selectinload
q = db.query(Product).options(selectinload(Product.memberships), selectinload(Product.prep_zones))
has_dashboard = holds(user, "core.dashboard.access")
@@ -277,8 +280,15 @@ def list_products(all: bool = False, category_id: int | None = None, db: Session
q = q.join(ProductCategory, ProductCategory.product_id == Product.id) \
.filter(ProductCategory.category_id == category_id) \
.order_by(ProductCategory.sort_order, Product.id)
return q.all()
return q.order_by(Product.sort_order, Product.id).all()
return _sold_filter(q.all(), sold_at)
return _sold_filter(q.order_by(Product.sort_order, Product.id).all(), sold_at)
def _sold_filter(products, points):
"""`points`: sales points, comma-separated; a product sold at any of them stays."""
from core.sales_points import normalize, sold_at
wanted = set(normalize((points or "").split(",")))
return products if not points else [p for p in products if wanted & set(sold_at(p))]
def _apply_categories(db, product, body, creating: bool) -> None:
@@ -336,6 +346,7 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
if body.cost_breakdown is not None:
data["cost_breakdown"] = json.dumps([item.model_dump() for item in body.cost_breakdown])
data["tags"] = json.dumps(body.tags) if body.tags is not None else None
data["sold_at"] = sales_points.dump(body.sold_at)
product = Product(**data)
db.add(product)
db.flush()
@@ -393,7 +404,7 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
"category_id", "primary_category_id", "category_ids"},
)
for field, value in scalar_fields.items():
setattr(product, field, value)
setattr(product, field, sales_points.dump(value) if field == "sold_at" else value)
_apply_categories(db, product, body, creating=False)
# Update prep zones if provided
if body.prep_zone_ids is not None: