diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 8ee1e66..19f8242 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -249,65 +249,64 @@ async def _push_product_images(db, products): logger.warning("Image push failed for product %d: %s", p.id, e) +def menu_snapshot(db) -> tuple[dict, list]: + """The customer apps' menu (contract C-2): top-level categories with every product listed + in them (D-23) that is sold at a customer-app sales point (phase 3S), each with a price + per such sales point from the pricing engine at this moment (`prices`, what the cloud + charges since S.2), `digital_price` = the QR menu's (older clouds) and its quick options. + → ({"categories": [...]}, the products once each)""" + from models.product import Category, Product, ProductCategory + from services.pos_cart import unit_prices + categories = db.query(Category).filter(Category.parent_id == None).all() # noqa: E711 + payload_categories = [] + all_products = [] + for cat in categories: + products = ( + db.query(Product) + .join(ProductCategory, ProductCategory.product_id == Product.id) + .filter(ProductCategory.category_id == cat.id, Product.lifecycle_status == "active") + .order_by(ProductCategory.sort_order, Product.id) + .all() + ) + products = [p for p in products if set(sales_points.sold_at(p)) & set(sales_points.DIGITAL)] + by_point = {sp: unit_prices(db, products, sp) for sp in sales_points.DIGITAL} + all_products.extend(p for p in products if p not in all_products) # once, even if listed twice + product_list = [] + for i, p in enumerate(products): + sold = [sp for sp in sales_points.sold_at(p) if sp in sales_points.DIGITAL] + product_list.append({ + "id": p.id, + "name": p.name, + "digital_name": p.digital_name, + "digital_description": p.digital_description, + "digital_price": round(by_point[sales_points.QR_TABLE][i], 2), + "base_price": p.base_price, + "digital_discount": 0, + "sold_at": sold, + "prices": {sp: round(by_point[sp][i], 2) for sp in sold}, + "digital_available": bool(p.digital_available), + "digital_image_url": p.digital_image_url, + "image_url": p.image_url, + "quick_options": [{"id": o.id, "name": o.name, "price": o.price} for o in p.quick_options], + }) + if product_list: + payload_categories.append({"id": cat.id, "name": cat.name, "sort_order": cat.sort_order, + "products": product_list}) + return {"categories": payload_categories}, all_products + + async def _push_menu_snapshot(): - """Serialize all digital-visible products+categories and POST to cloud.""" + """Build the customer apps' menu (menu_snapshot) and POST it to the cloud.""" if not settings.SITE_ID or not settings.CLOUD_URL: return try: from database import SessionLocal - from models.product import Category, Product, ProductCategory db = SessionLocal() try: - categories = db.query(Category).filter(Category.parent_id == None).all() - payload_categories = [] - all_products = [] - for cat in categories: - # every product LISTED in this category, in its order there (D-23) - products = ( - db.query(Product) - .join(ProductCategory, ProductCategory.product_id == Product.id) - .filter( - ProductCategory.category_id == cat.id, - 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, 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": round(qr_price, 2), - "base_price": p.base_price, - "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, - "quick_options": [ - {"id": o.id, "name": o.name, "price": o.price} - for o in p.quick_options - ], - }) - if product_list: - payload_categories.append({ - "id": cat.id, - "name": cat.name, - "sort_order": cat.sort_order, - "products": product_list, - }) - + snapshot, all_products = menu_snapshot(db) + payload_categories = snapshot["categories"] snapshot_json = json.dumps({"categories": payload_categories}) # Resolve numeric site_id from license state (set by heartbeat response) @@ -333,6 +332,16 @@ async def _push_menu_snapshot(): logger.warning("Menu snapshot push failed: %s", e) +def _with_table(cloud_order: dict): + """The customer's note, with the QR menu's table in front (S.2; S.7 puts the order on the + table itself).""" + table = (cloud_order.get("table_label") or "").strip() + notes = (cloud_order.get("customer_notes") or "").strip() + if not table: + return notes or None + return f"Table {table}" + (f" · {notes}" if notes else "") + + def store_online_orders(db, orders: list[dict]) -> dict: """Store online orders as the cloud hands them over (GET /api/orders/pending/{site}): one local order each, waiting for acceptance (plan step 3.3d). An order already stored @@ -358,8 +367,11 @@ def store_online_orders(db, orders: list[dict]) -> dict: opened_by=opener_id, 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")), + order_type="delivery" if cloud_order.get("order_type") == "delivery" else ( + "takeaway" if cloud_order.get("order_type") == "takeaway" else "here"), + # the cloud says where it was sold since S.2 (older clouds: from the order type) + sales_point=(cloud_order.get("sales_point") if cloud_order.get("sales_point") in sales_points.DIGITAL + else 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"], @@ -367,7 +379,7 @@ def store_online_orders(db, orders: list[dict]) -> dict: online_customer_name=cloud_order.get("customer_name"), online_customer_phone=cloud_order.get("customer_phone"), online_customer_address=cloud_order.get("customer_address"), - online_customer_notes=cloud_order.get("customer_notes"), + online_customer_notes=_with_table(cloud_order), online_order_type=cloud_order.get("order_type"), ) db.add(local_order) diff --git a/local_backend/tests/test_sales_points.py b/local_backend/tests/test_sales_points.py index 4287c38..f2c03a3 100644 --- a/local_backend/tests/test_sales_points.py +++ b/local_backend/tests/test_sales_points.py @@ -172,3 +172,37 @@ def test_migration_moves_digital_prices_and_visibility(tmp_path): (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") diff --git a/manager_dashboard/src/live/LiveProvider.jsx b/manager_dashboard/src/live/LiveProvider.jsx index 26139de..d6537bf 100644 --- a/manager_dashboard/src/live/LiveProvider.jsx +++ b/manager_dashboard/src/live/LiveProvider.jsx @@ -27,10 +27,16 @@ export default function LiveProvider({ children }) { url: () => wsUrlFor(`/api/ws/connect?token=${encodeURIComponent(token)}`), cursor: { load: () => seq, save: s => { seq = s } }, onEvent: emit, - onReady: () => emit('ready', null), + onReady: () => { + document.documentElement.dataset.live = 'ready' // tests wait for this instead of a fixed sleep + emit('ready', null) + }, }) live.start() - return () => live.stop() + return () => { + live.stop() + delete document.documentElement.dataset.live + } }, [token]) return {children} diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 5c15eef..c1acb94 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -483,7 +483,7 @@ try { await page.getByTestId('notif-count').waitFor({ state: 'detached', timeout: 5000 }).catch(() => {}) r.check('bell: "mark all as read" clears the count', await page.getByTestId('notif-count').count() === 0) await bell.click() // close - await sleep(1500) // the live socket is up (opened with the shell) + await page.waitForSelector('html[data-live="ready"]', { timeout: 10_000 }).catch(() => {}) // the live socket is up await supportLogin(backend.url) await page.getByTestId('notif-count').waitFor({ timeout: 8000 }).catch(() => {}) r.check('bell: a new one arrives live (no reload): count 1 and a toast', @@ -492,8 +492,13 @@ try { const unreadItem = panel.locator('[data-read="false"]').first() await unreadItem.click() await page.waitForFunction(() => !document.querySelector('[data-testid="notif-count"]'), null, { timeout: 5000 }).catch(() => {}) - r.check('bell: opening it marks it read', await page.getByTestId('notif-count').count() === 0 && - (await api('GET', '/api/platform/notifications', { token: boss })).unread === 0) + let notifAfter = await api('GET', '/api/platform/notifications', { token: boss }) + for (let i = 0; i < 30 && notifAfter.unread !== 0; i++) { // the count clears at once; the server hears it a moment later + await sleep(100) + notifAfter = await api('GET', '/api/platform/notifications', { token: boss }) + } + r.check('bell: opening it marks it read', await page.getByTestId('notif-count').count() === 0 && notifAfter.unread === 0, + JSON.stringify({ shown: await page.getByTestId('notif-count').textContent().catch(() => null), unread: notifAfter.unread })) await page.screenshot({ path: path.join(OUT, 'manager-notifications.png') }) await page.keyboard.press('Escape')