diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index fa3068b..e2e49c9 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -74,6 +74,7 @@ CODES: dict[str, tuple[int, str]] = { "pos.table_not_yours": (403, "{table} isn't in your zones. A manager can add the zone to your account."), "pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."), "pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."), + "order.not_sold_here": (422, "{name} isn't sold for this kind of order."), "refund.invalid": (422, "This refund doesn't add up ({reason})."), "refund.too_old": (409, "Only payments from today's business day can be refunded at the counter."), "refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."), diff --git a/local_backend/core/sales_points.py b/local_backend/core/sales_points.py new file mode 100644 index 0000000..cb651ff --- /dev/null +++ b/local_backend/core/sales_points.py @@ -0,0 +1,87 @@ +"""Sales points (plan phase 3S, step S.1): where an order is sold. A fixed list in code. + +Every order records its sales point (`orders.sales_point`); a product says where it's sold +(`products.sold_at`); prices for a sales point are price modifiers with the condition +`order_channel` (its `channels` param holds sales points). Labels live in the i18n packages +(`common:salesPoints.`). + + in_store the counter and the waiters, eating in + in_store_takeaway the counter, to take away (and phone orders delivered by the venue) + qr_table the QR menu, ordering at the table + online_takeaway online ordering, collected at the venue + online_delivery online ordering, delivered + online_preorder online reservation with food ready on arrival +""" +from __future__ import annotations + +import json + +IN_STORE = "in_store" +IN_STORE_TAKEAWAY = "in_store_takeaway" +QR_TABLE = "qr_table" +ONLINE_TAKEAWAY = "online_takeaway" +ONLINE_DELIVERY = "online_delivery" +ONLINE_PREORDER = "online_preorder" + +ALL: tuple[str, ...] = (IN_STORE, IN_STORE_TAKEAWAY, QR_TABLE, ONLINE_TAKEAWAY, ONLINE_DELIVERY, ONLINE_PREORDER) +IN_PERSON: tuple[str, ...] = (IN_STORE, IN_STORE_TAKEAWAY) +ONLINE: tuple[str, ...] = (ONLINE_TAKEAWAY, ONLINE_DELIVERY, ONLINE_PREORDER) +DIGITAL: tuple[str, ...] = (QR_TABLE,) + ONLINE # what the cloud's customer apps sell + +# the order_channel condition's values before S.1 → sales points +LEGACY_CHANNELS: dict[str, tuple[str, ...]] = { + "pos": (IN_STORE,), + "takeaway": (IN_STORE_TAKEAWAY,), + "online": ONLINE, + "qr": (QR_TABLE,), +} + + +def normalize(values) -> list[str]: + """Sales points from a list that may hold old channel names; unknown values dropped, + order kept, no duplicates.""" + out: list[str] = [] + for v in values or []: + for sp in (v,) if v in ALL else LEGACY_CHANNELS.get(v, ()): + if sp not in out: + out.append(sp) + return out + + +def for_order(order_type: str | None, source: str | None = None, online_order_type: str | None = None) -> str: + """The sales point of an order from what older code records (type, source).""" + if source == "online": + if online_order_type == "delivery": + return ONLINE_DELIVERY + if online_order_type == "takeaway": + return ONLINE_TAKEAWAY + if online_order_type == "preorder": + return ONLINE_PREORDER + return QR_TABLE # the QR menu's table orders arrive as online "dine_in" + return IN_STORE_TAKEAWAY if order_type in ("takeaway", "delivery") else IN_STORE + + +def of_order(order) -> str: + return getattr(order, "sales_point", None) or for_order(order.order_type, order.source, order.online_order_type) + + +def sold_at(product) -> list[str]: + """Where a product is sold (`products.sold_at`, JSON); missing or unreadable = everywhere.""" + raw = getattr(product, "sold_at", None) + if raw is None: + return list(ALL) + try: + values = json.loads(raw) if isinstance(raw, str) else raw + except ValueError: + return list(ALL) + return normalize(values) + + +def is_sold_at(product, point: str) -> bool: + return point in sold_at(product) + + +def dump(values) -> str: + """For `products.sold_at`: the sales points in the fixed order.""" + chosen = set(normalize(values)) + return json.dumps([sp for sp in ALL if sp in chosen]) diff --git a/local_backend/migrations/versions/0017_sales_points.py b/local_backend/migrations/versions/0017_sales_points.py new file mode 100644 index 0000000..7fb3761 --- /dev/null +++ b/local_backend/migrations/versions/0017_sales_points.py @@ -0,0 +1,113 @@ +"""sales points: orders.sales_point, products.sold_at; digital prices become price modifiers (plan phase 3S, step S.1) + +- orders.sales_point, from source / online_order_type / order_type (core/sales_points.for_order) +- products.sold_at (JSON list), from digital_visible (hidden online → sold in the venue only) +- digital_price / digital_discount → item price modifiers with the condition "sales point is + the QR menu or online" (a price difference, then a stackable % discount), so every place + that prices asks the same engine +- the order_channel condition's old values (pos, takeaway, online, qr) → sales points, in + price modifiers and deals +- drops products.digital_visible, digital_price, digital_discount + +Revision ID: 0017_sales_points +Revises: 0016_refunds +Create Date: 2026-11-15 21:00:00 +""" +import json + +from alembic import op +import sqlalchemy as sa + +from core.timeutil import UTCDateTime, utcnow + + +revision = '0017_sales_points' +down_revision = '0016_refunds' +branch_labels = None +depends_on = None + +ALL = ["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"] +IN_PERSON = ["in_store", "in_store_takeaway"] +DIGITAL = ["qr_table", "online_takeaway", "online_delivery", "online_preorder"] +LEGACY = {"pos": ["in_store"], "takeaway": ["in_store_takeaway"], + "online": ["online_takeaway", "online_delivery", "online_preorder"], "qr": ["qr_table"]} + + +def _remap(params: str) -> str: + try: + p = json.loads(params or "{}") + except ValueError: + return params + out = [] + for v in p.get("channels") or []: + for sp in ([v] if v in ALL else LEGACY.get(v, [])): + if sp not in out: + out.append(sp) + p["channels"] = out + return json.dumps(p) + + +def upgrade() -> None: + conn = op.get_bind() + + with op.batch_alter_table('orders', schema=None) as batch_op: + batch_op.add_column(sa.Column('sales_point', sa.String(), nullable=False, server_default='in_store')) + conn.execute(sa.text(""" + update orders set sales_point = case + when source = 'online' then case online_order_type + when 'delivery' then 'online_delivery' when 'takeaway' then 'online_takeaway' + when 'preorder' then 'online_preorder' else 'qr_table' end + when order_type in ('takeaway', 'delivery') then 'in_store_takeaway' + else 'in_store' end""")) + + with op.batch_alter_table('products', schema=None) as batch_op: + batch_op.add_column(sa.Column('sold_at', sa.Text(), nullable=False, server_default=json.dumps(ALL))) + conn.execute(sa.text("update products set sold_at = :v where digital_visible = 0"), {"v": json.dumps(IN_PERSON)}) + + modifiers = sa.table('price_modifiers', + sa.column('id', sa.Integer), sa.column('name', sa.String), sa.column('description', sa.Text), + sa.column('is_active', sa.Integer), sa.column('is_favorite', sa.Integer), + sa.column('allow_stack', sa.Integer), sa.column('sort_order', sa.Integer), + sa.column('scope', sa.String), sa.column('item_id', sa.Integer), + sa.column('action_type', sa.String), sa.column('action_value', sa.Float), + sa.column('created_at', UTCDateTime())) + conditions = sa.table('price_modifier_conditions', sa.column('modifier_id', sa.Integer), + sa.column('condition_type', sa.String), sa.column('params', sa.Text)) + now = utcnow() + rows = conn.execute(sa.text("select id, name, base_price, digital_price, digital_discount from products " + "where digital_price is not null or coalesce(digital_discount, 0) > 0")).fetchall() + for pid, name, base, price, discount in rows: + made = [] + if price is not None and abs(price - (base or 0.0)) > 0.0001: + made.append((f"Online price · {name}", "add_amount", round(price - (base or 0.0), 4), 0)) + if discount and discount > 0: + made.append((f"Online discount · {name}", "add_percent", -float(discount), 1)) + for label, action, value, stack in made: + mid = conn.execute(modifiers.insert().values( + name=label, description="From the product's digital menu price (moved in phase 3S)", + is_active=1, is_favorite=0, allow_stack=stack, sort_order=0, scope="item", item_id=pid, + action_type=action, action_value=value, created_at=now)).lastrowid + conn.execute(conditions.insert().values(modifier_id=mid, condition_type="order_channel", + params=json.dumps({"channels": DIGITAL}))) + + for table in ("price_modifier_conditions", "deal_conditions"): + for cid, params in conn.execute(sa.text(f"select id, params from {table} where condition_type = 'order_channel'")).fetchall(): + conn.execute(sa.text(f"update {table} set params = :p where id = :i"), {"p": _remap(params), "i": cid}) + + with op.batch_alter_table('products', schema=None) as batch_op: + batch_op.drop_column('digital_visible') + batch_op.drop_column('digital_price') + batch_op.drop_column('digital_discount') + + +def downgrade() -> None: + with op.batch_alter_table('products', schema=None) as batch_op: + batch_op.add_column(sa.Column('digital_discount', sa.Float(), nullable=False, server_default='0')) + batch_op.add_column(sa.Column('digital_price', sa.Float(), nullable=True)) + batch_op.add_column(sa.Column('digital_visible', sa.Integer(), nullable=False, server_default='1')) + op.get_bind().execute(sa.text("update products set digital_visible = 0 where sold_at not like '%qr_table%' " + "and sold_at not like '%online_%'")) + with op.batch_alter_table('products', schema=None) as batch_op: + batch_op.drop_column('sold_at') + with op.batch_alter_table('orders', schema=None) as batch_op: + batch_op.drop_column('sales_point') diff --git a/local_backend/models/order.py b/local_backend/models/order.py index fc91ed6..17e9d6f 100644 --- a/local_backend/models/order.py +++ b/local_backend/models/order.py @@ -22,6 +22,7 @@ class Order(Base): kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done kds_status_changed_at = Column(UTCDateTime, nullable=True) order_type = Column(String, default="here", nullable=False) # here|takeaway|delivery + sales_point = Column(String, default="in_store", nullable=False) # core/sales_points.py (phase 3S) # Xenia Connect — online order fields source = Column(String, default="pos", nullable=False) # "pos" | "online" diff --git a/local_backend/models/pricing.py b/local_backend/models/pricing.py index 698cea0..236735e 100644 --- a/local_backend/models/pricing.py +++ b/local_backend/models/pricing.py @@ -89,7 +89,7 @@ class PriceModifierCondition(Base): min_item_quantity {"min": N} (this product's qty in cart) min_category_qty {"category_id": N, "min": N} (items in category in cart) min_order_value {"min": 0.00} (cart total before modifiers) - order_channel {"channels": ["pos","online","qr","takeaway"]} + order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S) price_group_active {"price_group_id": N} user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts) low_stock {"threshold": N} (placeholder, needs inventory) diff --git a/local_backend/models/product.py b/local_backend/models/product.py index 8f016dc..17cc179 100644 --- a/local_backend/models/product.py +++ b/local_backend/models/product.py @@ -1,6 +1,9 @@ from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text from sqlalchemy.orm import relationship from database import Base +from core.sales_points import ALL as _SALES_POINTS, dump as _dump_sales_points + +_ALL_SALES_POINTS = _dump_sales_points(_SALES_POINTS) class Category(Base): @@ -42,13 +45,14 @@ class Product(Base): image_url = Column(String, nullable=True) sort_order = Column(Integer, default=0, nullable=False) - # Xenia Connect — digital menu overrides - digital_visible = Column(Integer, default=1, nullable=False) + # Where it's sold (phase 3S): JSON list of sales points (core/sales_points.py). Prices + # per sales point are price modifiers (condition order_channel), not columns. + sold_at = Column(Text, nullable=False, default=_ALL_SALES_POINTS) + # Xenia Connect — what the customer apps show (name, text, picture); digital_available = + # orderable online right now (a temporary switch, like is_available) digital_available = Column(Integer, default=1, nullable=False) digital_name = Column(String, nullable=True) digital_description = Column(String, nullable=True) - digital_price = Column(Float, nullable=True) - digital_discount = Column(Float, default=0.0, nullable=False) digital_image_url = Column(String, nullable=True) # sha256 of the image_url file last successfully pushed to the cloud — lets # cloud_sync skip re-uploading unchanged images on every sync tick diff --git a/local_backend/routers/data_transfer.py b/local_backend/routers/data_transfer.py index 07d45c6..8c7857a 100644 --- a/local_backend/routers/data_transfer.py +++ b/local_backend/routers/data_transfer.py @@ -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() diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index 03bba61..44659a8 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -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 diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index e39d368..c48c4df 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -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)], } diff --git a/local_backend/routers/products.py b/local_backend/routers/products.py index f00b25e..6922d0c 100644 --- a/local_backend/routers/products.py +++ b/local_backend/routers/products.py @@ -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: diff --git a/local_backend/schemas/product.py b/local_backend/schemas/product.py index 27e4e98..5a26c33 100644 --- a/local_backend/schemas/product.py +++ b/local_backend/schemas/product.py @@ -1,6 +1,10 @@ import json from pydantic import BaseModel, model_validator, field_validator -from typing import Optional, List, Any +from typing import Optional, List, Any, Literal + +from core.sales_points import ALL as _SALES_POINTS, sold_at as _sold_at + +SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"] class CategoryCreate(BaseModel): @@ -324,13 +328,12 @@ class ProductBase(BaseModel): lifecycle_status: str = "active" prep_zone_ids: List[int] = [] sort_order: int = 0 - # Xenia Connect — digital menu overrides - digital_visible: bool = True + # Where it's sold (phase 3S, core/sales_points.py); prices per sales point are price modifiers + sold_at: List[SalesPoint] = list(_SALES_POINTS) + # Xenia Connect — what the customer apps show digital_available: bool = True digital_name: Optional[str] = None digital_description: Optional[str] = None - digital_price: Optional[float] = None - digital_discount: Optional[float] = None digital_image_url: Optional[str] = None # Phase 2A — cost tracking cost_simple: Optional[float] = None @@ -372,13 +375,10 @@ class ProductUpdate(BaseModel): ingredients: Optional[List[ProductIngredientCreate]] = None preference_sets: Optional[List[PreferenceSetCreate]] = None modifier_groups: Optional[List[ModifierGroupCreate]] = None - # Xenia Connect — digital menu overrides - digital_visible: Optional[bool] = None + sold_at: Optional[List[SalesPoint]] = None digital_available: Optional[bool] = None digital_name: Optional[str] = None digital_description: Optional[str] = None - digital_price: Optional[float] = None - digital_discount: Optional[float] = None digital_image_url: Optional[str] = None # Phase 2A — cost tracking cost_simple: Optional[float] = None @@ -444,12 +444,10 @@ class ProductOut(ProductBase): 'prep_zone_ids': [z.id for z in data.prep_zones] if hasattr(data, 'prep_zones') else [], 'sort_order': data.sort_order, 'image_url': data.image_url, - 'digital_visible': bool(data.digital_visible), + 'sold_at': _sold_at(data), 'digital_available': bool(data.digital_available), 'digital_name': data.digital_name, 'digital_description': data.digital_description, - 'digital_price': data.digital_price, - 'digital_discount': data.digital_discount, 'digital_image_url': data.digital_image_url, 'cost_simple': data.cost_simple, 'cost_breakdown': parsed, diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 8268a5c..8ee1e66 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -11,6 +11,7 @@ Lock behaviour (unchanged): - cloud sets locked=true → lock_pending while a workday is open, locked once it closes - expiry past grace / site deactivated → likewise never mid-service """ +from core import sales_points from core.access.queries import holders_filter from core.timeutil import utcnow import asyncio @@ -269,23 +270,28 @@ async def _push_menu_snapshot(): .join(ProductCategory, ProductCategory.product_id == Product.id) .filter( ProductCategory.category_id == cat.id, - Product.digital_visible == 1, Product.lifecycle_status == "active", ) .order_by(ProductCategory.sort_order, Product.id) .all() ) + # sold by the customer apps (phase 3S); priced by the engine for the QR menu + # (S.2 sends a price per sales point) + products = [p for p in products if set(sales_points.sold_at(p)) & set(sales_points.DIGITAL)] + from services.pos_cart import unit_prices + qr_prices = unit_prices(db, products, sales_points.QR_TABLE) all_products.extend(p for p in products if p not in all_products) # once, even if listed twice product_list = [] - for p in products: + for p, qr_price in zip(products, qr_prices): product_list.append({ "id": p.id, "name": p.name, "digital_name": p.digital_name, "digital_description": p.digital_description, - "digital_price": p.digital_price, + "digital_price": round(qr_price, 2), "base_price": p.base_price, - "digital_discount": p.digital_discount, + "digital_discount": 0, + "sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.DIGITAL], "digital_available": bool(p.digital_available), "digital_image_url": p.digital_image_url, "image_url": p.image_url, @@ -353,6 +359,7 @@ def store_online_orders(db, orders: list[dict]) -> dict: status="open", source="online", order_type="delivery" if cloud_order.get("order_type") == "delivery" else "here", + sales_point=sales_points.for_order(None, "online", cloud_order.get("order_type")), business_day_id=day.id if day else None, online_order_ref=cloud_order["public_ref"], online_order_cloud_id=cloud_order["id"], diff --git a/local_backend/services/pos_cart.py b/local_backend/services/pos_cart.py index 55150e5..15b3827 100644 --- a/local_backend/services/pos_cart.py +++ b/local_backend/services/pos_cart.py @@ -20,7 +20,8 @@ Rules (the same as the waiter's options dialog, waiter_pwa ItemOptionsModal.jsx) - quantities: per-choice qty only on multi-select sets, per-add-on qty only on allow_multiple. Anything else → XeniaError("pos.line_invalid", line=n, reason=...), reason one of product_unavailable | unknown_quick | unknown_option | unknown_choice | unknown_sub | -choice_required | sub_required | unknown_ingredient | quantity | discount. +choice_required | sub_required | unknown_ingredient | quantity | discount | not_sold_here +(the product isn't sold at this sales point, phase 3S). A line may carry `discount_pct` (0–100, whole percent): the quote shows it; selling it needs ordering.prices.modify or a manager's approval (routers/pos.py). """ @@ -30,9 +31,15 @@ import json from dataclasses import dataclass, field from typing import Optional +from core import sales_points from core.errors import XeniaError -CHANNELS = {"here": "pos", "takeaway": "takeaway"} +POINTS = {"here": sales_points.IN_STORE, "takeaway": sales_points.IN_STORE_TAKEAWAY} + + +def point_for(order_type: str | None) -> str: + """The counter's sales point for an order type (phase 3S).""" + return POINTS.get(order_type or "here", sales_points.IN_STORE) def _subs(raw) -> list[dict]: @@ -175,19 +182,22 @@ def resolve_line(db, raw: dict, n: int) -> Line: return line -def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | None = None): +def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | None = None, point: str | None = None): """[(unit_price, [PriceEvent])] for each line, with the same context POST /api/orders/{id}/items builds: the order's existing items, the lines before it in the - same batch (at their resolved price), and this line.""" + same batch (at their resolved price), and this line. The sales point is the order type's + at the counter unless given; a product not sold there → pos.line_invalid not_sold_here.""" from core.timeutil import utcnow from services.pricing import OrderContext, build_active_price_group_ids, resolve_price now = utcnow() active = build_active_price_group_ids(db, now) - channel = CHANNELS.get(order_type, "pos") + channel = point or point_for(order_type) cart = list(existing_cart or []) out = [] - for line in lines: + for n, line in enumerate(lines): p = line.product + if not sales_points.is_sold_at(p, channel): + raise _bad(n, "not_sold_here") here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids, "quantity": line.quantity, "unit_price": p.base_price + line.extra} ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active) @@ -197,6 +207,22 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No return out +def unit_prices(db, products, point: str) -> list[float]: + """Each product's price for one unit without options at a sales point, right now, priced + on its own (an empty cart): what a menu shows.""" + from core.timeutil import utcnow + from services.pricing import OrderContext, build_active_price_group_ids, resolve_price + now = utcnow() + active = build_active_price_group_ids(db, now) + out = [] + for p in products: + here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids, + "quantity": 1, "unit_price": p.base_price} + ctx = OrderContext(channel=point, now=now, cart_items=[here], active_price_group_ids=active) + out.append(resolve_price(p, 1, 0.0, ctx, db)[0]) + return out + + def order_cart(order) -> list[dict]: """An order's active items as the pricing engine's cart context (what POST /api/orders/{id}/items starts from, and what a table's quote starts from, 3.3c).""" diff --git a/local_backend/services/pricing.py b/local_backend/services/pricing.py index 88c9ffe..0297ba1 100644 --- a/local_backend/services/pricing.py +++ b/local_backend/services/pricing.py @@ -33,7 +33,7 @@ from sqlalchemy.orm import Session @dataclass class OrderContext: """Snapshot of order-level facts needed to evaluate conditions.""" - channel: str # 'pos' | 'online' | 'qr' | 'takeaway' + channel: str # the order's sales point (core/sales_points.py) now: datetime # current UTC time cart_items: list # list of {product_id, category_id (primary), category_ids, quantity, unit_price} active_price_group_ids: set # set of PriceGroup.id that are currently active @@ -135,7 +135,8 @@ def _eval_condition(ctype: str, params: dict, ctx: OrderContext, return passed, {"min_order_value": round(total, 2)} if ctype == "order_channel": - passed = ctx.channel in params.get("channels", []) + from core.sales_points import normalize + passed = ctx.channel in normalize(params.get("channels", [])) return passed, {"order_channel": ctx.channel} if ctype == "price_group_active": diff --git a/local_backend/tests/test_sales_points.py b/local_backend/tests/test_sales_points.py new file mode 100644 index 0000000..4287c38 --- /dev/null +++ b/local_backend/tests/test_sales_points.py @@ -0,0 +1,174 @@ +"""Sales points, offerings and prices (plan phase 3S, step S.1). + +Done when: a "takeaway price" modifier makes the POS charge the lower price for a takeaway +sale and the normal one for eating in, and a product not sold at the counter doesn't show there.""" +import json +import re +from pathlib import Path + +from sqlalchemy import create_engine, text + +from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures) +from tests.test_pos import menu, on_shift, sale, till # noqa: F401 (fixtures) +from tests.test_pos_online import pulled + +ROOT = Path(__file__).resolve().parents[2] + + +def takeaway_price(db, product, price, channels=("in_store_takeaway",)): + """A price modifier as the manager's Pricing page makes it: this item, set the price, when + the sales point is one of `channels`.""" + from models.pricing import PriceModifier, PriceModifierCondition + m = PriceModifier(name=f"Takeaway {product.name}", scope="item", item_id=product.id, action_type="set", + action_value=price, is_active=1) + db.add(m) + db.flush() + db.add(PriceModifierCondition(modifier_id=m.id, condition_type="order_channel", + params=json.dumps({"channels": list(channels)}))) + db.commit() + return m + + +def sold_at(db, product, points): + from core.sales_points import dump + product.sold_at = dump(points) + db.commit() + + +def test_takeaway_price_at_the_counter(client, db, till, menu, on_shift): + """The done-when, first half: one cola, €3.50 to drink here, €2.50 to take away.""" + from models.order import Order, OrderItem + cola = menu["coffee"] + cola.base_price = 3.5 + db.commit() + takeaway_price(db, cola, 2.5) + listed = next(p for p in client.get("/api/pos/menu", headers=till["h"]).json()["products"] if p["id"] == cola.id) + assert listed["prices"] == {"in_store": 3.5, "in_store_takeaway": 2.5} + assert listed["sold_at"] == ["in_store", "in_store_takeaway"] + q = lambda t: client.post("/api/pos/quote", headers=till["h"], json={"order_type": t, "lines": [{"product_id": cola.id}]}).json() # noqa: E731 + assert (q("takeaway")["total"], q("here")["total"]) == (2.5, 3.5) + away = sale(client, till, [{"product_id": cola.id}], [{"method": "cash"}]) + here = client.post("/api/pos/sales", headers=till["h"], json={"order_type": "here", "lines": [{"product_id": cola.id}], + "payments": [{"method": "cash"}]}) + assert (away.json()["total"], here.json()["total"]) == (2.5, 3.5) + assert db.get(Order, away.json()["order_id"]).sales_point == "in_store_takeaway" + assert db.get(Order, here.json()["order_id"]).sales_point == "in_store" + item = db.query(OrderItem).filter(OrderItem.order_id == away.json()["order_id"]).one() + assert item.unit_price == 2.5 + + +def test_what_the_counter_doesnt_sell(client, db, till, menu, on_shift): + """The done-when, second half: a product sold only online isn't on the counter's menu and a + sale of it is refused; one sold only to take away can't be sold to eat in.""" + sold_at(db, menu["burger"], ["online_delivery", "online_takeaway"]) + sold_at(db, menu["coffee"], ["in_store_takeaway"]) + names = {p["name"]: p for p in client.get("/api/pos/menu", headers=till["h"]).json()["products"]} + assert "Burger" not in names and names["Freddo"]["sold_at"] == ["in_store_takeaway"] + r = client.post("/api/pos/quote", headers=till["h"], json={"order_type": "here", "lines": [{"product_id": menu["coffee"].id}]}) + assert err(r) == "pos.line_invalid" and r.json()["error"]["params"]["reason"] == "not_sold_here" + assert sale(client, till, [{"product_id": menu["coffee"].id}], [{"method": "card"}]).status_code == 201 # takeaway: fine + + +def test_waiter_orders_follow_the_sales_point(client, db, make_user, login, menu, on_shift): + """The waiter app lists what's sold in the shop and an order refuses the rest.""" + from models.order import Order + from models.user import WaiterZone + waiter = make_user(role="waiter") + db.add(WaiterZone(waiter_id=waiter.id, group_id=None)) + from models.shift import WaiterShift + db.add(WaiterShift(waiter_id=waiter.id, business_day_id=on_shift.business_day_id)) + db.commit() + h = login(waiter, "waiter") + sold_at(db, menu["burger"], ["online_delivery"]) + listed = [p["name"] for p in client.get("/api/products/", headers=h, params={"sold_at": "in_store,in_store_takeaway"}).json()] + assert "Burger" not in listed and "Freddo" in listed + assert "Burger" in [p["name"] for p in client.get("/api/products/", headers=h).json()] # no filter: as before + order = client.post("/api/orders/", headers=h, json={"table_id": None, "order_type": "here"}).json() + assert db.get(Order, order["id"]).sales_point == "in_store" + r = client.post(f"/api/orders/{order['id']}/items", headers=h, json={"items": [{"product_id": menu["burger"].id, "quantity": 1}]}) + assert err(r) == "order.not_sold_here" + + +def test_online_orders_get_their_sales_point(db, menu, make_user): + from core.timeutil import business_date_of, utcnow + from models.business_day import BusinessDay + from models.order import Order + make_user(role="owner") + db.add(BusinessDay(status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=1)) + db.commit() + assert db.get(Order, pulled(db, menu, 601, "delivery")).sales_point == "online_delivery" + assert db.get(Order, pulled(db, menu, 602, "dine_in")).sales_point == "qr_table" + + +def test_old_channel_names_still_price(client, db, till, menu, on_shift): + """A modifier saved before S.1 with the old value "takeaway" means the counter's takeaway.""" + takeaway_price(db, menu["coffee"], 2.0, channels=("takeaway",)) + q = client.post("/api/pos/quote", headers=till["h"], json={"order_type": "takeaway", "lines": [{"product_id": menu["coffee"].id}]}) + assert q.json()["total"] == 2.0 + + +def test_products_api_and_catalogue_carry_sold_at(client, db, owner_h): + from models.product import Category + cat = Category(name="Drinks") + db.add(cat) + db.commit() + r = client.post("/api/products/", headers=owner_h, json={"name": "Cola 1.5L", "base_price": 3.5, "primary_category_id": cat.id, + "category_ids": [cat.id], "sold_at": ["online_delivery", "in_store"]}) + assert r.status_code == 201, r.text + assert r.json()["sold_at"] == ["in_store", "online_delivery"] # stored in the fixed order + pid = r.json()["id"] + assert client.post("/api/products/", headers=owner_h, json={"name": "X", "base_price": 1, "sold_at": ["moon"]}).status_code == 422 + r = client.put(f"/api/products/{pid}", headers=owner_h, json={"sold_at": ["in_store_takeaway"]}) + assert r.json()["sold_at"] == ["in_store_takeaway"] + assert client.get("/api/products/", headers=owner_h).json()[0]["sold_at"] == ["in_store_takeaway"] + bundle = client.get("/api/data-transfer/export/catalog", headers=owner_h) + assert bundle.status_code == 200, bundle.text + product = next(p for c in bundle.json()["data"]["categories"] for p in c["products"] if p["name"] == "Cola 1.5L") + assert product["sold_at"] == ["in_store_takeaway"] + + +def test_the_frontend_list_matches_the_backend(): + """packages/access/src/salesPoints.js keeps the same list and old-name mapping.""" + from core.sales_points import ALL, LEGACY_CHANNELS + js = (ROOT / "packages" / "access" / "src" / "salesPoints.js").read_text(encoding="utf-8") + listed = re.search(r"export const SALES_POINTS = \[([^\]]*)\]", js).group(1) + assert [x.strip().strip("'") for x in listed.split(",")] == list(ALL) + for old, points in LEGACY_CHANNELS.items(): + assert re.search(rf"{old}: \[{', '.join(repr(p) for p in points)}\]", js), old + + +def test_migration_moves_digital_prices_and_visibility(tmp_path): + """0017: digital_visible → sold_at, digital_price / digital_discount → price modifiers for + the QR menu and online, old order_channel values → sales points, orders get theirs.""" + from alembic import command + from core.schema import alembic_config, upgrade_to_head + eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}") + with eng.begin() as conn: + command.upgrade(alembic_config(conn), "0016_refunds") + conn.execute(text("insert into users (id, username, role, is_active, pin_hash) values (1, 'boss', 'owner', 1, 'x')")) + for pid, name, visible, price, disc in ((1, "Cola", 1, 3.0, 0), (2, "Soup", 0, None, 0), (3, "Pie", 1, None, 10)): + conn.execute(text("insert into products (id, name, base_price, is_available, lifecycle_status, sort_order, digital_visible, " + "digital_available, digital_price, digital_discount, unit_type, quick_add_enabled, is_service_item) " + "values (:i, :n, 4.0, 1, 'active', 0, :v, 1, :p, :d, 'piece', 1, 0)"), + {"i": pid, "n": name, "v": visible, "p": price, "d": disc}) + conn.execute(text("insert into price_modifiers (id, name, is_active, is_favorite, allow_stack, sort_order, scope, action_type, action_value) " + "values (50, 'Old', 1, 0, 0, 0, 'global', 'add_amount', -1)")) + conn.execute(text("insert into price_modifier_conditions (modifier_id, condition_type, params) " + "values (50, 'order_channel', '{\"channels\": [\"pos\", \"online\"]}')")) + conn.execute(text("insert into orders (id, opened_by, status, order_type, kds_status, source) values (1, 1, 'closed', 'takeaway', 'served', 'pos')")) + conn.execute(text("insert into orders (id, opened_by, status, order_type, kds_status, source, online_order_type) " + "values (2, 1, 'closed', 'delivery', 'served', 'online', 'delivery')")) + upgrade_to_head(eng) + with eng.connect() as conn: + sold = dict(conn.execute(text("select name, sold_at from products")).fetchall()) + mods = conn.execute(text("select m.item_id, m.action_type, m.action_value, m.allow_stack, c.params from price_modifiers m " + "join price_modifier_conditions c on c.modifier_id = m.id where m.scope = 'item' order by m.item_id")).fetchall() + old = conn.execute(text("select params from price_modifier_conditions where modifier_id = 50")).scalar() + points = dict(conn.execute(text("select id, sales_point from orders")).fetchall()) + eng.dispose() + assert json.loads(sold["Soup"]) == ["in_store", "in_store_takeaway"] and len(json.loads(sold["Cola"])) == 6 + digital = ["qr_table", "online_takeaway", "online_delivery", "online_preorder"] + assert [(m[0], m[1], m[2], m[3], json.loads(m[4])["channels"]) for m in mods] == [ + (1, "add_amount", -1.0, 0, digital), (3, "add_percent", -10.0, 1, digital)] + assert json.loads(old)["channels"] == ["in_store"] + digital[1:] + assert points == {1: "in_store_takeaway", 2: "online_delivery"} diff --git a/manager_dashboard/src/pages/Management/ProductFormModal.jsx b/manager_dashboard/src/pages/Management/ProductFormModal.jsx index f3832ad..a7f0a06 100644 --- a/manager_dashboard/src/pages/Management/ProductFormModal.jsx +++ b/manager_dashboard/src/pages/Management/ProductFormModal.jsx @@ -2,6 +2,8 @@ import { useState, useEffect, useRef } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import toast from 'react-hot-toast' import client from '../../api/client' +import { useTranslation } from '@xenia/i18n' +import { SALES_POINTS } from '@xenia/access' // ── Small helpers ───────────────────────────────────────────────────────────── function moveItem(arr, i, dir) { @@ -195,13 +197,11 @@ function buildFormFromProduct(product) { allow_multi_select: ps.allow_multi_select ?? false, allow_choice_quantity: ps.allow_choice_quantity ?? false, })) ?? [], - digital_visible: product.digital_visible ?? true, + sold_at: product.sold_at ?? [...SALES_POINTS], digital_available: product.digital_available ?? true, digital_name: product.digital_name ?? '', digital_description: product.digital_description ?? '', digital_image_url: product.digital_image_url ?? '', - digital_price: product.digital_price ?? '', - digital_discount: product.digital_discount ?? '', // Phase 2A — cost tracking cost_mode: product.cost_breakdown?.length ? 'detailed' : 'simple', cost_simple: product.cost_simple ?? '', @@ -556,13 +556,11 @@ export default function ProductFormModal({ product, categories, printers, prepZo allow_multi_select: ps.allow_multi_select ?? false, allow_choice_quantity: ps.allow_choice_quantity ?? false, })), - digital_visible: form.digital_visible, + sold_at: form.sold_at, digital_available: form.digital_available, digital_name: form.digital_name || null, digital_description: form.digital_description || null, digital_image_url: form.digital_image_url || null, - digital_price: form.digital_price !== '' ? parseFloat(form.digital_price) : null, - digital_discount: form.digital_discount !== '' ? parseFloat(form.digital_discount) : null, // Phase 2A — cost tracking cost_simple: form.cost_mode === 'simple' && form.cost_simple !== '' ? parseFloat(form.cost_simple) : null, cost_breakdown: form.cost_mode === 'detailed' && form.cost_breakdown.length > 0 @@ -642,7 +640,7 @@ export default function ProductFormModal({ product, categories, printers, prepZo {[ { key: 'info', label: 'Πληροφορίες' }, ...(!form.is_service_item ? [ - { key: 'digital', label: 'Digital Menu' }, + { key: 'digital', label: 'Πού πωλείται' }, { key: 'cost', label: 'Κόστος' }, ...(fiscalEnabled ? [{ key: 'fiscal', label: 'Ταμειακή' }] : []), ] : []), @@ -842,90 +840,8 @@ export default function ProductFormModal({ product, categories, printers, prepZo } )} - {/* Tab 2: Digital Menu */} - {leftTab === 'digital' && (() => { - const basePrice = parseFloat(form.base_price) || 0 - const dp = form.digital_price !== '' ? parseFloat(form.digital_price) : null - const disc = form.digital_discount !== '' ? parseFloat(form.digital_discount) : null - let customerPrice = basePrice - if (dp !== null && !isNaN(dp)) customerPrice = dp - else if (disc !== null && !isNaN(disc) && disc > 0) customerPrice = Math.round(basePrice * (1 - disc / 100) * 100) / 100 - - return ( -
-
-

Ορατότητα

-
- -
- -

Uncheck to show as ‘Out of stock’

-
-
-
- -
-

Display overrides

-

Leave blank to use the standard product value

-
-
- - setField('digital_name', e.target.value)} - placeholder={form.name || 'Leave blank to use product name'} /> -
-
- -