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:
@@ -79,6 +79,7 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"fees.rule_not_found": (404, "Fee rule {rule_id} not found."),
|
||||
"fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."),
|
||||
"fees.order_invalid": (422, "The new order must list every rule once."),
|
||||
"fees.vat_group_unknown": (422, "VAT group {vat_group_id} isn't one of the fiscal machine's groups."),
|
||||
"refund.invalid": (422, "This refund doesn't add up ({reason})."),
|
||||
"refund.too_old": (409, "Only payments from today's business day can be refunded at the counter."),
|
||||
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
|
||||
|
||||
@@ -66,7 +66,16 @@
|
||||
"table_label": "Τραπεζι:",
|
||||
"table_value": "Τραπεζι {table}",
|
||||
"waiter_label": "Σερβιτορος:",
|
||||
"without": "ΧΩΡΙΣ:"
|
||||
"without": "ΧΩΡΙΣ:",
|
||||
"for_label": "Για:",
|
||||
"asap": "Το συντομοτερο",
|
||||
"online_label": "Online:",
|
||||
"type": {
|
||||
"delivery": "Διανομη",
|
||||
"takeaway": "Παραλαβη",
|
||||
"dine_in": "Τραπεζι",
|
||||
"preorder": "Προπαραγγελια"
|
||||
}
|
||||
}
|
||||
},
|
||||
"notification": {
|
||||
@@ -81,5 +90,8 @@
|
||||
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
|
||||
"failing": "Ένα δελτίο της παραγγελίας #{order_id} δεν έχει τυπωθεί ακόμα στον εκτυπωτή {printer} (αποτυχημένες προσπάθειες μέχρι τώρα: {attempts}· συνεχίζει να προσπαθεί). Ελέγξτε τον εκτυπωτή."
|
||||
}
|
||||
},
|
||||
"system_product": {
|
||||
"delivery_fee": "Μεταφορικά"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,16 @@
|
||||
"table_label": "Table:",
|
||||
"table_value": "Table {table}",
|
||||
"waiter_label": "Waiter:",
|
||||
"without": "NO:"
|
||||
"without": "NO:",
|
||||
"for_label": "For:",
|
||||
"asap": "As soon as possible",
|
||||
"online_label": "Online:",
|
||||
"type": {
|
||||
"delivery": "Delivery",
|
||||
"takeaway": "Takeaway",
|
||||
"dine_in": "Table",
|
||||
"preorder": "Pre-order"
|
||||
}
|
||||
}
|
||||
},
|
||||
"notification": {
|
||||
@@ -81,5 +90,8 @@
|
||||
"failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts).",
|
||||
"failing": "A ticket for order #{order_id} hasn't printed on {printer} yet (failed attempts so far: {attempts}; still retrying). Check the printer."
|
||||
}
|
||||
},
|
||||
"system_product": {
|
||||
"delivery_fee": "Delivery fee"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""system products (the delivery fee line); online orders keep their time, area and the site's price check (plan phase 3S, S.5)
|
||||
|
||||
Revision ID: 0019_online_order_site_side
|
||||
Revises: 0018_fee_rules
|
||||
Create Date: 2026-11-16 18:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.timeutil import UTCDateTime
|
||||
|
||||
|
||||
revision = '0019_online_order_site_side'
|
||||
down_revision = '0018_fee_rules'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('products', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('system_key', sa.String(), nullable=True))
|
||||
batch_op.create_index(batch_op.f('ix_products_system_key'), ['system_key'], unique=True)
|
||||
with op.batch_alter_table('orders', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('online_delivery_area', sa.String(), nullable=True))
|
||||
batch_op.add_column(sa.Column('online_price_diff', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('requested_for', UTCDateTime(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('orders', schema=None) as batch_op:
|
||||
batch_op.drop_column('requested_for')
|
||||
batch_op.drop_column('online_price_diff')
|
||||
batch_op.drop_column('online_delivery_area')
|
||||
with op.batch_alter_table('products', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_products_system_key'))
|
||||
batch_op.drop_column('system_key')
|
||||
@@ -34,6 +34,12 @@ class Order(Base):
|
||||
online_customer_address = Column(Text, nullable=True)
|
||||
online_customer_notes = Column(Text, nullable=True)
|
||||
online_order_type = Column(String, nullable=True) # "delivery" | "dine_in"
|
||||
online_delivery_area = Column(String, nullable=True) # the area's name (phase 3S, S.5)
|
||||
# the site's own price check when the order was pulled (S.5): NULL = the cloud's prices
|
||||
# match the site's; else JSON {lines: [...], fee: {...}|null} (services/online_check.py)
|
||||
online_price_diff = Column(Text, nullable=True)
|
||||
# when the customer wants it (S.5); NULL = as soon as possible
|
||||
requested_for = Column(UTCDateTime, nullable=True)
|
||||
# Phase 2F — customer CRM
|
||||
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True)
|
||||
|
||||
@@ -132,6 +138,11 @@ class OrderItem(Base):
|
||||
def unit_type(self) -> str:
|
||||
return self.product.unit_type if self.product and self.product.unit_type else "piece"
|
||||
|
||||
@property
|
||||
def system_key(self):
|
||||
"""A line the system added (the delivery fee, S.5): its product's system_key, else None."""
|
||||
return self.product.system_key if self.product is not None else None
|
||||
|
||||
|
||||
class PrintLog(Base):
|
||||
__tablename__ = "print_log"
|
||||
|
||||
@@ -40,8 +40,11 @@ class Product(Base):
|
||||
primary_category_id = Column(Integer, ForeignKey("categories.id"), nullable=True, index=True)
|
||||
base_price = Column(Float, nullable=False)
|
||||
is_available = Column(Boolean, default=True, nullable=False)
|
||||
# "active" | "archived" — archived products are kept for order history but hidden from active use
|
||||
# "active" | "archived" — archived products are kept for order history but hidden from active use;
|
||||
# "system" — a line the system adds itself (services/system_products.py), never on a menu
|
||||
lifecycle_status = Column(String, default="active", nullable=False)
|
||||
# system products only (phase 3S, S.5): what the line is, e.g. "delivery_fee"
|
||||
system_key = Column(String, nullable=True, unique=True, index=True)
|
||||
image_url = Column(String, nullable=True)
|
||||
sort_order = Column(Integer, default=0, nullable=False)
|
||||
|
||||
|
||||
@@ -16,6 +16,10 @@ is mirrored to the cloud in the background so the customer's tracking page follo
|
||||
never waits for the cloud (Rule 8). Paying an online order is the counter's ordinary payment
|
||||
(POST /api/pos/orders/{id}/pay): online orders belong to whoever holds connect_orders.manage
|
||||
(routers/orders.py _can_access_order).
|
||||
|
||||
Since phase 3S (S.5) an order carries the customer's time (`requested_for`, None = as soon as
|
||||
possible), its delivery area, the delivery fee as its own line (`system_key` "delivery_fee",
|
||||
paid with the items) and the site's price check (`price_diff`, services/online_check.py).
|
||||
"""
|
||||
import logging
|
||||
from typing import Literal, Optional
|
||||
@@ -129,7 +133,11 @@ def _board_out(order: Order) -> dict:
|
||||
"name": order.online_customer_name, "phone": order.online_customer_phone,
|
||||
"address": order.online_customer_address, "notes": order.online_customer_notes,
|
||||
},
|
||||
"requested_for": _iso(order.requested_for), # None = as soon as possible (S.5)
|
||||
"area": order.online_delivery_area,
|
||||
"price_diff": OrderOut._diff(order.online_price_diff),
|
||||
"items": [OrderItemOut.model_validate(i).model_dump(mode="json") for i in items],
|
||||
"fee": round(sum(_item_total(i) for i in items if i.system_key == "delivery_fee"), 2),
|
||||
"total": round(sum(_item_total(i) for i in items), 2),
|
||||
"unpaid": round(sum(_item_total(i) for i in items if i.status in UNPAID), 2),
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ def export_catalog(db: Session = Depends(get_db), user: User = Depends(require_m
|
||||
categories = db.query(Category).order_by(Category.sort_order).all()
|
||||
orphan_products = (
|
||||
db.query(Product)
|
||||
.filter(~Product.memberships.any(), Product.lifecycle_status != "archived")
|
||||
.filter(~Product.memberships.any(), Product.lifecycle_status != "archived", Product.system_key.is_(None))
|
||||
.order_by(Product.sort_order)
|
||||
.all()
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Delivery areas and fee rules (plan phase 3S, step S.3). Key: connect_orders.fees.
|
||||
|
||||
GET /api/connect/fees {areas, rules, ordering}
|
||||
GET /api/connect/fees {areas, rules, ordering, fee_product}
|
||||
PUT /api/connect/fees/fee-product the delivery fee line's name and VAT group (S.5)
|
||||
GET /api/connect/fees/ordering the online ordering settings PUT: save them
|
||||
POST /api/connect/fees/areas add an area PUT/DELETE /areas/{id}
|
||||
POST /api/connect/fees/rules add a rule PUT/DELETE /rules/{id}
|
||||
@@ -219,7 +220,53 @@ def _changed():
|
||||
|
||||
@router.get("")
|
||||
def list_fees(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
return {**fees_payload(db), "ordering": ordering_settings(db)}
|
||||
from services import system_products
|
||||
fee_product = system_products.get(db, system_products.DELIVERY_FEE)
|
||||
db.commit()
|
||||
return {**fees_payload(db), "ordering": ordering_settings(db),
|
||||
"fee_product": {**system_products.out(fee_product), "vat_groups": _vat_groups(db)}}
|
||||
|
||||
|
||||
def _vat_groups(db) -> list[dict]:
|
||||
"""The fiscal machine's VAT groups (setting fiscal.vat_groups): [{machine_id, friendly_name}]."""
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == "fiscal.vat_groups").first()
|
||||
try:
|
||||
groups = json.loads(row.value or "[]") if row else []
|
||||
except (TypeError, ValueError):
|
||||
return []
|
||||
return [{"machine_id": g.get("machine_id"), "friendly_name": g.get("friendly_name")}
|
||||
for g in groups if isinstance(g, dict) and isinstance(g.get("machine_id"), int)]
|
||||
|
||||
|
||||
class FeeProductBody(BaseModel):
|
||||
"""How the delivery fee line is called (on screens and the receipt) and its VAT group."""
|
||||
name: str = Field(min_length=1, max_length=40)
|
||||
vat_group_id: Optional[int] = Field(default=None, ge=1, le=99)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _strip(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("empty")
|
||||
return v
|
||||
|
||||
|
||||
@router.put("/fee-product")
|
||||
def put_fee_product(body: FeeProductBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""The delivery fee's system product (services/system_products.py). Lines already on orders
|
||||
keep the name they were added with; the VAT group counts from the next receipt."""
|
||||
from services import system_products
|
||||
if body.vat_group_id is not None:
|
||||
groups = [g["machine_id"] for g in _vat_groups(db)]
|
||||
if groups and body.vat_group_id not in groups:
|
||||
raise XeniaError("fees.vat_group_unknown", vat_group_id=body.vat_group_id)
|
||||
product = system_products.get(db, system_products.DELIVERY_FEE)
|
||||
product.name = product.fiscal_name = body.name
|
||||
product.fiscal_vat_group_id = body.vat_group_id
|
||||
db.commit()
|
||||
return system_products.out(product)
|
||||
|
||||
|
||||
@router.get("/ordering")
|
||||
|
||||
@@ -261,6 +261,9 @@ def _build_order_payload(order: Order, tables_map: dict, db: Session) -> dict:
|
||||
"opened_at": opened_at_out,
|
||||
"closed_at": _fmt_ts(order.closed_at) if order.closed_at else None,
|
||||
"notes": order.notes,
|
||||
# online orders (phase 3S, S.5): their reference and the customer's time (None = asap)
|
||||
"online_ref": order.online_order_ref if order.source == "online" else None,
|
||||
"requested_for": _fmt_ts(order.requested_for),
|
||||
"waiters": waiter_names,
|
||||
"items": items_out,
|
||||
}
|
||||
|
||||
@@ -382,6 +382,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"paid_in_shift_id": i.paid_in_shift_id,
|
||||
"price_adjustment": getattr(i, 'price_adjustment', 0.0) or 0.0,
|
||||
"unit_type": i.unit_type,
|
||||
"system_key": i.system_key, # the delivery fee line (phase 3S, S.5)
|
||||
}
|
||||
|
||||
def fmt_log(l):
|
||||
@@ -430,6 +431,9 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"kds_status": order.kds_status,
|
||||
"kds_status_changed_at": _iso(order.kds_status_changed_at),
|
||||
"customer_count": order.customer_count,
|
||||
# online orders (phase 3S, S.5): the customer's time (None = asap) and area
|
||||
"requested_for": _iso(order.requested_for),
|
||||
"online_delivery_area": order.online_delivery_area,
|
||||
"items": [fmt_item(i) for i in order.items],
|
||||
"waiters": [{"waiter_id": w.waiter_id} for w in order.waiters],
|
||||
"audit_logs": [fmt_log(l) for l in order.audit_logs],
|
||||
|
||||
@@ -271,7 +271,8 @@ def list_products(all: bool = False, category_id: int | None = None, sold_at: st
|
||||
`sold_at` (comma-separated): only products sold at one of those sales points (phase 3S; the
|
||||
waiter app asks for in_store,in_store_takeaway)."""
|
||||
from sqlalchemy.orm import selectinload
|
||||
q = db.query(Product).options(selectinload(Product.memberships), selectinload(Product.prep_zones))
|
||||
q = (db.query(Product).filter(Product.system_key.is_(None)) # system products: never listed (S.5)
|
||||
.options(selectinload(Product.memberships), selectinload(Product.prep_zones)))
|
||||
has_dashboard = holds(user, "core.dashboard.access")
|
||||
if not all or not has_dashboard:
|
||||
# Waiters only see active, available products
|
||||
@@ -395,7 +396,8 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
|
||||
|
||||
@router.put("/{product_id}", response_model=ProductOut)
|
||||
def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
product = db.query(Product).filter(Product.id == product_id).first()
|
||||
# system products (the delivery fee line, S.5) are not part of the catalogue
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
scalar_fields = body.model_dump(
|
||||
@@ -442,7 +444,8 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
|
||||
|
||||
@router.post("/{product_id}/image", response_model=ProductOut)
|
||||
async def upload_product_image(product_id: int, file: UploadFile = File(...), db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
product = db.query(Product).filter(Product.id == product_id).first()
|
||||
# system products (the delivery fee line, S.5) are not part of the catalogue
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
|
||||
@@ -480,7 +483,8 @@ def list_modifier_groups(product_id: int, db: Session = Depends(get_db), user: U
|
||||
|
||||
@router.post("/{product_id}/modifier-groups", response_model=ModifierGroupOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_modifier_group(product_id: int, body: ModifierGroupCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
product = db.query(Product).filter(Product.id == product_id).first()
|
||||
# system products (the delivery fee line, S.5) are not part of the catalogue
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
g = ProductModifierGroup(product_id=product_id, modifier_type=body.modifier_type, name=body.name, sort_order=body.sort_order)
|
||||
@@ -520,7 +524,8 @@ def delete_modifier_group(product_id: int, group_id: int, db: Session = Depends(
|
||||
|
||||
@router.delete("/{product_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_product(product_id: int, hard: bool = False, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
product = db.query(Product).filter(Product.id == product_id).first()
|
||||
# system products (the delivery fee line, S.5) are not part of the catalogue
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
if hard:
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from pydantic import BaseModel
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel, field_validator
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from schemas.base import UTCDatetime
|
||||
@@ -64,6 +66,7 @@ class OrderItemOut(BaseModel):
|
||||
course_id: Optional[int] = None
|
||||
deal_id: Optional[int] = None
|
||||
linked_item_id: Optional[int] = None
|
||||
system_key: Optional[str] = None # a line the system added: "delivery_fee" (phase 3S, S.5)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -162,6 +165,9 @@ class OrderOut(BaseModel):
|
||||
online_customer_address: Optional[str] = None
|
||||
online_customer_notes: Optional[str] = None
|
||||
online_order_type: Optional[str] = None
|
||||
online_delivery_area: Optional[str] = None
|
||||
online_price_diff: Optional[dict] = None # the site's price check (S.5); None = matched
|
||||
requested_for: Optional[UTCDatetime] = None # None = as soon as possible
|
||||
order_type: str = "here"
|
||||
customer_count: Optional[int] = None
|
||||
items: List[OrderItemOut] = []
|
||||
@@ -170,3 +176,14 @@ class OrderOut(BaseModel):
|
||||
print_jobs: List[PrintJobOut] = []
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@field_validator("online_price_diff", mode="before")
|
||||
@classmethod
|
||||
def _diff(cls, value):
|
||||
if value is None or isinstance(value, dict):
|
||||
return value
|
||||
try:
|
||||
data = json.loads(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)}
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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}
|
||||
@@ -0,0 +1,170 @@
|
||||
"""The site side of online orders (plan phase 3S, step S.5): a pulled order keeps the customer's
|
||||
time and area, its delivery fee becomes a line of its own (a system product: paid with the
|
||||
items, counted in the shift, on the fiscal receipt, never in the kitchen), and the site checks
|
||||
the cloud's prices with its own engine (a difference is kept and shown, the customer pays what
|
||||
they were charged)."""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
|
||||
from tests.test_pos import drawer_printer, menu, till # noqa: F401 (fixtures)
|
||||
from tests.test_pos_online import board, cloud, counter, kds_ids # noqa: F401 (fixtures)
|
||||
|
||||
|
||||
def pull(db, menu, cloud_id=601, *, burger_price=10.0, fee=2.5, area_id=None, area="Centre", **extra):
|
||||
"""An online delivery order as the cloud hands it over (S.4 shape)."""
|
||||
from services.cloud_sync import store_online_orders
|
||||
order = {
|
||||
"id": cloud_id, "public_ref": f"ORD-{cloud_id:04d}", "order_type": "delivery", "sales_point": "online_delivery",
|
||||
"customer_name": "Maria", "customer_phone": "6911111111", "customer_address": "Harbour 7",
|
||||
"status": "pending_acceptance", "delivery_area": area, "delivery_area_id": area_id,
|
||||
"requested_for": "2026-11-16T19:30:00+00:00", "created_at": "2026-11-16T17:00:00+00:00",
|
||||
"items_json": json.dumps([
|
||||
{"product_id": menu["burger"].id, "name": "Burger", "quantity": 2, "unit_price": burger_price + 1.0,
|
||||
"options": [{"id": menu["burger"].quick_options[0].id, "name": "Extra cheese", "price": 1.0}]},
|
||||
{"product_id": menu["coffee"].id, "name": "Freddo", "quantity": 1, "unit_price": 3.0, "options": []},
|
||||
]),
|
||||
"subtotal": round(2 * (burger_price + 1.0) + 3.0, 2), "delivery_fee": fee,
|
||||
"total": round(2 * (burger_price + 1.0) + 3.0 + fee, 2), **extra,
|
||||
}
|
||||
return store_online_orders(db, [order])[cloud_id]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fees_set(db):
|
||||
"""The venue's own fee rules: €2.50 to the Centre (a fixed fee)."""
|
||||
from models.fees import DeliveryArea, FeeRule
|
||||
centre = DeliveryArea(name="Centre", postcodes=json.dumps(["85100"]), is_active=1, sort_order=0)
|
||||
db.add(centre)
|
||||
db.flush()
|
||||
db.add(FeeRule(name="Centre", is_active=1, sort_order=0, sales_points=json.dumps(["online_delivery"]),
|
||||
area_ids=json.dumps([centre.id]), action="set", value=2.5, stop=1))
|
||||
db.commit()
|
||||
return centre
|
||||
|
||||
|
||||
def test_the_fee_is_its_own_line_and_never_reaches_the_kitchen(client, db, counter, menu, owner_h, cloud, fees_set):
|
||||
from models.order import Order
|
||||
from models.product import Product
|
||||
oid = pull(db, menu, area_id=fees_set.id)
|
||||
order = db.get(Order, oid)
|
||||
assert order.requested_for.isoformat() == "2026-11-16T19:30:00+00:00"
|
||||
assert order.online_delivery_area == "Centre"
|
||||
assert order.online_price_diff is None # the cloud's prices are the venue's
|
||||
fee = [i for i in order.items if i.system_key == "delivery_fee"]
|
||||
assert [(i.product_name, i.quantity, i.unit_price, i.printed, i.kds_status) for i in fee] == [("Delivery fee", 1, 2.5, True, "served")]
|
||||
burger = next(i for i in order.items if i.product_id == menu["burger"].id)
|
||||
assert json.loads(burger.selected_options) == [{"id": menu["burger"].quick_options[0].id, "name": "Extra cheese",
|
||||
"price_delta": 1.0, "type": "quick"}]
|
||||
assert burger.unit_cost == 3.5 # the cost snapshot, as for any order
|
||||
# the system product: never on a menu or in the catalogue, never added by hand
|
||||
product = db.query(Product).filter(Product.system_key == "delivery_fee").one()
|
||||
assert product.lifecycle_status == "system"
|
||||
assert product.id not in [p["id"] for p in client.get("/api/products/?all=true", headers=owner_h).json()]
|
||||
assert product.id not in [p["id"] for p in client.get("/api/pos/menu", headers=counter["h"]).json()["products"]]
|
||||
assert client.put(f"/api/products/{product.id}", headers=owner_h, json={"name": "x"}).status_code == 404
|
||||
assert err(client.post(f"/api/orders/{oid}/items", headers=owner_h,
|
||||
json={"items": [{"product_id": product.id, "quantity": 1}]})) == "order.not_sold_here"
|
||||
# the board: the time, the area, the fee
|
||||
o = board(client, counter)["incoming"][0]
|
||||
assert (o["requested_for"], o["area"], o["fee"], o["total"], o["price_diff"]) == ("2026-11-16T19:30:00+00:00", "Centre", 2.5, 27.5, None)
|
||||
assert [i["system_key"] for i in o["items"]] == [None, None, "delivery_fee"]
|
||||
# accepted: the kitchen gets the food, not the fee
|
||||
client.post(f"/api/connect/orders/{oid}/accept", headers=counter["h"])
|
||||
assert cloud["printed"] == [(oid, sorted(i.id for i in order.items if i.system_key is None))]
|
||||
kds = next(x for x in client.get("/api/kds/orders", headers=owner_h).json()["orders"] if x["id"] == oid)
|
||||
assert [i["product_name"] for i in kds["items"]] == ["Burger", "Freddo"]
|
||||
assert kds["online_ref"] == "ORD-0601" and kds["requested_for"] == "2026-11-16T19:30:00+00:00"
|
||||
assert kds["kds_status"] == "pending" # the served fee line doesn't count
|
||||
|
||||
|
||||
def test_paid_at_the_counter_in_full_with_the_shift_and_the_fiscal_receipt(client, db, counter, menu, cloud, fees_set,
|
||||
monkeypatch, owner_h):
|
||||
from models.settings import PosSettings
|
||||
from services import fiscal
|
||||
issued = []
|
||||
monkeypatch.setattr(fiscal, "send_fiscal_receipt_background",
|
||||
lambda items, method, total, db, order_id, db_factory, **kw: issued.append((items, method, total)))
|
||||
for key, value in (("fiscal.enabled", "true"), ("fiscal.vat_groups", json.dumps([{"machine_id": 2, "friendly_name": "13%"}]))):
|
||||
row = db.get(PosSettings, key)
|
||||
if row is None:
|
||||
db.add(PosSettings(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
menu["burger"].fiscal_vat_group_id = menu["coffee"].fiscal_vat_group_id = 2
|
||||
db.commit()
|
||||
oid = pull(db, menu, area_id=fees_set.id)
|
||||
h = counter["h"]
|
||||
client.post(f"/api/connect/orders/{oid}/accept", headers=h)
|
||||
for s in ("preparing", "out_for_delivery"):
|
||||
client.post(f"/api/connect/orders/{oid}/status", headers=h, json={"status": s})
|
||||
o = board(client, counter)["in_progress"][0]
|
||||
assert o["unpaid"] == 27.5
|
||||
paid = client.post(f"/api/pos/orders/{oid}/pay", headers=h,
|
||||
json={"payments": [{"method": "cash", "item_ids": [i["id"] for i in o["items"]]}], "cash_given": 30})
|
||||
assert paid.status_code == 200, paid.text
|
||||
assert paid.json()["total"] == 27.5 and paid.json()["change"] == 2.5
|
||||
# the fee is on the receipt, with the VAT group most of the venue's products use
|
||||
(items, method, total), = issued
|
||||
assert method == "cash" and total == 27.5
|
||||
assert {"name": "Delivery fee", "qty": 1, "unit_price": 2.5, "vat_group_id": 2} in items
|
||||
# and in the shift
|
||||
from routers.shifts import compute_shift_total
|
||||
assert compute_shift_total(counter["shift"].id, db) == 27.5
|
||||
|
||||
|
||||
def test_the_site_flags_prices_that_differ(client, db, counter, menu, fees_set):
|
||||
from models.order import Order
|
||||
# the cloud charged an old burger price and a fee the venue no longer has for that area
|
||||
oid = pull(db, menu, cloud_id=602, burger_price=9.0, fee=4.0, area_id=fees_set.id)
|
||||
diff = json.loads(db.get(Order, oid).online_price_diff)
|
||||
assert diff["lines"] == [{"product_id": menu["burger"].id, "name": "Burger", "quantity": 2, "cloud": 10.0, "site": 11.0, "reason": "price"}]
|
||||
assert diff["fee"] == {"cloud": 4.0, "site": 2.5, "reason": "price"}
|
||||
assert (diff["cloud_total"], diff["site_total"]) == (27.0, 27.5)
|
||||
# the customer pays what they were charged: the order keeps the cloud's prices
|
||||
o = next(x for x in board(client, counter)["incoming"] if x["id"] == oid)
|
||||
assert o["total"] == 27.0 and o["fee"] == 4.0 and o["price_diff"]["fee"]["site"] == 2.5
|
||||
# an area the venue doesn't serve (any more), a product no longer sold online
|
||||
menu["coffee"].sold_at = json.dumps(["in_store"])
|
||||
db.commit()
|
||||
oid = pull(db, menu, cloud_id=603, area_id=999)
|
||||
diff = json.loads(db.get(Order, oid).online_price_diff)
|
||||
assert [(x["name"], x["reason"]) for x in diff["lines"]] == [("Freddo", "not_sold")]
|
||||
assert diff["fee"] == {"cloud": 2.5, "site": None, "reason": "area"}
|
||||
|
||||
|
||||
def test_no_fee_no_line_and_asap(db, menu, counter):
|
||||
from models.order import Order
|
||||
oid = pull(db, menu, cloud_id=604, fee=0.0, requested_for=None, sales_point="online_takeaway", order_type="takeaway",
|
||||
delivery_area=None)
|
||||
order = db.get(Order, oid)
|
||||
assert order.requested_for is None and order.online_delivery_area is None
|
||||
assert all(i.system_key is None for i in order.items) and len(order.items) == 2
|
||||
|
||||
|
||||
def test_the_fee_line_name_and_vat_group(client, db, owner_h):
|
||||
from models.settings import PosSettings
|
||||
r = client.get("/api/connect/fees", headers=owner_h)
|
||||
assert r.status_code == 200, r.text
|
||||
fp = r.json()["fee_product"]
|
||||
assert fp["key"] == "delivery_fee" and fp["name"] == "Delivery fee" and fp["vat_groups"] == []
|
||||
r = client.put("/api/connect/fees/fee-product", headers=owner_h, json={"name": "Μεταφορικά", "vat_group_id": 3})
|
||||
assert r.status_code == 200 and r.json()["name"] == "Μεταφορικά" and r.json()["vat_group_id"] == 3
|
||||
db.add(PosSettings(key="fiscal.vat_groups", value=json.dumps([{"machine_id": 1, "friendly_name": "24%"}])))
|
||||
db.commit()
|
||||
assert err(client.put("/api/connect/fees/fee-product", headers=owner_h, json={"name": "Fee", "vat_group_id": 3})) == "fees.vat_group_unknown"
|
||||
assert client.put("/api/connect/fees/fee-product", headers=owner_h, json={"name": " ", "vat_group_id": 1}).status_code == 422
|
||||
assert client.get("/api/connect/fees", headers=owner_h).json()["fee_product"]["vat_groups"] == [{"machine_id": 1, "friendly_name": "24%"}]
|
||||
|
||||
|
||||
def test_kitchen_ticket_shows_the_reference_and_the_time(db, menu):
|
||||
from models.order import Order
|
||||
from services.printer_service import _online_meta, _place
|
||||
order = db.get(Order, pull(db, menu, cloud_id=605))
|
||||
meta = _online_meta(order)
|
||||
assert meta[0] == ("Online:", "ORD-0605 - Delivery")
|
||||
assert meta[1][0] == "For:" and meta[1][1].endswith("21:30") # 19:30 UTC at the venue (Athens, winter)
|
||||
assert _place(order, "None") == "ORD-0605"
|
||||
order.requested_for = None
|
||||
assert _online_meta(order)[1] == ("For:", "As soon as possible")
|
||||
Reference in New Issue
Block a user