feat(connect): the site side of online orders: fee line, customer's time, price check

Plan phase 3S, step S.5.
- Pull: an online order keeps the customer's time (orders.requested_for, None = as soon as
  possible) and delivery area; quick options are stored in the site's entry shape; items get
  their cost snapshot.
- The delivery fee is its own order line: a system product (products.system_key
  "delivery_fee", lifecycle "system", sold nowhere; services/system_products.py), created on
  first use in the venue's language with the VAT group most products use. Added printed and
  served, so kitchen tickets and the KDS never see it; paid at the counter with the items,
  counted in the shift, on the fiscal receipt with its VAT group. Never listed in the
  catalogue (products list, export, edit endpoints → 404) and never added by hand.
- Price check (services/online_check.py): each line priced as the snapshot prices it, at the
  order's time, and the fee through the same engine with the site's rules and the cloud's
  area id; differences kept on orders.online_price_diff and shown. The customer pays what
  the cloud charged.
- Counter: time chip (or as soon as possible), area, fee line, price warning; takeaway is
  its own kind (was shown as "at the venue") and finishes as "collected". KDS cards show the
  online reference and the time; kitchen tickets print the reference, the type and the time.
- Manager: Online ordering → "The fee on the receipt" (name, VAT group;
  PUT /api/connect/fees/fee-product, fees.vat_group_unknown); the online orders page shows
  the time, area and price warning.
