Files
xenia-pos-local/local_backend/tests/test_sales_points.py
T
bonaminandClaude Opus 5.5 ffeb2b45cb feat: the menu snapshot carries a price per sales point; pulled orders keep the cloud's sales point and table (platform-v2 3S, S.2)
- services/cloud_sync.menu_snapshot(db) (split out of the push, tested): sold_at + prices
  per customer-app sales point from the pricing engine; digital_price = the QR menu's.
- store_online_orders: sales_point from the cloud (older clouds: from the type), takeaway
  orders typed takeaway, the QR menu's table in front of the customer's note.
- manager e2e: waits for the live connection (html[data-live]) instead of a fixed 1.5 s,
  and for the server to record "read" (two timing races seen in a full run).
- Tests: +2 in test_sales_points.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:38:46 +02:00

209 lines
13 KiB
Python

"""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"}
def test_the_cloud_menu_carries_a_price_per_sales_point(db, menu):
"""S.2: the snapshot says where each product is sold online and its price there (the cloud
charges these), from the same price rules as the counter."""
from models.product import ProductCategory
from services.cloud_sync import menu_snapshot
cola = menu["coffee"]
cola.base_price = 3.5
for prod in (cola, menu["burger"]):
if not prod.memberships:
db.add(ProductCategory(product_id=prod.id, category_id=prod.primary_category_id, sort_order=0))
db.commit()
takeaway_price(db, cola, 2.5, channels=("online_takeaway",))
sold_at(db, menu["burger"], ["in_store"]) # not sold by the customer apps
snap, _ = menu_snapshot(db)
products = {p["id"]: p for c in snap["categories"] for p in c["products"]}
assert menu["burger"].id not in products
p = products[cola.id]
assert p["prices"] == {"qr_table": 3.5, "online_takeaway": 2.5, "online_delivery": 3.5, "online_preorder": 3.5}
assert p["digital_price"] == 3.5 and p["sold_at"] == ["qr_table", "online_takeaway", "online_delivery", "online_preorder"]
def test_pulled_orders_take_the_clouds_sales_point_and_table(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()
o = db.get(Order, pulled(db, menu, 701, "dine_in", table_label="5", customer_notes="No ice"))
assert (o.sales_point, o.online_customer_notes, o.order_type) == ("qr_table", "Table 5 · No ice", "here")
o = db.get(Order, pulled(db, menu, 702, "takeaway", sales_point="online_takeaway"))
assert (o.sales_point, o.order_type) == ("online_takeaway", "takeaway")