feat(backend,terminal): online orders on the counter POS (platform-v2 step 3.3d)
- Counter POS gets an "Online" mode (module on + connect_orders.manage): New / In
progress / Finished, a chime on arrival (and every 30 s while one waits), badge,
toast in any mode; the order panel offers only the next step: accept / reject with
a reason, preparing, ready or out for delivery, then take the payment (shared
PaymentDialog, drawer, shift) and mark delivered/served.
- connect_orders router on v2 conventions: require(connect_orders.manage), error
codes online.not_found / online.status_changed, the cloud's step order enforced,
audit rows, GET /api/connect/orders/board. POS device scope gains connect_orders.*;
barista and barman get the key by default.
- Fixes: the KDS showed online orders before acceptance; accepting printed no
kitchen tickets; a pull whose synced mark failed stored the order twice
(store_online_orders skips known cloud ids); pulled orders lacked the business day
and delivery type; rejected orders kept active items; delivered sets closed_at/by.
- Online orders belong to holders of connect_orders.manage (_can_access_order), so
the counter pays them with POST /api/pos/orders/{id}/pay.
- Tests: test_pos_online.py (5), terminal unit +1, terminal.mjs +17 with a fake
cloud (pull, synced, status mirror); fixed a timing race in a 3.3c check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -327,6 +327,61 @@ async def _push_menu_snapshot():
|
||||
logger.warning("Menu snapshot push failed: %s", e)
|
||||
|
||||
|
||||
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
|
||||
(an earlier pull whose "synced" mark didn't reach the cloud) isn't stored twice.
|
||||
Returns {cloud id: local order id}; a repeated order maps to minus its local id."""
|
||||
from models.business_day import BusinessDay
|
||||
from models.order import Order, OrderItem
|
||||
from models.user import User
|
||||
|
||||
# the opener is the first account with the manager dashboard (orders need one)
|
||||
system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first()
|
||||
opener_id = system_user.id if system_user else 1
|
||||
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
out = {}
|
||||
for cloud_order in orders:
|
||||
known = db.query(Order).filter(Order.source == "online",
|
||||
Order.online_order_cloud_id == cloud_order["id"]).first()
|
||||
if known is not None:
|
||||
out[cloud_order["id"]] = -known.id
|
||||
continue
|
||||
local_order = Order(
|
||||
table_id=None,
|
||||
opened_by=opener_id,
|
||||
status="open",
|
||||
source="online",
|
||||
order_type="delivery" if cloud_order.get("order_type") == "delivery" else "here",
|
||||
business_day_id=day.id if day else None,
|
||||
online_order_ref=cloud_order["public_ref"],
|
||||
online_order_cloud_id=cloud_order["id"],
|
||||
online_status="pending_acceptance",
|
||||
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_order_type=cloud_order.get("order_type"),
|
||||
)
|
||||
db.add(local_order)
|
||||
db.flush()
|
||||
for item in json.loads(cloud_order.get("items_json") or "[]"):
|
||||
db.add(OrderItem(
|
||||
order_id=local_order.id,
|
||||
product_id=item.get("product_id"),
|
||||
added_by=opener_id,
|
||||
quantity=item.get("quantity", 1),
|
||||
unit_price=item.get("unit_price", 0.0),
|
||||
selected_options=json.dumps(item.get("options", [])),
|
||||
status="active",
|
||||
printed=False,
|
||||
))
|
||||
db.commit()
|
||||
out[cloud_order["id"]] = local_order.id
|
||||
logger.info("Online order %s pulled and created as local order %d", cloud_order["public_ref"], local_order.id)
|
||||
return out
|
||||
|
||||
|
||||
async def _pull_pending_orders():
|
||||
"""Fetch online orders from cloud that haven't been synced to local yet."""
|
||||
if not settings.SITE_ID or not settings.CLOUD_URL:
|
||||
@@ -349,75 +404,31 @@ async def _pull_pending_orders():
|
||||
return
|
||||
|
||||
from database import SessionLocal
|
||||
from models.order import Order, OrderItem
|
||||
from models.product import Product
|
||||
from services.sse_bus import broadcast_sync
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# Use a system user id=1 (first manager/sysadmin) as the opener
|
||||
from models.user import User
|
||||
system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first()
|
||||
opener_id = system_user.id if system_user else 1
|
||||
|
||||
for cloud_order in orders:
|
||||
# Create local Order row — no table_id for online orders
|
||||
local_order = Order(
|
||||
table_id=None,
|
||||
opened_by=opener_id,
|
||||
status="open",
|
||||
source="online",
|
||||
online_order_ref=cloud_order["public_ref"],
|
||||
online_order_cloud_id=cloud_order["id"],
|
||||
online_status="pending_acceptance",
|
||||
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_order_type=cloud_order.get("order_type"),
|
||||
)
|
||||
db.add(local_order)
|
||||
db.flush() # get local_order.id
|
||||
|
||||
# Create OrderItem rows
|
||||
items = json.loads(cloud_order.get("items_json", "[]"))
|
||||
for item in items:
|
||||
product = db.query(Product).filter(
|
||||
Product.id == item.get("product_id")
|
||||
).first()
|
||||
db.add(OrderItem(
|
||||
order_id=local_order.id,
|
||||
product_id=item.get("product_id"),
|
||||
added_by=opener_id,
|
||||
quantity=item.get("quantity", 1),
|
||||
unit_price=item.get("unit_price", 0.0),
|
||||
selected_options=json.dumps(item.get("options", [])),
|
||||
status="active",
|
||||
printed=False,
|
||||
))
|
||||
|
||||
db.commit()
|
||||
|
||||
# Mark synced on cloud
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
await client.post(
|
||||
f"{settings.CLOUD_URL}/api/orders/{cloud_order['id']}/synced",
|
||||
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
|
||||
json={"local_order_id": local_order.id},
|
||||
)
|
||||
|
||||
logger.info("Online order %s pulled and created as local order %d",
|
||||
cloud_order["public_ref"], local_order.id)
|
||||
|
||||
db.close()
|
||||
|
||||
# Broadcast SSE so the manager dashboard lights up
|
||||
broadcast_sync("online_order_received", {"count": len(orders)})
|
||||
|
||||
stored = store_online_orders(db, orders)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
db.close()
|
||||
logger.error("Failed to process pulled orders: %s", e)
|
||||
return
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
new_ids = [local_id for local_id in stored.values() if local_id > 0]
|
||||
if new_ids:
|
||||
# the counter POS and the manager light up (and ring) at once
|
||||
broadcast_sync("online_order_received", {"count": len(new_ids), "order_ids": new_ids})
|
||||
|
||||
# Mark synced on the cloud (also orders stored by an earlier pull whose mark failed)
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
for cloud_id, local_id in stored.items():
|
||||
await client.post(
|
||||
f"{settings.CLOUD_URL}/api/orders/{cloud_id}/synced",
|
||||
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
|
||||
json={"local_order_id": abs(local_id)},
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning("Order pull failed: %s", e)
|
||||
|
||||
Reference in New Issue
Block a user