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: