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:
@@ -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."),
|
||||
|
||||
@@ -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.<key>`).
|
||||
|
||||
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])
|
||||
@@ -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')
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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)."""
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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"}
|
||||
@@ -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
|
||||
</div>}
|
||||
</>)}
|
||||
|
||||
{/* 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 (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-3">Ορατότητα</p>
|
||||
<div className="space-y-3">
|
||||
<label className="flex items-center gap-3 cursor-pointer select-none">
|
||||
<input type="checkbox" checked={form.digital_visible}
|
||||
onChange={e => setField('digital_visible', e.target.checked)}
|
||||
className="w-4 h-4 accent-primary-700" />
|
||||
<span className="text-sm font-medium text-gray-700">Show on digital menu</span>
|
||||
</label>
|
||||
<div>
|
||||
<label className="flex items-center gap-3 cursor-pointer select-none">
|
||||
<input type="checkbox" checked={form.digital_available}
|
||||
onChange={e => setField('digital_available', e.target.checked)}
|
||||
className="w-4 h-4 accent-primary-700" />
|
||||
<span className="text-sm font-medium text-gray-700">Available for ordering</span>
|
||||
</label>
|
||||
<p className="text-xs text-gray-400 mt-1 ml-7">Uncheck to show as ‘Out of stock’</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-1">Display overrides</p>
|
||||
<p className="text-xs text-gray-400 mb-3">Leave blank to use the standard product value</p>
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="label">Display name (override)</label>
|
||||
<input className="input" value={form.digital_name}
|
||||
onChange={e => setField('digital_name', e.target.value)}
|
||||
placeholder={form.name || 'Leave blank to use product name'} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Description</label>
|
||||
<textarea className="input resize-none" rows={3}
|
||||
value={form.digital_description}
|
||||
onChange={e => setField('digital_description', e.target.value)}
|
||||
placeholder="Leave blank to use product description"
|
||||
style={{ lineHeight: 1.5, fontSize: 13 }} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Image URL</label>
|
||||
<input className="input" value={form.digital_image_url}
|
||||
onChange={e => setField('digital_image_url', e.target.value)}
|
||||
placeholder="https://…" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-3">Pricing</p>
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="label">Online price (override)</label>
|
||||
<input type="number" step="0.01" min="0" className="input w-40"
|
||||
value={form.digital_price}
|
||||
onChange={e => setField('digital_price', e.target.value)}
|
||||
placeholder="e.g. 9.50" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Discount %</label>
|
||||
<input type="number" step="1" min="0" max="100" className="input w-40"
|
||||
value={form.digital_discount}
|
||||
onChange={e => setField('digital_discount', e.target.value)}
|
||||
placeholder="e.g. 10 for 10% off" />
|
||||
</div>
|
||||
<div className="rounded-lg bg-green-50 border border-green-200 px-4 py-3 text-sm text-green-800">
|
||||
Customer sees: <span className="font-bold">€{customerPrice.toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
{/* Tab 2: where it's sold (phase 3S) and what the customer apps show */}
|
||||
{leftTab === 'digital' && <SoldAtTab form={form} setField={setField} />}
|
||||
|
||||
{/* Tab 3: Cost */}
|
||||
{leftTab === 'cost' && (
|
||||
@@ -1423,3 +1339,74 @@ export default function ProductFormModal({ product, categories, printers, prepZo
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Where a product is sold (plan phase 3S): one checkbox per sales point, the customer apps'
|
||||
// display overrides, and where prices per sales point live (price rules, not fields here).
|
||||
function SoldAtTab({ form, setField }) {
|
||||
const { t } = useTranslation('common')
|
||||
const toggle = sp => setField('sold_at', form.sold_at.includes(sp)
|
||||
? form.sold_at.filter(x => x !== sp)
|
||||
: SALES_POINTS.filter(x => x === sp || form.sold_at.includes(x)))
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-ink-3 uppercase tracking-widest mb-1">Πού πωλείται</p>
|
||||
<p className="text-xs text-ink-3 mb-3">Όπου δεν είναι επιλεγμένο, το προϊόν δεν εμφανίζεται και δεν γίνεται δεκτό σε παραγγελίες.</p>
|
||||
<div className="space-y-2" data-testid="sold-at">
|
||||
{SALES_POINTS.map(sp => (
|
||||
<label key={sp} className="flex items-start gap-3 cursor-pointer select-none">
|
||||
<input type="checkbox" checked={form.sold_at.includes(sp)} onChange={() => toggle(sp)}
|
||||
className="w-4 h-4 mt-0.5 accent-accent" data-testid={`sold-at-${sp}`} />
|
||||
<span>
|
||||
<span className="block text-sm font-medium text-ink">{t(`salesPoints.${sp}.name`)}</span>
|
||||
<span className="block text-xs text-ink-3">{t(`salesPoints.${sp}.hint`)}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-ink-2 mt-3 rounded-lg bg-surface-2 border border-line px-3 py-2">
|
||||
Διαφορετική τιμή ανά σημείο πώλησης (π.χ. φθηνότερο σε πακέτο): Τιμολόγηση → Τροποποιητές, με συνθήκη «Κανάλι παραγγελίας».
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-ink-3 uppercase tracking-widest mb-3">QR μενού και online</p>
|
||||
<div>
|
||||
<label className="flex items-center gap-3 cursor-pointer select-none">
|
||||
<input type="checkbox" checked={form.digital_available}
|
||||
onChange={e => setField('digital_available', e.target.checked)}
|
||||
className="w-4 h-4 accent-accent" />
|
||||
<span className="text-sm font-medium text-ink">Διαθέσιμο για παραγγελία τώρα</span>
|
||||
</label>
|
||||
<p className="text-xs text-ink-3 mt-1 ml-7">Ξετσεκάρετε για να εμφανίζεται ως «Εξαντλήθηκε».</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-ink-3 uppercase tracking-widest mb-1">Εμφάνιση στους πελάτες</p>
|
||||
<p className="text-xs text-ink-3 mb-3">Αφήστε κενό για να χρησιμοποιηθούν τα στοιχεία του προϊόντος.</p>
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="label">Όνομα</label>
|
||||
<input className="input" value={form.digital_name}
|
||||
onChange={e => setField('digital_name', e.target.value)}
|
||||
placeholder={form.name || ''} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Περιγραφή</label>
|
||||
<textarea className="input resize-none" rows={3}
|
||||
value={form.digital_description}
|
||||
onChange={e => setField('digital_description', e.target.value)}
|
||||
style={{ lineHeight: 1.5, fontSize: 13 }} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Διεύθυνση εικόνας</label>
|
||||
<input className="input" value={form.digital_image_url}
|
||||
onChange={e => setField('digital_image_url', e.target.value)}
|
||||
placeholder="https://…" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Plus, Gift, Power, Pencil, Trash2, X, Info } from 'lucide-react'
|
||||
import toast from 'react-hot-toast'
|
||||
import client from '../../../api/client'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access'
|
||||
import Button from '../../../ui/Button'
|
||||
import Modal from '../../../ui/Modal'
|
||||
import { ConfirmModal } from '../../../ui/Modal'
|
||||
@@ -31,12 +33,12 @@ const CONDITION_TYPES = [
|
||||
{ value: 'time_range', label: 'Ώρα ημέρας' },
|
||||
{ value: 'day_of_week', label: 'Ημέρα εβδομάδας' },
|
||||
{ value: 'date_range', label: 'Εύρος ημερομηνιών' },
|
||||
{ value: 'order_channel', label: 'Κανάλι παραγγελίας' },
|
||||
{ value: 'order_channel', label: 'Σημείο πώλησης' },
|
||||
{ value: 'price_group_active',label: 'Ομάδα τιμής ενεργή' },
|
||||
]
|
||||
|
||||
const DAYS = ['Δευτέρα','Τρίτη','Τετάρτη','Πέμπτη','Παρασκευή','Σάββατο','Κυριακή']
|
||||
const CHANNELS = ['pos','online','qr','takeaway']
|
||||
const CHANNELS = SALES_POINTS // phase 3S: the order_channel condition holds sales points
|
||||
|
||||
const ACTION_TYPES = [
|
||||
{ value: 'apply_modifier', label: 'Εφαρμογή τροποποιητή' },
|
||||
@@ -50,6 +52,7 @@ const ACTION_TYPES = [
|
||||
// ─── Reuse condition editor (simplified for deals) ────────────────────────────
|
||||
|
||||
function ConditionRow({ cond, onChange, onRemove, groups }) {
|
||||
const { t } = useTranslation('common')
|
||||
const set = (k, v) => onChange({ ...cond, params: { ...cond.params, [k]: v } })
|
||||
const setType = t => onChange({ condition_type: t, params: {} })
|
||||
|
||||
@@ -123,10 +126,10 @@ function ConditionRow({ cond, onChange, onRemove, groups }) {
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{CHANNELS.map(ch => (
|
||||
<button type="button" key={ch}
|
||||
onClick={() => { const channels = cond.params.channels ?? []; set('channels', channels.includes(ch) ? channels.filter(x => x !== ch) : [...channels, ch]) }}
|
||||
onClick={() => { const channels = normalizeSalesPoints(cond.params.channels); set('channels', channels.includes(ch) ? channels.filter(x => x !== ch) : [...channels, ch]) }}
|
||||
className={`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${
|
||||
(cond.params.channels ?? []).includes(ch) ? 'bg-sky-100 text-sky-700' : 'bg-white border border-slate-200 text-slate-500 hover:bg-slate-50'
|
||||
}`}>{ch}</button>
|
||||
normalizeSalesPoints(cond.params.channels).includes(ch) ? 'bg-sky-100 text-sky-700' : 'bg-white border border-slate-200 text-slate-500 hover:bg-slate-50'
|
||||
}`}>{t(`salesPoints.${ch}.name`)}</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
} from 'lucide-react'
|
||||
import toast from 'react-hot-toast'
|
||||
import client from '../../../api/client'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access'
|
||||
import Button from '../../../ui/Button'
|
||||
import Modal from '../../../ui/Modal'
|
||||
import { ConfirmModal } from '../../../ui/Modal'
|
||||
@@ -40,14 +42,14 @@ const CONDITION_TYPES = [
|
||||
{ value: 'min_item_quantity', label: 'Ελάχιστη ποσότητα προϊόντος' },
|
||||
{ value: 'min_category_qty', label: 'Ελάχιστη ποσότητα κατηγορίας' },
|
||||
{ value: 'min_order_value', label: 'Ελάχιστη αξία παραγγελίας' },
|
||||
{ value: 'order_channel', label: 'Κανάλι παραγγελίας' },
|
||||
{ value: 'order_channel', label: 'Σημείο πώλησης' },
|
||||
{ value: 'price_group_active', label: 'Ομάδα τιμής ενεργή' },
|
||||
{ value: 'user_tier', label: 'Επίπεδο πελάτη (placeholder)' },
|
||||
{ value: 'low_stock', label: 'Χαμηλό απόθεμα (placeholder)' },
|
||||
]
|
||||
|
||||
const DAYS = ['Δευτέρα','Τρίτη','Τετάρτη','Πέμπτη','Παρασκευή','Σάββατο','Κυριακή']
|
||||
const CHANNELS = ['pos','online','qr','takeaway']
|
||||
const CHANNELS = SALES_POINTS // phase 3S: the order_channel condition holds sales points
|
||||
|
||||
const ROUND_OPTIONS = [
|
||||
{ value: '', label: 'Χωρίς στρογγυλοποίηση' },
|
||||
@@ -62,6 +64,7 @@ const ROUND_OPTIONS = [
|
||||
// ─── Condition editor ─────────────────────────────────────────────────────────
|
||||
|
||||
function ConditionEditor({ cond, onChange, onRemove, groups, categories, prepZones }) {
|
||||
const { t } = useTranslation('common')
|
||||
const set = (k, v) => onChange({ ...cond, params: { ...cond.params, [k]: v } })
|
||||
const setType = t => onChange({ condition_type: t, params: {} })
|
||||
|
||||
@@ -175,12 +178,12 @@ function ConditionEditor({ cond, onChange, onRemove, groups, categories, prepZon
|
||||
{CHANNELS.map(ch => (
|
||||
<button type="button" key={ch}
|
||||
onClick={() => {
|
||||
const channels = cond.params.channels ?? []
|
||||
const channels = normalizeSalesPoints(cond.params.channels)
|
||||
set('channels', channels.includes(ch) ? channels.filter(x => x !== ch) : [...channels, ch])
|
||||
}}
|
||||
className={`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${
|
||||
(cond.params.channels ?? []).includes(ch) ? 'bg-sky-100 text-sky-700' : 'bg-white border border-slate-200 text-slate-500 hover:bg-slate-50'
|
||||
}`}>{ch}</button>
|
||||
normalizeSalesPoints(cond.params.channels).includes(ch) ? 'bg-sky-100 text-sky-700' : 'bg-white border border-slate-200 text-slate-500 hover:bg-slate-50'
|
||||
}`}>{t(`salesPoints.${ch}.name`)}</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -7,9 +7,12 @@
|
||||
// useModule('kds') · useCan('catalog.menu.manage') · useCan([a, b]) (any) · useCan([a, b], { all: true })
|
||||
// <Can perm="…" fallback={…}> · <RequireModule module="…">
|
||||
//
|
||||
// SALES_POINTS, IN_PERSON, DIGITAL where an order is sold (phase 3S)
|
||||
//
|
||||
// UI hiding only: the backend checks every request (CS-14).
|
||||
|
||||
export { AccessProvider } from './AccessProvider.jsx'
|
||||
export { useAccess, useModule, useCan, can } from './hooks.js'
|
||||
export { Can, RequireModule, ModuleOff, NoAccess } from './guards.jsx'
|
||||
export { OverrideHost } from './OverrideHost.jsx'
|
||||
export { SALES_POINTS, IN_PERSON, DIGITAL, normalizeSalesPoints } from './salesPoints.js'
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// Sales points (plan phase 3S): where an order is sold. The same fixed list as the backend's
|
||||
// core/sales_points.py; labels are common:salesPoints.<key>.name / .hint.
|
||||
export const SALES_POINTS = ['in_store', 'in_store_takeaway', 'qr_table', 'online_takeaway', 'online_delivery', 'online_preorder']
|
||||
export const IN_PERSON = ['in_store', 'in_store_takeaway']
|
||||
export const DIGITAL = ['qr_table', 'online_takeaway', 'online_delivery', 'online_preorder']
|
||||
|
||||
// the order_channel condition's values before phase 3S → sales points (backend LEGACY_CHANNELS)
|
||||
const LEGACY = { pos: ['in_store'], takeaway: ['in_store_takeaway'], online: ['online_takeaway', 'online_delivery', 'online_preorder'], qr: ['qr_table'] }
|
||||
|
||||
/** Sales points from a list that may hold old channel names; unknown values dropped, no duplicates. */
|
||||
export function normalizeSalesPoints(values) {
|
||||
const out = []
|
||||
for (const v of values ?? []) {
|
||||
for (const sp of SALES_POINTS.includes(v) ? [v] : (LEGACY[v] ?? [])) if (!out.includes(sp)) out.push(sp)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Sales points (phase 3S): the same list and old-value mapping as core/sales_points.py.
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { normalizeSalesPoints, SALES_POINTS } from '../src/salesPoints.js'
|
||||
|
||||
test('sales points: the fixed list and the old channel names', () => {
|
||||
assert.deepEqual(SALES_POINTS, ['in_store', 'in_store_takeaway', 'qr_table', 'online_takeaway', 'online_delivery', 'online_preorder'])
|
||||
assert.deepEqual(normalizeSalesPoints(['pos', 'qr']), ['in_store', 'qr_table'])
|
||||
assert.deepEqual(normalizeSalesPoints(['online', 'online_delivery', 'nope']), ['online_takeaway', 'online_delivery', 'online_preorder'])
|
||||
assert.deepEqual(normalizeSalesPoints(undefined), [])
|
||||
})
|
||||
@@ -50,5 +50,31 @@
|
||||
"noAccessTitle": "Δεν έχετε πρόσβαση σε αυτή τη σελίδα",
|
||||
"noAccessBody": "Ζητήστε την από έναν υπεύθυνο, αν τη χρειάζεστε.",
|
||||
"loadFailed": "Δεν φορτώθηκαν οι ρυθμίσεις του καταστήματος"
|
||||
},
|
||||
"salesPoints": {
|
||||
"in_store": {
|
||||
"name": "Στο κατάστημα",
|
||||
"hint": "Ταμείο και σερβιτόροι, για κατανάλωση εντός"
|
||||
},
|
||||
"in_store_takeaway": {
|
||||
"name": "Πακέτο από το ταμείο",
|
||||
"hint": "Ταμείο, για πακέτο (και τηλεφωνικές παραγγελίες που παραδίδει το κατάστημα)"
|
||||
},
|
||||
"qr_table": {
|
||||
"name": "QR μενού στο τραπέζι",
|
||||
"hint": "Οι πελάτες παραγγέλνουν από το QR μενού στο τραπέζι τους"
|
||||
},
|
||||
"online_takeaway": {
|
||||
"name": "Online, πακέτο",
|
||||
"hint": "Παραγγελία online, παραλαβή από το κατάστημα"
|
||||
},
|
||||
"online_delivery": {
|
||||
"name": "Online, διανομή",
|
||||
"hint": "Παραγγελία online, με παράδοση"
|
||||
},
|
||||
"online_preorder": {
|
||||
"name": "Online, με κράτηση",
|
||||
"hint": "Κράτηση online, το φαγητό έτοιμο με την άφιξη"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,8 @@
|
||||
"error": "Κάτι πήγε στραβά στον διακομιστή (αίτημα {{request_id}})."
|
||||
},
|
||||
"order": {
|
||||
"not_found": "Η παραγγελία {{order_id}} δεν βρέθηκε."
|
||||
"not_found": "Η παραγγελία {{order_id}} δεν βρέθηκε.",
|
||||
"not_sold_here": "Το {{name}} δεν πωλείται για αυτό το είδος παραγγελίας."
|
||||
},
|
||||
"notification": {
|
||||
"not_found": "Η ειδοποίηση {{notification_id}} δεν βρέθηκε."
|
||||
|
||||
@@ -50,5 +50,31 @@
|
||||
"noAccessTitle": "You don't have access to this page",
|
||||
"noAccessBody": "Ask a manager if you need it.",
|
||||
"loadFailed": "Can't load the venue's settings"
|
||||
},
|
||||
"salesPoints": {
|
||||
"in_store": {
|
||||
"name": "In the shop",
|
||||
"hint": "Counter and waiters, eating in"
|
||||
},
|
||||
"in_store_takeaway": {
|
||||
"name": "Takeaway at the counter",
|
||||
"hint": "Counter, to take away (and phone orders the venue delivers)"
|
||||
},
|
||||
"qr_table": {
|
||||
"name": "QR menu at the table",
|
||||
"hint": "Customers order from the QR menu at their table"
|
||||
},
|
||||
"online_takeaway": {
|
||||
"name": "Online, takeaway",
|
||||
"hint": "Ordered online, collected at the venue"
|
||||
},
|
||||
"online_delivery": {
|
||||
"name": "Online, delivery",
|
||||
"hint": "Ordered online, delivered"
|
||||
},
|
||||
"online_preorder": {
|
||||
"name": "Online, with a reservation",
|
||||
"hint": "Reserved online, food ready on arrival"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,8 @@
|
||||
"error": "Something went wrong on the server (request {{request_id}})."
|
||||
},
|
||||
"order": {
|
||||
"not_found": "Order {{order_id}} not found."
|
||||
"not_found": "Order {{order_id}} not found.",
|
||||
"not_sold_here": "{{name}} isn't sold for this kind of order."
|
||||
},
|
||||
"notification": {
|
||||
"not_found": "Notification {{notification_id}} not found."
|
||||
|
||||
@@ -18,7 +18,7 @@ import { useCan, useModule } from '@xenia/access'
|
||||
import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui'
|
||||
import { useLiveEvent } from '../../device/context'
|
||||
import { playChime } from './chime'
|
||||
import { addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart'
|
||||
import { addLine, categoriesWithProducts, forSalesPoint, salesPointFor, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart'
|
||||
import { findOnline, ONLINE_LISTS } from './logic/online'
|
||||
import { zoneCounts } from './logic/tables'
|
||||
import OnlinePanel from './OnlinePanel'
|
||||
@@ -91,10 +91,14 @@ function Counter({ menu, t }) {
|
||||
const setCart = atTable ? setTableCart : setSaleCart
|
||||
const leaveTable = () => { setTableId(null); setTableCart([]) }
|
||||
|
||||
// what's sold for this order (phase 3S): eating in at a table, or the sale's order type,
|
||||
// each product at that sales point's price
|
||||
const point = salesPointFor(atTable ? 'here' : orderType)
|
||||
const sellable = useMemo(() => forSalesPoint(menu.products, point), [menu.products, point])
|
||||
const byId = useMemo(() => new Map(menu.products.map(p => [p.id, p])), [menu.products])
|
||||
const categories = useMemo(() => categoriesWithProducts(menu.categories, menu.products), [menu])
|
||||
const shown = useMemo(() => (query.trim() ? searchProducts(menu.products, query) : productsIn(menu.products, category)),
|
||||
[menu.products, query, category])
|
||||
const categories = useMemo(() => categoriesWithProducts(menu.categories, sellable), [menu.categories, sellable])
|
||||
const shown = useMemo(() => (query.trim() ? searchProducts(sellable, query) : productsIn(sellable, category)),
|
||||
[sellable, query, category])
|
||||
const counts = useMemo(() => zoneCounts(tables.data?.tables ?? []), [tables.data])
|
||||
|
||||
const tap = product => {
|
||||
|
||||
@@ -221,3 +221,16 @@ export function splitPayments(methods, totals) {
|
||||
export const DISCOUNTS = [0, 5, 10, 15, 20, 25, 50, 100]
|
||||
|
||||
const round2 = n => Math.round(n * 100) / 100
|
||||
|
||||
/** The counter's sales point for an order type (phase 3S; backend pos_cart.point_for). */
|
||||
export function salesPointFor(orderType) {
|
||||
return orderType === 'takeaway' ? 'in_store_takeaway' : 'in_store'
|
||||
}
|
||||
|
||||
/** The menu's products sold at a sales point, each with that sales point's price (GET
|
||||
* /api/pos/menu sends `sold_at` and `prices`; older answers: everything, `price`). */
|
||||
export function forSalesPoint(products, point) {
|
||||
return products
|
||||
.filter(p => !p.sold_at || p.sold_at.includes(point))
|
||||
.map(p => (p.prices?.[point] != null ? { ...p, price: p.prices[point] } : p))
|
||||
}
|
||||
|
||||
@@ -173,3 +173,14 @@ test('refunds: picking items, quantities, total, method, approval (3.3e)', async
|
||||
assert.equal(needsApproval(items, pickAll(items)), false)
|
||||
assert.equal(needsApproval([{ ...coffee, mine: false }], { 1: 1 }), true)
|
||||
})
|
||||
|
||||
test('sales points at the counter: what is sold and at which price (phase 3S)', async () => {
|
||||
const { forSalesPoint, salesPointFor } = await import('../src/apps/pos/logic/cart.js')
|
||||
assert.equal(salesPointFor('takeaway'), 'in_store_takeaway')
|
||||
assert.equal(salesPointFor('here'), 'in_store')
|
||||
const cola = { id: 1, price: 3.5, prices: { in_store: 3.5, in_store_takeaway: 2.5 }, sold_at: ['in_store', 'in_store_takeaway'] }
|
||||
const soup = { id: 2, price: 6, prices: { in_store: 6, in_store_takeaway: 6 }, sold_at: ['in_store'] }
|
||||
const old = { id: 3, price: 4 }
|
||||
assert.deepEqual(forSalesPoint([cola, soup, old], 'in_store_takeaway').map(p => [p.id, p.price]), [[1, 2.5], [3, 4]])
|
||||
assert.deepEqual(forSalesPoint([cola, soup, old], 'in_store').map(p => [p.id, p.price]), [[1, 3.5], [2, 6], [3, 4]])
|
||||
})
|
||||
|
||||
@@ -62,7 +62,7 @@ export function SSEProvider({ children }) {
|
||||
const snapshotProducts = useCallback(async () => {
|
||||
try {
|
||||
const [prodRes, catRes] = await Promise.all([
|
||||
client.get('/api/products/'),
|
||||
client.get('/api/products/', { params: { sold_at: 'in_store,in_store_takeaway' } }), // phase 3S
|
||||
client.get('/api/products/categories'),
|
||||
])
|
||||
await db.products.bulkPut(prodRes.data)
|
||||
|
||||
@@ -7,7 +7,7 @@ export const PRODUCTS_KEY = ['products']
|
||||
|
||||
async function fetchAndCacheProducts() {
|
||||
const [prodRes, catRes] = await Promise.all([
|
||||
client.get('/api/products/'),
|
||||
client.get('/api/products/', { params: { sold_at: 'in_store,in_store_takeaway' } }), // phase 3S
|
||||
client.get('/api/products/categories'),
|
||||
])
|
||||
const products = prodRes.data
|
||||
|
||||
Reference in New Issue
Block a user