- order_items.source (Alembic 0025): waiter | counter | qr | online, set by the server (orders.add_priced_items: the phone / manager 'waiter', the counter 'counter'; the QR menu's lines 'qr', online orders 'online'; a split line keeps its source); lines of existing online orders backfilled 'online'; in the order's item output. - Waiter: lines the guests sent from the QR menu (or an online order) carry a "📱 QR" / "🌐 Online" mark; the qr_order message's banner has "Open the table", and in the bell's list the message opens it. - Tests: source per channel, migration 0025, QR placement marks 'qr'; waiter e2e +1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
764 lines
32 KiB
Python
764 lines
32 KiB
Python
"""
|
|
Periodic cloud check-in. Runs every 5 minutes as an asyncio background task.
|
|
|
|
Licensing (KI-006, see services/license.py): the cloud is needed to RENEW a
|
|
license, not to RUN one. Each heartbeat returns a signed license token; the
|
|
site stores it and enforces it offline — until expiry (+5 days grace), however
|
|
long it has no internet. apply_license() re-evaluates the stored token without
|
|
network: at startup, after every heartbeat attempt and when a workday closes.
|
|
|
|
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
|
|
import json
|
|
import logging
|
|
import os
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
|
|
from config import settings
|
|
from services.license_state import license_state
|
|
from services.license import evaluate, parse_dt, verify_token
|
|
|
|
ORDER_POLL_INTERVAL = settings.CONNECT_SYNC_INTERVAL_SECONDS
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
SYNC_INTERVAL_SECONDS = 5 * 60 # 5 minutes
|
|
|
|
|
|
def _data_dir() -> Path:
|
|
"""Directory of the SQLite database — the persistent data volume in Docker."""
|
|
from services.tls_identity import tls_dir
|
|
return tls_dir().parent
|
|
|
|
|
|
# In the data volume: it must survive container re-creation (image updates,
|
|
# compose changes), or an offline site would lose its license. Earlier versions
|
|
# kept it inside the container at local_backend/license_state.json.
|
|
STATE_FILE = _data_dir() / "license_state.json"
|
|
LEGACY_STATE_FILE = Path(__file__).parent.parent / "license_state.json"
|
|
|
|
|
|
def _load_persisted_state():
|
|
for path in (STATE_FILE, LEGACY_STATE_FILE):
|
|
if path.exists():
|
|
try:
|
|
license_state.update(json.loads(path.read_text()))
|
|
logger.info("Loaded persisted license state from %s", path)
|
|
return
|
|
except Exception as e:
|
|
logger.warning("Could not load license state file %s: %s", path, e)
|
|
|
|
|
|
def _persist_state():
|
|
try:
|
|
STATE_FILE.write_text(json.dumps(license_state))
|
|
except Exception as e:
|
|
logger.warning("Could not persist license state: %s", e)
|
|
|
|
|
|
def _latest_activity(db) -> datetime | None:
|
|
"""Newest order timestamp in the database — the clock can't be set before it."""
|
|
from sqlalchemy import func
|
|
from models.order import Order, OrderItem
|
|
stamps = [db.query(func.max(Order.opened_at)).scalar(), db.query(func.max(OrderItem.added_at)).scalar()]
|
|
stamps = [parse_dt(x) for x in stamps if x]
|
|
return max(stamps, default=None)
|
|
|
|
|
|
def apply_license(now: datetime | None = None) -> None:
|
|
"""Re-evaluate the license from the stored signed token (no network) and install
|
|
the resulting module entitlements (core/modules/entitlements.py).
|
|
|
|
Called at startup, after every heartbeat and when a business day closes (expiry,
|
|
grace and remote locks are deferred to that moment, never mid-service).
|
|
LICENSE_MODE=off (dev machines only): every module, no limits.
|
|
No SITE_ID / no valid v2 token / expired / inactive / locked: the free tier."""
|
|
from core.modules import entitlements
|
|
|
|
if settings.LICENSE_MODE == "off":
|
|
license_state.update({"license_mode": "off", "licensed": True, "license_problem": None,
|
|
"entitlement_mode": "dev", "locked": False, "lock_pending": False})
|
|
entitlements.set_dev()
|
|
return
|
|
|
|
from database import SessionLocal
|
|
from models.business_day import BusinessDay
|
|
|
|
now = now or utcnow()
|
|
payload = verify_token(license_state.get("license_token"), settings.SITE_ID) if settings.SITE_ID else None
|
|
db = SessionLocal()
|
|
try:
|
|
workday_open = db.query(BusinessDay).filter(BusinessDay.status == "open").first() is not None
|
|
latest_activity = _latest_activity(db)
|
|
finally:
|
|
db.close()
|
|
|
|
floors = [parse_dt(license_state.get("time_high_water")), latest_activity,
|
|
parse_dt(payload["issued_at"]) if payload else None]
|
|
floor = max((f for f in floors if f), default=None)
|
|
result = evaluate(payload, now, floor, workday_open)
|
|
if result["license_problem"] != "clock":
|
|
license_state["time_high_water"] = max(floor or now, now).isoformat()
|
|
|
|
if payload: # lock requested by the cloud — deferred while a workday is open
|
|
if payload.get("locked"):
|
|
if workday_open and not license_state.get("locked"):
|
|
license_state["lock_pending"] = True
|
|
else:
|
|
license_state["lock_pending"] = False
|
|
license_state["locked"] = True
|
|
else:
|
|
license_state["lock_pending"] = False
|
|
license_state["locked"] = False
|
|
|
|
ent = entitlements.compute(payload if result["license_problem"] != "clock" else None,
|
|
result["licensed"], bool(license_state.get("locked")), now, workday_open,
|
|
result["license_problem"])
|
|
last_sync = parse_dt(license_state.get("last_sync"))
|
|
license_state.update({**result, "license_mode": "enforced", "entitlement_mode": ent.mode,
|
|
"offline_days": (now - last_sync).days if last_sync else None})
|
|
_persist_state()
|
|
entitlements.set_current(ent)
|
|
from core.notifications import check_license_expiry
|
|
check_license_expiry(result.get("expires_at"), result.get("days_until_expiry"), bool(result["licensed"]))
|
|
if result["license_problem"]:
|
|
logger.warning("License problem: %s (licensed=%s, entitlements=%s)",
|
|
result["license_problem"], result["licensed"], ent.mode)
|
|
|
|
|
|
def _get_local_ip() -> str | None:
|
|
"""The server's LAN IP as phones see it — same resolver as the manager's
|
|
pairing QR (override → live detection → HOST_IP), see services/lan_ip.py.
|
|
No socket tricks: inside Docker they return the unreachable bridge IP."""
|
|
from database import SessionLocal
|
|
from services.lan_ip import resolve_lan_ip
|
|
db = SessionLocal()
|
|
try:
|
|
return resolve_lan_ip(db)["effective"]
|
|
except Exception:
|
|
return None
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def module_catalog() -> list[dict]:
|
|
"""What this site's code can run (heartbeat C-1, D-20): the cloud's module editor is
|
|
built from it, so the sysadmin can only license modules the site knows."""
|
|
from core.modules.registry import registry
|
|
return [{"key": m.key, "kind": m.kind, "name": m.name, "depends": list(m.depends),
|
|
"limits": [{"key": lim.key, "description": lim.description, "free": lim.free,
|
|
"licensed_default": lim.licensed_default} for lim in m.limits]}
|
|
for m in registry().values()]
|
|
|
|
|
|
async def _sync_once():
|
|
if not settings.SITE_ID or not settings.CLOUD_URL:
|
|
logger.debug("No SITE_ID/CLOUD_URL configured — skipping cloud sync")
|
|
return
|
|
|
|
try:
|
|
local_ip = _get_local_ip()
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
resp = await client.post(
|
|
f"{settings.CLOUD_URL}/api/heartbeat/",
|
|
headers={
|
|
"X-Site-ID": settings.SITE_ID,
|
|
"X-Site-Key": settings.SITE_KEY,
|
|
},
|
|
json={"version": settings.VERSION, "local_ip": local_ip, "module_catalog": module_catalog()},
|
|
)
|
|
resp.raise_for_status()
|
|
data = resp.json()
|
|
|
|
token = data.get("license_token")
|
|
if token and verify_token(token, settings.SITE_ID):
|
|
license_state["license_token"] = token
|
|
elif token:
|
|
logger.error("Cloud sent a license token that does not verify (not v2?) - keeping the previous one")
|
|
else:
|
|
logger.error("Cloud sent no license token - keeping the previous one")
|
|
|
|
license_state.update({
|
|
"latest_version": data.get("latest_version"),
|
|
"waiter_domain": data.get("waiter_domain"),
|
|
"site_numeric_id": data.get("site_numeric_id"),
|
|
"apps_url": data.get("apps_url"), # the customer apps' address (S.7: table QR codes)
|
|
"last_sync": utcnow().isoformat(),
|
|
"sync_failed": False,
|
|
})
|
|
logger.info("Cloud sync OK (signed license: %s)", bool(token))
|
|
|
|
except Exception as e:
|
|
logger.warning("Cloud sync failed: %s", e)
|
|
license_state["sync_failed"] = True
|
|
|
|
# Online or not: the stored signed license decides (no more 72h offline rule)
|
|
apply_license()
|
|
|
|
IMAGE_DIR = Path("/app/data/product_images")
|
|
|
|
|
|
async def _push_product_images(db, products):
|
|
"""Upload the local image file for each product whose picture changed since
|
|
the last successful push (tracked via Product.cloud_image_hash), so the
|
|
public QR menu can show it without needing a manually-set digital_image_url.
|
|
Skips products that already have a manual digital_image_url override."""
|
|
import hashlib
|
|
|
|
site_numeric_id = license_state.get("site_numeric_id")
|
|
if not site_numeric_id:
|
|
return
|
|
|
|
for p in products:
|
|
if p.digital_image_url or not p.image_url:
|
|
continue
|
|
|
|
filename = os.path.basename(p.image_url)
|
|
filepath = IMAGE_DIR / filename
|
|
if not filepath.exists():
|
|
continue
|
|
|
|
try:
|
|
contents = filepath.read_bytes()
|
|
image_hash = hashlib.sha256(contents).hexdigest()
|
|
if image_hash == p.cloud_image_hash:
|
|
continue
|
|
|
|
async with httpx.AsyncClient(timeout=20) as client:
|
|
resp = await client.post(
|
|
f"{settings.CLOUD_URL}/api/menu/sync-image",
|
|
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
|
|
data={"product_id": str(p.id)},
|
|
files={"file": (filename, contents)},
|
|
)
|
|
resp.raise_for_status()
|
|
|
|
p.cloud_image_hash = image_hash
|
|
db.commit()
|
|
logger.info("Pushed image for product %d to cloud", p.id)
|
|
|
|
except Exception as e:
|
|
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})
|
|
# delivery areas and fee rules (S.3): the cloud applies them at checkout with the same
|
|
# engine (services/fees.py); the venue's time zone says what "22:00" and "Saturday" mean
|
|
from core.timeutil import venue_tz
|
|
from routers.fees import fees_payload, ordering_settings
|
|
# the tables' QR codes (S.7): only their tokens' hashes, and whether ordering at the table is on
|
|
from services import table_qr
|
|
qr = table_qr.snapshot(db)
|
|
db.commit()
|
|
return {"categories": payload_categories, "fees": fees_payload(db), "ordering": ordering_settings(db),
|
|
"timezone": venue_tz().key, "qr": qr}, all_products
|
|
|
|
|
|
async def _push_menu_snapshot():
|
|
"""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
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
snapshot, all_products = menu_snapshot(db)
|
|
payload_categories = snapshot["categories"]
|
|
snapshot_json = json.dumps(snapshot)
|
|
|
|
# Resolve numeric site_id from license state (set by heartbeat response)
|
|
site_numeric_id = license_state.get("site_numeric_id")
|
|
if not site_numeric_id:
|
|
logger.debug("Menu push skipped — site_numeric_id not yet known")
|
|
return
|
|
|
|
async with httpx.AsyncClient(timeout=15) as client:
|
|
resp = await client.post(
|
|
f"{settings.CLOUD_URL}/api/menu/sync",
|
|
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
|
|
json={"site_id": site_numeric_id, "snapshot_json": snapshot_json},
|
|
)
|
|
resp.raise_for_status()
|
|
logger.info("Menu snapshot pushed (%d categories)", len(payload_categories))
|
|
|
|
await _push_product_images(db, all_products)
|
|
finally:
|
|
db.close()
|
|
|
|
except Exception as e:
|
|
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], booked: list | None = None, at_table: list | None = None) -> 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.
|
|
|
|
Phase 3S, S.5: the order keeps the customer's time and delivery area; the cloud's prices
|
|
are what the customer pays (items at the cloud's unit prices, the delivery fee as a
|
|
system-product line, services/system_products.py), and the site's own engine checks them
|
|
(services/online_check.py: a difference is kept on the order and shown, never changed).
|
|
|
|
S.6: table bookings ("reservation", "preorder") become Reservations waiting to be confirmed
|
|
(services/online_reservations.py); their ids go into `booked` (new ones) and the map.
|
|
|
|
S.7: a QR-menu order with a table (from a valid table QR token) goes straight onto that
|
|
table's order (services/qr_orders.py); its cloud id goes into `at_table` (the puller tells
|
|
the cloud it reached the kitchen). Without a usable table it waits at the counter as before."""
|
|
from models.business_day import BusinessDay
|
|
from models.order import Order, OrderItem
|
|
from models.user import User
|
|
from services import online_check, online_reservations, qr_orders, system_products
|
|
|
|
# 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:
|
|
if cloud_order.get("order_type") == "dine_in" and cloud_order.get("table_id"):
|
|
placed_in = qr_orders.already_placed(db, cloud_order)
|
|
if placed_in is not None:
|
|
out[cloud_order["id"]] = -placed_in
|
|
if at_table is not None:
|
|
at_table.append(cloud_order["id"]) # its "in the kitchen" may not have reached the cloud
|
|
continue
|
|
placed = qr_orders.place(db, cloud_order, opener_id)
|
|
if placed is not None:
|
|
db.commit()
|
|
qr_orders.after(db, placed, opener_id)
|
|
out[cloud_order["id"]] = placed["order"].id
|
|
if at_table is not None:
|
|
at_table.append(cloud_order["id"])
|
|
logger.info("QR order %s placed on table %s (order %d)", cloud_order["public_ref"], placed["table"].id, placed["order"].id)
|
|
continue
|
|
db.rollback()
|
|
if cloud_order.get("order_type") in ("reservation", "preorder"):
|
|
seen = online_reservations.known(db, cloud_order["id"])
|
|
if seen is not None:
|
|
out[cloud_order["id"]] = -seen.id
|
|
continue
|
|
r = online_reservations.store(db, cloud_order, sales_points.ONLINE_PREORDER)
|
|
db.commit()
|
|
out[cloud_order["id"]] = r.id
|
|
if booked is not None:
|
|
booked.append(r.id)
|
|
logger.info("Online booking %s pulled as reservation %d", cloud_order["public_ref"], r.id)
|
|
continue
|
|
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
|
|
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")))
|
|
diff = online_check.diff(db, cloud_order, point)
|
|
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 (
|
|
"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=point,
|
|
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=_with_table(cloud_order),
|
|
online_order_type=cloud_order.get("order_type"),
|
|
online_delivery_area=cloud_order.get("delivery_area"),
|
|
online_price_diff=json.dumps(diff) if diff else None,
|
|
requested_for=_aware(cloud_order.get("requested_for")),
|
|
)
|
|
db.add(local_order)
|
|
db.flush()
|
|
add_cloud_items(db, local_order.id, opener_id, json.loads(cloud_order.get("items_json") or "[]"))
|
|
fee = round(float(cloud_order.get("delivery_fee") or 0.0), 2)
|
|
if fee > 0:
|
|
fee_product = system_products.get(db, system_products.DELIVERY_FEE)
|
|
db.add(OrderItem(
|
|
order_id=local_order.id, product_id=fee_product.id, added_by=opener_id, quantity=1,
|
|
unit_price=fee, unit_cost=0.0, selected_options="[]", status="active",
|
|
# not for the kitchen: never printed on a ticket, never on the KDS
|
|
printed=True, kds_status="served",
|
|
))
|
|
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)
|
|
if diff:
|
|
logger.warning("Online order %s: the site prices it at %.2f, the cloud charged %.2f",
|
|
cloud_order["public_ref"], diff["site_total"], diff["cloud_total"])
|
|
return out
|
|
|
|
|
|
def add_cloud_items(db, order_id: int, opener_id: int, items: list, source: str = "online") -> list:
|
|
"""The cloud's lines as order items, at the cloud's prices (what the customer pays)."""
|
|
from models.order import OrderItem
|
|
out = []
|
|
for item in items:
|
|
row = OrderItem(
|
|
order_id=order_id,
|
|
source=source,
|
|
product_id=item.get("product_id"),
|
|
added_by=opener_id,
|
|
quantity=item.get("quantity", 1),
|
|
unit_price=item.get("unit_price", 0.0),
|
|
unit_cost=_cost(db, item.get("product_id")),
|
|
# the site's entry shape (services/pos_cart.py: quick add-ons, prices included in unit_price)
|
|
selected_options=json.dumps([
|
|
{"id": o.get("id"), "name": o.get("name"), "price_delta": o.get("price", 0.0), "type": "quick"}
|
|
if isinstance(o, dict) else o for o in item.get("options", [])]),
|
|
status="active",
|
|
printed=False,
|
|
)
|
|
db.add(row)
|
|
out.append(row)
|
|
return out
|
|
|
|
|
|
def online_opener_id(db) -> int:
|
|
"""Orders need an opener: the first account with the manager dashboard."""
|
|
from models.user import User
|
|
system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first()
|
|
return system_user.id if system_user else 1
|
|
|
|
|
|
def _aware(raw):
|
|
"""An ISO time from the cloud → aware UTC (naive = UTC); None for none or garbage."""
|
|
if not raw:
|
|
return None
|
|
try:
|
|
when = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
|
|
except ValueError:
|
|
return None
|
|
return when if when.tzinfo else when.replace(tzinfo=timezone.utc)
|
|
|
|
|
|
def _cost(db, product_id):
|
|
"""The product's cost now (the snapshot every order item keeps, phase 2A), or None."""
|
|
from models.product import Product
|
|
product = db.get(Product, product_id) if isinstance(product_id, int) else None
|
|
if product is None:
|
|
return None
|
|
if product.cost_breakdown:
|
|
try:
|
|
total = sum(e.get("amount", 0.0) for e in json.loads(product.cost_breakdown) if isinstance(e, dict))
|
|
if total > 0:
|
|
return total
|
|
except (TypeError, ValueError):
|
|
pass
|
|
return product.cost_simple or None
|
|
|
|
|
|
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:
|
|
return
|
|
|
|
site_numeric_id = license_state.get("site_numeric_id")
|
|
if not site_numeric_id:
|
|
return
|
|
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
resp = await client.get(
|
|
f"{settings.CLOUD_URL}/api/orders/pending/{site_numeric_id}",
|
|
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
|
|
)
|
|
resp.raise_for_status()
|
|
orders = resp.json()
|
|
|
|
if not orders:
|
|
return
|
|
|
|
from database import SessionLocal
|
|
from services.ws_bus import broadcast_sync
|
|
|
|
db = SessionLocal()
|
|
booked, at_table = [], []
|
|
try:
|
|
stored = store_online_orders(db, orders, booked, at_table)
|
|
except Exception as e:
|
|
db.rollback()
|
|
logger.error("Failed to process pulled orders: %s", e)
|
|
return
|
|
finally:
|
|
db.close()
|
|
|
|
bookings = {o["id"] for o in orders if o.get("order_type") in ("reservation", "preorder")} | set(at_table)
|
|
new_ids = [local_id for cloud_id, local_id in stored.items() if local_id > 0 and cloud_id not in bookings]
|
|
if booked:
|
|
broadcast_sync("reservation_requested", {"count": len(booked), "reservation_ids": booked})
|
|
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)},
|
|
)
|
|
# QR orders put on their table went to the kitchen: the customer's page says so (S.7)
|
|
for cloud_id in at_table:
|
|
await client.patch(
|
|
f"{settings.CLOUD_URL}/api/orders/{cloud_id}/status",
|
|
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
|
|
json={"status": "accepted"},
|
|
)
|
|
|
|
except Exception as e:
|
|
logger.warning("Order pull failed: %s", e)
|
|
|
|
|
|
def load_license_at_startup() -> None:
|
|
"""Decide from the stored license before anything else runs (main.py lifespan,
|
|
before the worker supervisor starts), so no module runs a moment longer than allowed."""
|
|
_load_persisted_state()
|
|
apply_license()
|
|
|
|
|
|
async def _sync_loop():
|
|
while True:
|
|
await _sync_once()
|
|
await asyncio.sleep(SYNC_INTERVAL_SECONDS)
|
|
|
|
|
|
async def _push_stats_snapshot():
|
|
"""Collect live operational stats and POST to cloud for the remote manager dashboard."""
|
|
if not settings.SITE_ID or not settings.CLOUD_URL:
|
|
return
|
|
|
|
site_numeric_id = license_state.get("site_numeric_id")
|
|
if not site_numeric_id:
|
|
return
|
|
|
|
try:
|
|
from database import SessionLocal
|
|
from models.order import Order, OrderItem
|
|
from models.business_day import BusinessDay
|
|
from models.shift import WaiterShift
|
|
from sqlalchemy import func
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
now = utcnow()
|
|
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
|
|
# Open tables = orders currently in status open or partially_paid
|
|
open_tables = db.query(Order).filter(
|
|
Order.status.in_(["open", "partially_paid"]),
|
|
Order.source == "pos",
|
|
).count()
|
|
|
|
# Today's completed POS orders (paid or closed today)
|
|
today_pos_orders = db.query(Order).filter(
|
|
Order.status.in_(["paid", "closed"]),
|
|
Order.source == "pos",
|
|
Order.closed_at >= today_start,
|
|
).all()
|
|
today_order_count = len(today_pos_orders)
|
|
|
|
# Today's revenue: sum of paid items on those orders
|
|
today_revenue = 0.0
|
|
for o in today_pos_orders:
|
|
for item in o.items:
|
|
if item.status in ("active", "paid"):
|
|
today_revenue += item.unit_price * item.quantity
|
|
|
|
# Online orders today
|
|
online_orders_today = db.query(Order).filter(
|
|
Order.source == "online",
|
|
Order.opened_at >= today_start,
|
|
).count()
|
|
|
|
online_orders_pending = db.query(Order).filter(
|
|
Order.source == "online",
|
|
Order.online_status == "pending_acceptance",
|
|
).count()
|
|
|
|
# Active business day
|
|
open_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
|
current_shift = None
|
|
if open_day:
|
|
active_shift = db.query(WaiterShift).filter(
|
|
WaiterShift.business_day_id == open_day.id,
|
|
WaiterShift.ended_at == None,
|
|
).first()
|
|
if active_shift:
|
|
current_shift = {
|
|
"waiter_id": active_shift.waiter_id,
|
|
"started_at": active_shift.started_at.isoformat(),
|
|
}
|
|
|
|
finally:
|
|
db.close()
|
|
|
|
snapshot = {
|
|
"open_tables": open_tables,
|
|
"today_revenue": round(today_revenue, 2),
|
|
"today_orders": today_order_count,
|
|
"online_orders_pending": online_orders_pending,
|
|
"online_orders_today": online_orders_today,
|
|
"current_shift": current_shift,
|
|
"as_of": now.isoformat(),
|
|
}
|
|
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
resp = await client.post(
|
|
f"{settings.CLOUD_URL}/api/remote/snapshot",
|
|
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
|
|
json={"site_id": site_numeric_id, "snapshot_json": json.dumps(snapshot)},
|
|
)
|
|
resp.raise_for_status()
|
|
logger.info("Stats snapshot pushed: %s", snapshot)
|
|
|
|
except Exception as e:
|
|
logger.warning("Stats snapshot push failed: %s", e)
|
|
|
|
|
|
# ── Module workers (APPS_PLATFORM D-19) ─────────────────────────────────────
|
|
# Started/stopped by core/modules/supervisor.py while their module is effective:
|
|
# connect_menu -> menu_push_worker (menu snapshot every 5 min)
|
|
# connect_orders -> order_pull_worker (pending online orders every CONNECT_SYNC_INTERVAL_SECONDS)
|
|
# connect_remote -> stats_push_worker (stats snapshot every 5 min)
|
|
# v1 ran all three in one _connect_loop. Each now waits for the first heartbeat to
|
|
# learn site_numeric_id, then does its first run at once.
|
|
PUSH_INTERVAL_SECONDS = 5 * 60
|
|
|
|
|
|
async def _wait_for_site_id(max_seconds: int = 30) -> None:
|
|
for _ in range(max_seconds):
|
|
if license_state.get("site_numeric_id"):
|
|
return
|
|
await asyncio.sleep(1)
|
|
|
|
|
|
# A change to what the customer apps sell (products, price rules, fees) pushes the menu soon,
|
|
# not at the next 5-minute tick (phase 3S): request_menu_push() from any thread wakes the
|
|
# worker; edits in a row within MENU_SETTLE_SECONDS become one push.
|
|
MENU_SETTLE_SECONDS = 5
|
|
MENU_PATHS = ("/api/products", "/api/pricing", "/api/connect/fees", "/api/data-transfer/import",
|
|
"/api/connect/qr", "/api/tables") # S.7: the tables' QR codes travel with the menu
|
|
_menu_wake: "asyncio.Event | None" = None
|
|
_menu_loop = None
|
|
|
|
|
|
def request_menu_push() -> None:
|
|
"""Ask the menu worker to push soon. Thread-safe; nothing happens while it isn't running."""
|
|
loop, wake = _menu_loop, _menu_wake
|
|
if loop is not None and wake is not None:
|
|
try:
|
|
loop.call_soon_threadsafe(wake.set)
|
|
except RuntimeError: # the loop has closed
|
|
pass
|
|
|
|
|
|
def menu_changed(method: str, path: str, status_code: int) -> bool:
|
|
"""Whether a finished request changed what the customer apps sell."""
|
|
return method not in ("GET", "HEAD", "OPTIONS") and status_code < 400 and path.startswith(MENU_PATHS)
|
|
|
|
|
|
async def menu_push_worker():
|
|
global _menu_wake, _menu_loop
|
|
_menu_loop, _menu_wake = asyncio.get_running_loop(), asyncio.Event()
|
|
await _wait_for_site_id()
|
|
while True:
|
|
_menu_wake.clear()
|
|
await _push_menu_snapshot()
|
|
try:
|
|
await asyncio.wait_for(_menu_wake.wait(), PUSH_INTERVAL_SECONDS)
|
|
await asyncio.sleep(MENU_SETTLE_SECONDS)
|
|
except asyncio.TimeoutError:
|
|
pass
|
|
|
|
|
|
async def stats_push_worker():
|
|
await _wait_for_site_id()
|
|
while True:
|
|
await _push_stats_snapshot()
|
|
await asyncio.sleep(PUSH_INTERVAL_SECONDS)
|
|
|
|
|
|
async def order_pull_worker():
|
|
await _wait_for_site_id()
|
|
while True:
|
|
await _pull_pending_orders()
|
|
await asyncio.sleep(ORDER_POLL_INTERVAL)
|
|
|
|
|
|
async def start_cloud_sync() -> asyncio.Task:
|
|
"""License heartbeat only (core). Connect pushes/pulls are module workers (see above)."""
|
|
return asyncio.create_task(_sync_loop())
|