- Migration 0019. Tests: tests/test_online_site_side.py (6), terminal unit test, e2e
  (terminal: fee, time, warning, paid in full; manager: fee line settings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 15:38:25 +02:00
co-authored by Claude Opus 5.5
parent 8ea44d71aa
commit 0ca700279a
38 changed files with 899 additions and 69 deletions
+58 -4
View File
@@ -351,10 +351,16 @@ 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."""
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)."""
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.user import User
from services import online_check, 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()
@@ -367,6 +373,9 @@ def store_online_orders(db, orders: list[dict]) -> dict:
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,
@@ -375,8 +384,7 @@ def store_online_orders(db, orders: list[dict]) -> dict:
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"))),
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"],
@@ -386,6 +394,9 @@ def store_online_orders(db, orders: list[dict]) -> dict:
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()
@@ -396,16 +407,59 @@ def store_online_orders(db, orders: list[dict]) -> dict:
added_by=opener_id,
quantity=item.get("quantity", 1),
unit_price=item.get("unit_price", 0.0),
selected_options=json.dumps(item.get("options", [])),
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,
))
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 _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:
+90
View File
@@ -0,0 +1,90 @@
"""The site checks the cloud's prices when it pulls an online order (plan phase 3S, step S.5).
The cloud prices online orders from the menu the site last pushed (S.2), so its prices may be
up to one push old (a change pushes about 5 s later; the 5-minute push is the fallback). The
customer was promised the cloud's prices and is charged them; this check only tells the venue
when the site's own engine says something else, so nobody is surprised at the counter.
diff(db, cloud_order, sales_point) -> None (all matched) | {
"lines": [{product_id, name, quantity, cloud, site, reason}], reason: price | not_sold | option
"fee": {cloud, site, reason} | None, reason: price | area | minimum
"cloud_total", "site_total"}
Each line is priced as the snapshot prices it (services/cloud_sync.menu_snapshot): the product
on its own at the order's sales point, plus its quick options, at the time the customer
ordered. The fee goes through the same engine (services/fees.py) with the site's rules, the
area the cloud matched (by id) and the order's time at the venue.
"""
from __future__ import annotations
from datetime import datetime
EPS = 0.005
def _when(cloud_order: dict):
from core.timeutil import utcnow
raw = cloud_order.get("created_at")
if isinstance(raw, str):
try:
when = datetime.fromisoformat(raw.replace("Z", "+00:00"))
if when.tzinfo is not None:
return when
except ValueError:
pass
return utcnow()
def diff(db, cloud_order: dict, sales_point: str) -> dict | None:
import json
from core import sales_points
from core.timeutil import to_venue
from models.product import Product
from routers.fees import fees_payload
from services import fees
from services.pos_cart import unit_prices
when = _when(cloud_order)
lines, site_subtotal = [], 0.0
items = json.loads(cloud_order.get("items_json") or "[]")
for item in items:
qty = item.get("quantity", 1) or 1
cloud = round(float(item.get("unit_price") or 0.0), 2)
entry = {"product_id": item.get("product_id"), "name": item.get("name"), "quantity": qty, "cloud": cloud}
product = db.get(Product, item.get("product_id")) if isinstance(item.get("product_id"), int) else None
if product is None or product.lifecycle_status != "active" or not sales_points.is_sold_at(product, sales_point):
lines.append({**entry, "site": None, "reason": "not_sold"})
site_subtotal += cloud * qty
continue
quick = {q.id: q for q in product.quick_options}
chosen = [o.get("id") if isinstance(o, dict) else o for o in item.get("options") or []]
if any(oid not in quick for oid in chosen):
lines.append({**entry, "site": None, "reason": "option"})
site_subtotal += cloud * qty
continue
site = round(unit_prices(db, [product], sales_point, now=when)[0] + sum(quick[o].price or 0.0 for o in chosen), 2)
site_subtotal += site * qty
if abs(site - cloud) > EPS:
lines.append({**entry, "site": site, "reason": "price"})
fee = None
cloud_fee = round(float(cloud_order.get("delivery_fee") or 0.0), 2)
if sales_point == sales_points.ONLINE_DELIVERY or cloud_fee:
data = fees_payload(db)
local = to_venue(when)
result = fees.compute(data["rules"], data["areas"], sales_point=sales_point,
subtotal=round(float(cloud_order.get("subtotal") or 0.0), 2),
items=sum(int(i.get("quantity", 1) or 1) for i in items),
area_id=cloud_order.get("delivery_area_id"), postcode=None,
weekday=local.weekday(), hhmm=local.strftime("%H:%M"))
if result["refused"]:
fee = {"cloud": cloud_fee, "site": None,
"reason": "area" if result["refused"] == "area_not_served" else "minimum"}
elif abs(result["fee"] - cloud_fee) > EPS:
fee = {"cloud": cloud_fee, "site": result["fee"], "reason": "price"}
if not lines and fee is None:
return None
site_fee = fee["site"] if fee and fee["site"] is not None else cloud_fee
return {"lines": lines, "fee": fee,
"cloud_total": round(float(cloud_order.get("total") or 0.0), 2),
"site_total": round(site_subtotal + site_fee, 2)}
+4 -4
View File
@@ -207,12 +207,12 @@ 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."""
def unit_prices(db, products, point: str, now=None) -> list[float]:
"""Each product's price for one unit without options at a sales point, right now (or at
`now`, UTC), 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()
now = now or utcnow()
active = build_active_price_group_ids(db, now)
out = []
for p in products:
+47 -5
View File
@@ -66,6 +66,34 @@ def _cap(text: str, caps: bool) -> str:
return text.upper() if caps else text
def _online_meta(order) -> list[tuple[str, str]]:
"""An online order's ticket lines (phase 3S, S.5): [(label, value)] - its reference and
type, and when the customer wants it (venue time; the date only when it isn't today)."""
if getattr(order, "source", None) != "online":
return []
from core.timeutil import to_venue, venue_now
kind = order.online_order_type or order.order_type
label = _tr("print.ticket.type." + kind) if kind in ("delivery", "takeaway", "dine_in", "preorder") else kind
out = [(_tr("print.ticket.online_label"), f"{order.online_order_ref or order.id} - {label}")]
if kind in ("delivery", "takeaway", "preorder"):
when = to_venue(order.requested_for) if order.requested_for else None
if when is None:
value = _tr("print.ticket.asap")
elif when.date() == venue_now().date():
value = when.strftime("%H:%M")
else:
value = when.strftime("%d/%m %H:%M")
out.append((_tr("print.ticket.for_label"), value))
return out
def _place(order, table_name: str) -> str:
"""What the compact header shows as the table: the online reference for online orders."""
if getattr(order, "source", None) == "online" and order.table is None:
return order.online_order_ref or str(order.id)
return table_name
def _gr(text: str) -> bytes:
"""Encode text to CP737 bytes. Replaces unknown chars instead of crashing."""
return text.encode('cp737', errors='replace')
@@ -641,9 +669,11 @@ def _print_kitchen_ticket_body(p: Network, order: Order, items: List[OrderItem],
if compact:
p._raw(b'\x1b\x61\x00')
_apply_font(p, sz_ord, b_ord)
header = _tr("print.ticket.compact_header", order=order.id, table=table_name, time=now_str, waiter=waiter_nick)
header = _tr("print.ticket.compact_header", order=order.id, table=_place(order, table_name), time=now_str, waiter=waiter_nick)
if customer_count:
header += _tr("print.ticket.compact_guests", count=customer_count)
for label, value in _online_meta(order)[1:]:
header += f" | {label} {value}"
_raw_text(p, (header.upper() if c_ord else header) + "\n")
_reset_font(p)
_divider(p, div, line_width)
@@ -655,7 +685,12 @@ def _print_kitchen_ticket_body(p: Network, order: Order, items: List[OrderItem],
_divider(p, div, line_width)
p._raw(b'\x1b\x61\x00')
_apply_font(p, sz_meta, b_meta)
_raw_text(p, _cap(_tr("print.ticket.table_label"), c_meta) + " " + _tr("print.ticket.table_value", table=table_name) + "\n")
online = _online_meta(order)
if online and order.table is None:
for label, value in online:
_raw_text(p, _cap(label, c_meta) + f" {value}\n")
else:
_raw_text(p, _cap(_tr("print.ticket.table_label"), c_meta) + " " + _tr("print.ticket.table_value", table=table_name) + "\n")
_raw_text(p, _cap(_tr("print.ticket.date_label"), c_meta) + f" {now_str}\n")
_raw_text(p, _cap(_tr("print.ticket.waiter_label"), c_meta) + f" {waiter_nick}\n")
if customer_count:
@@ -1445,7 +1480,7 @@ def _do_print_cancellation(order_id: int, item_ids: List[int], db: Session):
def _print_cancel_ticket(p: Network, order: Order, items: List[OrderItem], db: Session, line_width: int, div: str):
cfg = _load_print_settings(db)
table_name = order.table.label or str(order.table.number) if order.table else str(order.table_id)
table_name = _place(order, order.table.label or str(order.table.number) if order.table else str(order.table_id))
now_str = _greek_date(utcnow())
def _cancel_banner():
@@ -2076,9 +2111,11 @@ def print_service_items_sync(order: Order, service_entries: List[dict], db: Sess
if compact:
p._raw(b'\x1b\x61\x00')
_apply_font(p, sz_ord, b_ord)
header = _tr("print.ticket.compact_header", order=order.id, table=table_name, time=now_str, waiter=waiter_nick)
header = _tr("print.ticket.compact_header", order=order.id, table=_place(order, table_name), time=now_str, waiter=waiter_nick)
if customer_count:
header += _tr("print.ticket.compact_guests", count=customer_count)
for label, value in _online_meta(order)[1:]:
header += f" | {label} {value}"
_raw_text(p, (header.upper() if c_ord else header) + "\n")
_reset_font(p)
_divider(p, div, pr.line_width or LINE_WIDTH)
@@ -2087,7 +2124,12 @@ def print_service_items_sync(order: Order, service_entries: List[dict], db: Sess
_divider(p, div, pr.line_width or LINE_WIDTH)
p._raw(b'\x1b\x61\x00')
_apply_font(p, sz_meta, b_meta)
_raw_text(p, _cap(_tr("print.ticket.table_label"), c_meta) + " " + _tr("print.ticket.table_value", table=table_name) + "\n")
online = _online_meta(order)
if online and order.table is None:
for label, value in online:
_raw_text(p, _cap(label, c_meta) + f" {value}\n")
else:
_raw_text(p, _cap(_tr("print.ticket.table_label"), c_meta) + " " + _tr("print.ticket.table_value", table=table_name) + "\n")
_raw_text(p, _cap(_tr("print.ticket.date_label"), c_meta) + f" {now_str}\n")
_raw_text(p, _cap(_tr("print.ticket.waiter_label"), c_meta) + f" {waiter_nick}\n")
if customer_count:
+55
View File
@@ -0,0 +1,55 @@
"""Products the system adds to orders itself (plan phase 3S, step S.5).
An online delivery order's fee is an order line like any other, so everything that already
handles lines handles it: the counter's payment takes items + fee, the shift and the day
count it, the fiscal receipt prints it with its VAT group, a refund can give it back. Its
product is a *system product*:
- `lifecycle_status = "system"` and `sold_at = []`: never on a menu (the POS, the waiter app,
the cloud snapshot and the manager's product lists only show active products), and nobody
can add it by hand (POST /api/orders/{id}/items refuses it: not sold anywhere);
- `system_key` says what it is ("delivery_fee"); `OrderItem.system_key` exposes it so the
screens can show the line apart;
- its line is added already printed and served: the kitchen and the KDS never see it.
The product is created the first time it's needed, named in the venue's language, with the
VAT group most of the venue's products use (the manager can change both: Online ordering →
"On the receipt", PUT /api/connect/fees/fee-product).
"""
from __future__ import annotations
from collections import Counter
DELIVERY_FEE = "delivery_fee"
KEYS = (DELIVERY_FEE,)
def _usual_vat_group(db):
"""The VAT group most active products have (None when none has one)."""
from models.product import Product
groups = Counter(g for (g,) in db.query(Product.fiscal_vat_group_id)
.filter(Product.lifecycle_status == "active", Product.fiscal_vat_group_id.isnot(None)))
return groups.most_common(1)[0][0] if groups else None
def get(db, key: str, create: bool = True):
"""The system product for `key`, created on first use (flushed, not committed)."""
from core.i18n import t, venue_language
from models.product import Product
if key not in KEYS:
raise ValueError(f"unknown system product {key!r}")
product = db.query(Product).filter(Product.system_key == key).first()
if product is not None or not create:
return product
name = t(f"system_product.{key}", venue_language())
product = Product(name=name, fiscal_name=name, base_price=0.0, is_available=True, lifecycle_status="system",
system_key=key, sold_at="[]", digital_available=0, quick_add_enabled=False,
fiscal_vat_group_id=_usual_vat_group(db), cost_simple=0.0)
db.add(product)
db.flush()
return product
def out(product) -> dict:
return {"id": product.id, "key": product.system_key, "name": product.name,
"fiscal_name": product.fiscal_name, "vat_group_id": product.fiscal_vat_group_id}