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:
@@ -42,6 +42,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
|
||||
| `local_backend/services/fiscal/` | Fiscal devices behind one driver interface (D-27, step 3.3e): `base.py` (`prepare_receipt` / `prepare_credit_note` → send, `credit_notes` flag, `status`), `txt_file.py` (the dTEC100extra folder bridge, the only driver today; no credit notes yet), `__init__.py` (the venue's driver from `fiscal.type`, item building, background issue). **A new machine = a new driver module listed in `DRIVERS`**; never write to a device from a router |
|
||||
| `local_backend/services/fees.py` | Delivery fee engine (phase 3S). **Byte-identical copy in `cloud-service/cloud_backend/services/fees.py`**: change both, and `tests/fixtures/fee_cases.json` in both; `tests/test_fees.py` fails if they differ |
|
||||
| `local_backend/services/refunds.py` | Refunds: their own records (`models/refund.py`), never edits of the paid items; shift / day totals subtract them |
|
||||
| `local_backend/services/system_products.py`, `services/online_check.py` | Lines the system adds itself (phase 3S): the delivery fee is an order line whose product has `system_key` and `lifecycle_status = "system"` (never on a menu or in the catalogue, never added by hand, added printed + served so the kitchen never sees it; paid, counted, receipted and refunded like any line). The site's own price check of a pulled online order (`orders.online_price_diff`): shown, never applied — the customer pays the cloud's prices |
|
||||
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
|
||||
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
||||
| `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below |
|
||||
|
||||
@@ -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")
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { useLiveEvent } from '../live/useLiveEvent'
|
||||
import {
|
||||
getIncomingOrders,
|
||||
@@ -55,9 +56,17 @@ function OrderCard({ order, onAction }) {
|
||||
return () => clearInterval(id)
|
||||
}, [])
|
||||
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatDate, formatDateTime, formatMoney, formatTime } = useFormat()
|
||||
const subtotal = calcTotals(order.items)
|
||||
const isDelivery = order.online_order_type === 'delivery'
|
||||
const isTakeaway = order.online_order_type === 'takeaway'
|
||||
const st = order.online_status
|
||||
// phase 3S (S.5): when the customer wants it, and the venue's own price check
|
||||
const when = order.requested_for
|
||||
? t('onlineOrders.for', { when: formatDate(order.requested_for) === formatDate(new Date()) ? formatTime(order.requested_for) : formatDateTime(order.requested_for, 'datetimeShort') })
|
||||
: t('onlineOrders.asap')
|
||||
const diff = order.online_price_diff
|
||||
|
||||
async function act(fn) {
|
||||
setBusy(true)
|
||||
@@ -75,7 +84,7 @@ function OrderCard({ order, onAction }) {
|
||||
<span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${
|
||||
isDelivery ? 'bg-orange-100 text-orange-700' : 'bg-teal-100 text-teal-700'
|
||||
}`}>
|
||||
{isDelivery ? 'Delivery' : 'Dine-in'}
|
||||
{isDelivery ? 'Delivery' : isTakeaway ? 'Takeaway' : 'Dine-in'}
|
||||
</span>
|
||||
<OnlineStatusBadge status={st} />
|
||||
</div>
|
||||
@@ -91,7 +100,15 @@ function OrderCard({ order, onAction }) {
|
||||
<p className="text-gray-500">{order.online_customer_phone}</p>
|
||||
)}
|
||||
{isDelivery && order.online_customer_address && (
|
||||
<p className="text-gray-500">{order.online_customer_address}</p>
|
||||
<p className="text-gray-500">{order.online_customer_address}{order.online_delivery_area ? ` · ${order.online_delivery_area}` : ''}</p>
|
||||
)}
|
||||
{(isDelivery || isTakeaway) && (
|
||||
<p className={`font-semibold ${order.requested_for ? 'text-info-ink' : 'text-ink-2'}`} data-testid="online-when">{when}</p>
|
||||
)}
|
||||
{diff && (
|
||||
<p className="text-warning-ink bg-warning-soft rounded px-2 py-1 text-xs mt-1" data-testid="online-price-diff">
|
||||
{t('onlineOrders.priceDiff', { charged: formatMoney(diff.cloud_total), here: formatMoney(diff.site_total) })}
|
||||
</p>
|
||||
)}
|
||||
{order.online_customer_notes && (
|
||||
<p className="text-amber-700 bg-amber-50 rounded px-2 py-1 text-xs mt-1">
|
||||
@@ -105,7 +122,9 @@ function OrderCard({ order, onAction }) {
|
||||
<div className="space-y-1 text-sm text-gray-700">
|
||||
{order.items.map((it, i) => (
|
||||
<div key={i} className="flex justify-between">
|
||||
<span>{it.quantity} × {it.product?.name ?? `#${it.product_id}`}</span>
|
||||
<span className={it.system_key ? 'text-ink-2' : undefined}>
|
||||
{it.system_key ? (it.product_name ?? it.product?.name) : `${it.quantity} × ${it.product_name ?? it.product?.name ?? `#${it.product_id}`}`}
|
||||
</span>
|
||||
<span className="text-gray-500">€{(((it.unit_price ?? 0) + (it.price_adjustment ?? 0)) * it.quantity).toFixed(2)}</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// The delivery fee on the bill and the fiscal receipt (plan phase 3S, step S.5). An online
|
||||
// delivery order's fee arrives as its own line (a system product the venue never sells by
|
||||
// hand), so the counter takes items + fee and the receipt prints it. Here the venue names
|
||||
// that line and picks its VAT group. PUT /api/connect/fees/fee-product.
|
||||
import { useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Field, Input, Select } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
|
||||
export default function FeeProductCard({ product, onSaved }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [name, setName] = useState(product.name ?? '')
|
||||
const [vat, setVat] = useState(product.vat_group_id == null ? '' : String(product.vat_group_id))
|
||||
const [busy, setBusy] = useState(false)
|
||||
const groups = product.vat_groups ?? []
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await client.put('/api/connect/fees/fee-product', { name: name.trim(), vat_group_id: vat === '' ? null : Number(vat) })
|
||||
toast.success(t('fees.saved'))
|
||||
onSaved?.()
|
||||
} catch (err) { toast.error(errorMessage(err, t)) }
|
||||
setBusy(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="p-4 rounded-card border border-line bg-surface grid gap-3" aria-labelledby="fee-product-h" data-testid="fee-product">
|
||||
<div className="grid gap-1">
|
||||
<h2 id="fee-product-h" className="text-title font-semibold text-ink">{t('feeProduct.title')}</h2>
|
||||
<p className="text-label text-ink-2">{t('feeProduct.intro')}</p>
|
||||
</div>
|
||||
<Field label={t('feeProduct.name')}>
|
||||
<Input value={name} maxLength={40} onChange={e => setName(e.target.value)} data-testid="fee-product-name" />
|
||||
</Field>
|
||||
<Field label={t('feeProduct.vat')} hint={groups.length ? undefined : t('feeProduct.noGroups')}>
|
||||
{groups.length ? (
|
||||
<Select value={vat} onChange={e => setVat(e.target.value)} data-testid="fee-product-vat">
|
||||
<option value="">{t('feeProduct.vatNone')}</option>
|
||||
{groups.map(g => <option key={g.machine_id} value={String(g.machine_id)}>{g.friendly_name || g.machine_id}</option>)}
|
||||
</Select>
|
||||
) : (
|
||||
<Input inputMode="numeric" value={vat} onChange={e => setVat(e.target.value.replace(/\D/g, ''))} data-testid="fee-product-vat" />
|
||||
)}
|
||||
</Field>
|
||||
<div><Button onClick={save} loading={busy} disabled={!name.trim()} data-testid="fee-product-save">{t('fees.save')}</Button></div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Online ordering (plan phase 3S, steps S.3–S.4): the ordering settings (OrderingSettings),
|
||||
// delivery areas and fees. Backend: /api/connect/fees
|
||||
// Online ordering (plan phase 3S, steps S.3–S.5): the ordering settings (OrderingSettings),
|
||||
// delivery areas and fees, and the fee's line on the receipt (FeeProductCard). Backend: /api/connect/fees
|
||||
// (connect_orders.fees). The venue lists the areas it delivers to and the fee rules, looked
|
||||
// at from the top: a rule whose conditions hold changes the fee (set, add, % of the
|
||||
// products, free) or refuses the order below a minimum; "stop here" makes the first match
|
||||
@@ -13,6 +13,7 @@ import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { SALES_POINTS } from '@xenia/access'
|
||||
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import FeeProductCard from './FeeProductCard'
|
||||
import OrderingSettings from './OrderingSettings'
|
||||
import { ACTIONS, DAYS, describeRule, emptyRule, moveRule, parsePostcodes, previewBody, ruleBody, ruleProblems, ruleToForm } from './feesLogic'
|
||||
|
||||
@@ -109,6 +110,7 @@ export default function FeesPage() {
|
||||
)}
|
||||
</section>
|
||||
<TestOrder areas={data.areas} />
|
||||
{data.fee_product && <FeeProductCard key={JSON.stringify(data.fee_product)} product={data.fee_product} onSaved={load} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -102,6 +102,7 @@
|
||||
"area_not_found": "Η περιοχή διανομής {{area_id}} δεν βρέθηκε.",
|
||||
"rule_not_found": "Ο κανόνας χρέωσης {{rule_id}} δεν βρέθηκε.",
|
||||
"area_in_use": "Αυτή η περιοχή χρησιμοποιείται από κανόνες χρέωσης: {{rules}}. Αλλάξτε πρώτα αυτούς τους κανόνες.",
|
||||
"order_invalid": "Η νέα σειρά πρέπει να περιέχει κάθε κανόνα μία φορά."
|
||||
"order_invalid": "Η νέα σειρά πρέπει να περιέχει κάθε κανόνα μία φορά.",
|
||||
"vat_group_unknown": "Η ομάδα ΦΠΑ {{vat_group_id}} δεν είναι μία από τις ομάδες της φορολογικής μηχανής."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -541,5 +541,18 @@
|
||||
},
|
||||
"asap": "«Το συντομότερο»",
|
||||
"asapHint": "Όσο είναι ανοιχτά, οι πελάτες μπορούν να παραγγείλουν και για το συντομότερο."
|
||||
},
|
||||
"onlineOrders": {
|
||||
"for": "Για {{when}}",
|
||||
"asap": "Το συντομότερο",
|
||||
"priceDiff": "Χρεώθηκε {{charged}} online· με τις τωρινές τιμές του καταστήματος θα ήταν {{here}}. Ο πελάτης πληρώνει όσο χρεώθηκε."
|
||||
},
|
||||
"feeProduct": {
|
||||
"title": "Τα μεταφορικά στην απόδειξη",
|
||||
"intro": "Τα μεταφορικά μιας παραγγελίας διανομής είναι ξεχωριστή γραμμή στον λογαριασμό και στη φορολογική απόδειξη. Δώστε της όνομα και ομάδα ΦΠΑ.",
|
||||
"name": "Όνομα στον λογαριασμό και την απόδειξη",
|
||||
"vat": "Ομάδα ΦΠΑ",
|
||||
"vatNone": "Χωρίς ομάδα ΦΠΑ",
|
||||
"noGroups": "Ορίστε τις ομάδες ΦΠΑ της φορολογικής μηχανής στις Ρυθμίσεις → Φορολογικά για να διαλέξετε εδώ."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,8 @@
|
||||
"done": "✓ Έτοιμη"
|
||||
},
|
||||
"batch": "Παρτίδα {{n}}",
|
||||
"noCourse": "Χωρίς πιάτο"
|
||||
"noCourse": "Χωρίς πιάτο",
|
||||
"for": "για {{time}}"
|
||||
},
|
||||
"channel": {
|
||||
"here": "Εδώ",
|
||||
@@ -310,7 +311,8 @@
|
||||
"pick": "Επιλέξτε μια παραγγελία για να τη δείτε",
|
||||
"type": {
|
||||
"delivery": "Διανομή",
|
||||
"dine_in": "Στο κατάστημα"
|
||||
"dine_in": "Στο κατάστημα",
|
||||
"takeaway": "Παραλαβή"
|
||||
},
|
||||
"status": {
|
||||
"pending_acceptance": "Περιμένει απάντηση",
|
||||
@@ -332,11 +334,13 @@
|
||||
},
|
||||
"payAnd": {
|
||||
"delivered": "Είσπραξη {{amount}} · παραδόθηκε",
|
||||
"served": "Είσπραξη {{amount}} · σερβιρίστηκε"
|
||||
"served": "Είσπραξη {{amount}} · σερβιρίστηκε",
|
||||
"collected": "Είσπραξη {{amount}} · παραλήφθηκε"
|
||||
},
|
||||
"mark": {
|
||||
"delivered": "Παραδόθηκε",
|
||||
"served": "Σερβιρίστηκε"
|
||||
"served": "Σερβιρίστηκε",
|
||||
"collected": "Παραλήφθηκε"
|
||||
},
|
||||
"rejectTitle": "Απόρριψη αυτής της παραγγελίας;",
|
||||
"rejectBody": "Ο πελάτης βλέπει τον λόγο στη σελίδα της παραγγελίας του.",
|
||||
@@ -349,7 +353,22 @@
|
||||
"other": "Άλλος λόγος…"
|
||||
},
|
||||
"keep": "Να μείνει",
|
||||
"rejectConfirm": "Απόρριψη παραγγελίας"
|
||||
"rejectConfirm": "Απόρριψη παραγγελίας",
|
||||
"asap": "Το συντομότερο",
|
||||
"for": "Για {{when}}",
|
||||
"diff": {
|
||||
"title": "Οι τιμές διαφέρουν από του καταστήματος",
|
||||
"body": "Ο πελάτης χρεώθηκε {{charged}} online (και πληρώνει αυτό)· με τις σημερινές τιμές εδώ θα ήταν {{here}}.",
|
||||
"fee": "Μεταφορικά",
|
||||
"reason": {
|
||||
"price": "{{online}} online, {{here}} εδώ",
|
||||
"not_sold": "{{online}} online, δεν πωλείται πλέον online εδώ",
|
||||
"option": "{{online}} online, μια επιλογή δεν υπάρχει πλέον εδώ",
|
||||
"fee_price": "{{online}} online, {{here}} εδώ",
|
||||
"fee_area": "{{online}} online, η περιοχή δεν εξυπηρετείται πλέον",
|
||||
"fee_minimum": "{{online}} online, κάτω από την ελάχιστη παραγγελία εδώ"
|
||||
}
|
||||
}
|
||||
},
|
||||
"receipts": {
|
||||
"scope": {
|
||||
|
||||
@@ -102,6 +102,7 @@
|
||||
"area_not_found": "Delivery area {{area_id}} not found.",
|
||||
"rule_not_found": "Fee rule {{rule_id}} not found.",
|
||||
"area_in_use": "This area is used by fee rules: {{rules}}. Change those rules first.",
|
||||
"order_invalid": "The new order must list every rule once."
|
||||
"order_invalid": "The new order must list every rule once.",
|
||||
"vat_group_unknown": "VAT group {{vat_group_id}} isn't one of the fiscal machine's groups."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -541,5 +541,18 @@
|
||||
},
|
||||
"asap": "\"As soon as possible\"",
|
||||
"asapHint": "While open, customers can also order for as soon as possible."
|
||||
},
|
||||
"onlineOrders": {
|
||||
"for": "For {{when}}",
|
||||
"asap": "As soon as possible",
|
||||
"priceDiff": "Charged {{charged}} online; at the venue's prices now it would be {{here}}. The customer pays what they were charged."
|
||||
},
|
||||
"feeProduct": {
|
||||
"title": "The fee on the receipt",
|
||||
"intro": "A delivery order's fee is its own line on the bill and the fiscal receipt. Name it and choose its VAT group.",
|
||||
"name": "Name on the bill and receipt",
|
||||
"vat": "VAT group",
|
||||
"vatNone": "No VAT group",
|
||||
"noGroups": "Set up the fiscal machine's VAT groups in Settings → Fiscal to pick one here."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,8 @@
|
||||
"done": "✓ Done"
|
||||
},
|
||||
"batch": "Round {{n}}",
|
||||
"noCourse": "No course"
|
||||
"noCourse": "No course",
|
||||
"for": "for {{time}}"
|
||||
},
|
||||
"channel": {
|
||||
"here": "Here",
|
||||
@@ -310,7 +311,8 @@
|
||||
"pick": "Pick an order to see it",
|
||||
"type": {
|
||||
"delivery": "Delivery",
|
||||
"dine_in": "At the venue"
|
||||
"dine_in": "At the venue",
|
||||
"takeaway": "Takeaway"
|
||||
},
|
||||
"status": {
|
||||
"pending_acceptance": "Waiting for an answer",
|
||||
@@ -332,11 +334,13 @@
|
||||
},
|
||||
"payAnd": {
|
||||
"delivered": "Take {{amount}} · delivered",
|
||||
"served": "Take {{amount}} · served"
|
||||
"served": "Take {{amount}} · served",
|
||||
"collected": "Take {{amount}} · collected"
|
||||
},
|
||||
"mark": {
|
||||
"delivered": "Mark as delivered",
|
||||
"served": "Mark as served"
|
||||
"served": "Mark as served",
|
||||
"collected": "Mark as collected"
|
||||
},
|
||||
"rejectTitle": "Reject this order?",
|
||||
"rejectBody": "The customer sees the reason on their order page.",
|
||||
@@ -349,7 +353,22 @@
|
||||
"other": "Other reason…"
|
||||
},
|
||||
"keep": "Keep it",
|
||||
"rejectConfirm": "Reject order"
|
||||
"rejectConfirm": "Reject order",
|
||||
"asap": "As soon as possible",
|
||||
"for": "For {{when}}",
|
||||
"diff": {
|
||||
"title": "Prices differ from the venue's",
|
||||
"body": "The customer was charged {{charged}} online (and pays that); at today's prices here it would be {{here}}.",
|
||||
"fee": "Delivery fee",
|
||||
"reason": {
|
||||
"price": "{{online}} online, {{here}} here",
|
||||
"not_sold": "{{online}} online, not sold online here any more",
|
||||
"option": "{{online}} online, an extra no longer exists here",
|
||||
"fee_price": "{{online}} online, {{here}} here",
|
||||
"fee_area": "{{online}} online, the area isn't served here any more",
|
||||
"fee_minimum": "{{online}} online, below the minimum here"
|
||||
}
|
||||
}
|
||||
},
|
||||
"receipts": {
|
||||
"scope": {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// itself after 5 s without a touch); a long press on an unselected card shows quick actions.
|
||||
import { Fragment, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Bike, Info, ShoppingBag, User, Utensils } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { courseGroups, minutesSince } from '../logic/board'
|
||||
import { BLOCK_GAP, BODY_PAD_B, BODY_PAD_H, BODY_PAD_T, CARD_FOOT_H_BASE, CARD_HEAD_H_BASE, CARD_SUB_H_BASE } from '../logic/layout'
|
||||
import { KDS, alpha } from '../theme'
|
||||
@@ -16,8 +16,9 @@ const HOLD_MS = 500
|
||||
const IDLE_DESELECT_MS = 5000
|
||||
const CHANNEL_ICONS = { here: Utensils, takeaway: ShoppingBag, delivery: Bike }
|
||||
|
||||
function ChannelBadge({ orderType, tableName, fs }) {
|
||||
function ChannelBadge({ orderType, tableName, requestedFor, fs }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatTime } = useFormat()
|
||||
const type = CHANNEL_ICONS[orderType] ? orderType : 'here'
|
||||
const Icon = CHANNEL_ICONS[type]
|
||||
const iconSz = Math.round(17 * fs)
|
||||
@@ -25,6 +26,8 @@ function ChannelBadge({ orderType, tableName, fs }) {
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: Math.round(15 * fs), fontWeight: 700, whiteSpace: 'nowrap', color: alpha('on-status', 0.6), flexShrink: 0 }}>
|
||||
<Icon style={{ width: iconSz, height: iconSz, opacity: 0.65 }} />
|
||||
{type === 'here' && tableName ? tableName : t(`kds.channel.${type}`)}
|
||||
{/* an online order for a later time (phase 3S, S.5) */}
|
||||
{requestedFor && <span data-testid="card-for">{t('kds.card.for', { time: formatTime(requestedFor) })}</span>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -159,14 +162,14 @@ export default function OrderCard({ order, age, ageText, layout, focused, dimmed
|
||||
{t('kds.card.items', { count: itemCount })}
|
||||
</span>
|
||||
</div>
|
||||
<div onClick={deselect}><ChannelBadge orderType={order.order_type} tableName={order.table_name} fs={fs} /></div>
|
||||
<div onClick={deselect}><ChannelBadge orderType={order.order_type} tableName={order.table_name} requestedFor={order.requested_for} fs={fs} /></div>
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: subBg, color: alpha('on-status', 0.88),
|
||||
padding: '0 11px', height: Math.round(CARD_SUB_H_BASE * fs), flexShrink: 0, fontSize: 12.5 * fs, fontWeight: 600,
|
||||
}}>
|
||||
<span style={{ fontFamily: 'ui-monospace, monospace', letterSpacing: '.02em', opacity: 0.85, lineHeight: 1 }}>#{order.id}</span>
|
||||
<span style={{ fontFamily: 'ui-monospace, monospace', letterSpacing: '.02em', opacity: 0.85, lineHeight: 1 }}>{order.online_ref || `#${order.id}`}</span>
|
||||
<span onClick={deselect} style={{ fontSize: 11 * fs, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', lineHeight: 1 }}>
|
||||
{t(`kds.card.status.${order.kds_status === 'done' || order.kds_status === 'preparing' ? order.kds_status : 'pending'}`)}
|
||||
</span>
|
||||
|
||||
@@ -4,18 +4,22 @@
|
||||
// ready or out for delivery, then finish: take what's unpaid (the counter's ordinary payment,
|
||||
// cash/card/split with the drawer) and mark it delivered. Someone else's change meanwhile is
|
||||
// refused by the backend and the order shows where it is now.
|
||||
// Phase 3S (S.5): the customer's time (or "as soon as possible"), the delivery area, the
|
||||
// delivery fee as its own line (paid with the items), and a warning when the venue's own
|
||||
// prices differ from what the customer was charged online (the customer pays what they saw).
|
||||
import { useState } from 'react'
|
||||
import { Ban, Banknote, Bike, Check, ChefHat, MapPin, MessageSquare, PackageCheck, Phone, Utensils } from 'lucide-react'
|
||||
import { AlertTriangle, Ban, Banknote, Bike, Check, ChefHat, Clock, MapPin, MessageSquare, PackageCheck, Phone, ShoppingBag, Utensils } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Input } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { nextStep } from './logic/online'
|
||||
import { diffRows, finishWord as finishOf, kindOf, nextStep } from './logic/online'
|
||||
import { itemPayments, orderLines, orderSums, qtyLabel } from './logic/tables'
|
||||
import PaymentDialog from './PaymentDialog'
|
||||
|
||||
const REASONS = ['busy', 'unavailable', 'closing', 'area']
|
||||
const STEP_ICON = { preparing: ChefHat, ready: PackageCheck, out_for_delivery: Bike }
|
||||
const KIND_ICON = { delivery: Bike, takeaway: ShoppingBag, dine_in: Utensils }
|
||||
|
||||
export default function OnlinePanel({ order, onChanged }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
@@ -36,8 +40,9 @@ export default function OnlinePanel({ order, onChanged }) {
|
||||
const lines = orderLines(order)
|
||||
const sums = orderSums(lines)
|
||||
const step = nextStep(order)
|
||||
const delivery = order.type === 'delivery'
|
||||
const finishWord = delivery ? 'delivered' : 'served'
|
||||
const kind = kindOf(order)
|
||||
const KindIcon = KIND_ICON[kind]
|
||||
const finishWord = finishOf(order)
|
||||
|
||||
const run = async (fn) => {
|
||||
setBusy(true)
|
||||
@@ -60,29 +65,32 @@ export default function OnlinePanel({ order, onChanged }) {
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex-1 text-title font-semibold">{order.ref}</span>
|
||||
<span className="text-label font-medium text-ink-2 flex items-center gap-1">
|
||||
{delivery ? <Bike size={16} aria-hidden="true" /> : <Utensils size={16} aria-hidden="true" />}
|
||||
{t(`pos.online.type.${delivery ? 'delivery' : 'dine_in'}`)}
|
||||
<KindIcon size={16} aria-hidden="true" />
|
||||
{t(`pos.online.type.${kind}`)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-caption text-ink-2">{t(`pos.online.status.${order.status}`)} · {formatTime(order.opened_at)}</div>
|
||||
{kind !== 'dine_in' && <WhenChip when={order.requested_for} />}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<section className="p-3 border-b border-line grid gap-1.5 text-body" data-testid="online-customer">
|
||||
<div className="text-body-lg font-semibold">{order.customer.name}</div>
|
||||
{order.customer.phone && <Detail icon={Phone}>{order.customer.phone}</Detail>}
|
||||
{order.customer.address && <Detail icon={MapPin}>{order.customer.address}</Detail>}
|
||||
{order.customer.address && <Detail icon={MapPin}>{order.customer.address}{order.area ? ` · ${order.area}` : ''}</Detail>}
|
||||
{order.customer.notes && (
|
||||
<div className="p-2 rounded-control bg-warning-soft text-warning-ink flex gap-2">
|
||||
<MessageSquare size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span>{order.customer.notes}</span>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<PriceCheck diff={order.price_diff} />
|
||||
<section data-testid="online-lines">
|
||||
{lines.map(l => (
|
||||
<div key={l.id} className={`px-3 py-2 border-b border-line flex items-start gap-2 ${l.paid ? 'text-ink-3' : 'text-ink'}`} data-testid="online-line">
|
||||
<div key={l.id} className={`px-3 py-2 border-b border-line flex items-start gap-2 ${l.paid ? 'text-ink-3' : 'text-ink'}`}
|
||||
data-testid={l.system ? 'online-fee' : 'online-line'}>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="text-body font-medium">{qtyLabel(l.quantity, l.unitType)} {l.name}</span>
|
||||
<span className={`text-body ${l.system ? 'text-ink-2' : 'font-medium'}`}>{l.system ? l.name : `${qtyLabel(l.quantity, l.unitType)} ${l.name}`}</span>
|
||||
{(l.options.length > 0 || l.notes) && (
|
||||
<span className="block text-caption text-ink-2">{[...l.options, l.notes && `“${l.notes}”`].filter(Boolean).join(' · ')}</span>
|
||||
)}
|
||||
@@ -138,6 +146,42 @@ export default function OnlinePanel({ order, onChanged }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** When the customer wants it: a time (with the day when it isn't today) or as soon as possible. */
|
||||
function WhenChip({ when }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatDate, formatDateTime, formatTime } = useFormat()
|
||||
const label = !when ? t('pos.online.asap')
|
||||
: t('pos.online.for', { when: formatDate(when) === formatDate(new Date()) ? formatTime(when) : formatDateTime(when, 'datetimeShort') })
|
||||
return (
|
||||
<div className={`justify-self-start mt-1 px-2 h-7 rounded-control flex items-center gap-1.5 text-label font-semibold
|
||||
${when ? 'bg-info-soft text-info-ink' : 'bg-surface-2 text-ink-2'}`} data-testid="online-when">
|
||||
<Clock size={14} aria-hidden="true" />{label}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The venue's own prices differ from what the customer was charged (S.5): what differs, line by line. */
|
||||
function PriceCheck({ diff }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
const rows = diffRows(diff)
|
||||
if (!rows.length) return null
|
||||
const money = v => (v == null ? '—' : formatMoney(v))
|
||||
return (
|
||||
<section className="m-3 p-2.5 rounded-control bg-warning-soft text-warning-ink grid gap-1 text-label" role="note" data-testid="online-price-diff">
|
||||
<p className="font-semibold flex items-center gap-1.5"><AlertTriangle size={15} aria-hidden="true" />{t('pos.online.diff.title')}</p>
|
||||
<p>{t('pos.online.diff.body', { charged: formatMoney(diff.cloud_total), here: formatMoney(diff.site_total) })}</p>
|
||||
<ul className="grid gap-0.5">
|
||||
{rows.map(r => (
|
||||
<li key={r.key}>
|
||||
{r.name ?? t('pos.online.diff.fee')}: {t(`pos.online.diff.reason.${r.reason}`, { online: money(r.cloud), here: money(r.site) })}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function Detail({ icon: Icon, children }) {
|
||||
return <div className="flex items-start gap-2 text-ink-2"><Icon size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span className="text-ink">{children}</span></div>
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
// finished; picked on the left), each order as a card with its reference, delivery or at the
|
||||
// venue, the customer, how long it has waited and what it costs. New orders stand out until
|
||||
// someone answers them. A tap shows the order on the right (OnlinePanel).
|
||||
import { Bike, Clock, Utensils } from 'lucide-react'
|
||||
import { AlertTriangle, Bike, Clock, ShoppingBag, Utensils } from 'lucide-react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { EmptyState, Spinner } from '@xenia/ui'
|
||||
import { minutesSince } from './logic/online'
|
||||
import { kindOf, minutesSince } from './logic/online'
|
||||
|
||||
const LOOK = {
|
||||
pending_acceptance: 'bg-warning-soft border-warning text-warning-ink',
|
||||
@@ -38,18 +38,26 @@ export default function OnlineView({ data, list, picked, onPick, now }) {
|
||||
|
||||
function OrderCard({ order, picked, onPick, now }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney, formatTime } = useFormat()
|
||||
const Icon = order.type === 'delivery' ? Bike : Utensils
|
||||
const { formatDate, formatDateTime, formatMoney, formatTime } = useFormat()
|
||||
const kind = kindOf(order)
|
||||
const Icon = { delivery: Bike, takeaway: ShoppingBag, dine_in: Utensils }[kind]
|
||||
const waiting = order.status === 'pending_acceptance'
|
||||
const when = order.requested_for
|
||||
? (formatDate(order.requested_for) === formatDate(new Date(now)) ? formatTime(order.requested_for) : formatDateTime(order.requested_for, 'datetimeShort'))
|
||||
: null
|
||||
return (
|
||||
<button type="button" onClick={onPick} aria-pressed={picked} data-testid="online-order" data-order={order.id} data-status={order.status}
|
||||
className={`min-h-32 p-3 rounded-card border-2 shadow-raised text-left flex flex-col gap-1 active:scale-[0.98] transition-transform duration-fast
|
||||
${LOOK[order.status] ?? LOOK.delivered} ${picked ? 'ring-2 ring-accent ring-offset-2 ring-offset-canvas' : ''}`}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="flex-1 min-w-0 text-title font-semibold truncate">{order.ref}</span>
|
||||
<Icon size={18} aria-label={t(`pos.online.type.${order.type === 'delivery' ? 'delivery' : 'dine_in'}`)} />
|
||||
{order.price_diff && <AlertTriangle size={16} aria-label={t('pos.online.diff.title')} data-testid="card-diff" />}
|
||||
<Icon size={18} aria-label={t(`pos.online.type.${kind}`)} />
|
||||
</span>
|
||||
<span className="text-body font-medium truncate">{order.customer.name}</span>
|
||||
{kind !== 'dine_in' && (
|
||||
<span className="text-label font-semibold" data-testid="card-when">{when ? t('pos.online.for', { when }) : t('pos.online.asap')}</span>
|
||||
)}
|
||||
<span className="text-label font-medium">{t(`pos.online.status.${order.status}`)}</span>
|
||||
<span className="mt-auto flex items-baseline justify-between gap-2">
|
||||
<span className="text-heading font-semibold">{formatMoney(order.total)}</span>
|
||||
|
||||
@@ -11,7 +11,7 @@ export function nextStep(order) {
|
||||
switch (order.status) {
|
||||
case 'pending_acceptance': return { kind: 'answer' }
|
||||
case 'accepted': return { kind: 'status', to: 'preparing' }
|
||||
case 'preparing': return { kind: 'status', to: order.type === 'delivery' ? 'out_for_delivery' : 'ready' }
|
||||
case 'preparing': return { kind: 'status', to: kindOf(order) === 'delivery' ? 'out_for_delivery' : 'ready' }
|
||||
case 'ready':
|
||||
case 'out_for_delivery': return { kind: 'finish', pay: order.unpaid > 0.004 }
|
||||
default: return null
|
||||
@@ -32,3 +32,25 @@ export function findOnline(board, id) {
|
||||
export function minutesSince(iso, now = Date.now()) {
|
||||
return Math.max(0, Math.floor((now - Date.parse(iso)) / 60_000))
|
||||
}
|
||||
|
||||
/** What kind of online order: 'delivery' | 'takeaway' | 'dine_in' (a QR-menu table order). */
|
||||
export function kindOf(order) {
|
||||
return order?.type === 'delivery' || order?.type === 'takeaway' ? order.type : 'dine_in'
|
||||
}
|
||||
|
||||
/** The word the finish button uses: delivered (delivery), collected (takeaway), served. */
|
||||
export function finishWord(order) {
|
||||
return { delivery: 'delivered', takeaway: 'collected', dine_in: 'served' }[kindOf(order)]
|
||||
}
|
||||
|
||||
/** The site's price check of a pulled order (phase 3S, S.5; GET /board `price_diff`) as rows:
|
||||
* [{ key, name, cloud, site, reason }]; reason: price | not_sold | option (lines),
|
||||
* fee_price | fee_area | fee_minimum (the delivery fee). [] when the prices matched. */
|
||||
export function diffRows(diff) {
|
||||
if (!diff) return []
|
||||
const rows = (diff.lines ?? []).map((l, i) => ({
|
||||
key: `l${i}`, name: l.name, quantity: l.quantity, cloud: l.cloud, site: l.site, reason: l.reason,
|
||||
}))
|
||||
if (diff.fee) rows.push({ key: 'fee', name: null, quantity: 1, cloud: diff.fee.cloud, site: diff.fee.site, reason: `fee_${diff.fee.reason}` })
|
||||
return rows
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ export function orderLines(order) {
|
||||
options: optionNames(i.selected_options),
|
||||
notes: i.notes,
|
||||
kds: i.kds_status ?? 'pending',
|
||||
system: i.system_key ?? null, // a line the system added: 'delivery_fee' (phase 3S)
|
||||
}))
|
||||
return [...lines.filter(l => !l.paid), ...lines.filter(l => l.paid)]
|
||||
}
|
||||
|
||||
@@ -149,6 +149,25 @@ test('online orders: the next step and finding an order (3.3d)', async () => {
|
||||
assert.equal(minutesSince('2026-11-15T10:01:00Z', at), 0)
|
||||
})
|
||||
|
||||
test('online orders: kind, finish word, the price check rows (S.5)', async () => {
|
||||
const { diffRows, finishWord, kindOf, nextStep } = await import('../src/apps/pos/logic/online.js')
|
||||
assert.equal(kindOf({ type: 'takeaway' }), 'takeaway')
|
||||
assert.equal(kindOf({ type: 'dine_in' }), 'dine_in')
|
||||
assert.equal(kindOf({}), 'dine_in')
|
||||
assert.deepEqual(nextStep({ status: 'preparing', type: 'takeaway' }), { kind: 'status', to: 'ready' })
|
||||
assert.equal(finishWord({ type: 'delivery' }), 'delivered')
|
||||
assert.equal(finishWord({ type: 'takeaway' }), 'collected')
|
||||
assert.equal(finishWord({ type: 'dine_in' }), 'served')
|
||||
assert.deepEqual(diffRows(null), [])
|
||||
assert.deepEqual(diffRows({
|
||||
lines: [{ name: 'Burger', quantity: 2, cloud: 8, site: 8.5, reason: 'price' }],
|
||||
fee: { cloud: 2, site: null, reason: 'area' },
|
||||
}), [
|
||||
{ key: 'l0', name: 'Burger', quantity: 2, cloud: 8, site: 8.5, reason: 'price' },
|
||||
{ key: 'fee', name: null, quantity: 1, cloud: 2, site: null, reason: 'fee_area' },
|
||||
])
|
||||
})
|
||||
|
||||
test('refunds: picking items, quantities, total, method, approval (3.3e)', async () => {
|
||||
const { byPiece, defaultMethod, needsApproval, pickAll, refundLines, refundTotal, setPickQty, togglePick } = await import('../src/apps/pos/logic/refunds.js')
|
||||
const coffee = { id: 1, unit_type: 'piece', refundable: 2, unit_total: 3, method: 'cash', mine: true }
|
||||
|
||||
@@ -562,6 +562,17 @@ try {
|
||||
await page.getByTestId('test-run').click()
|
||||
await page.waitForFunction(() => document.querySelector('[data-testid="test-result"]')?.dataset.refused, null, { timeout: 5000 }).catch(() => {})
|
||||
r.check('fees: …a postcode outside the areas is refused', await page.getByTestId('test-result').getAttribute('data-refused') === 'area_not_served')
|
||||
// S.5: the fee's line on the bill and the receipt (a system product, never in the catalogue)
|
||||
await page.getByTestId('fee-product-name').fill('Delivery')
|
||||
await page.getByTestId('fee-product-vat').fill('2')
|
||||
await page.getByTestId('fee-product-save').click()
|
||||
let feeProduct = null
|
||||
for (let i = 0; i < 30 && feeProduct?.name !== 'Delivery'; i++) {
|
||||
feeProduct = (await api('GET', '/api/connect/fees', { token: boss })).fee_product
|
||||
if (feeProduct?.name !== 'Delivery') await sleep(100)
|
||||
}
|
||||
r.check('fees: the fee line\'s name and VAT group are saved', feeProduct?.name === 'Delivery' && feeProduct?.vat_group_id === 2, JSON.stringify(feeProduct))
|
||||
r.check('fees: …and it never shows in the products list', !(await api('GET', '/api/products/?all=true', { token: boss })).some(p => p.id === feeProduct?.id))
|
||||
await page.screenshot({ path: path.join(OUT, 'manager-fees.png'), fullPage: true })
|
||||
|
||||
await page.goto(`${APP}/settings`)
|
||||
|
||||
@@ -157,7 +157,7 @@ try {
|
||||
const pending = await call('GET', `/api/orders/pending/${numeric}`, { headers: siteH })
|
||||
const delivery = pending.find(o => o.public_ref === 'ORD-0002')
|
||||
r.check('the site receives it at the cloud\'s prices with the area', delivery && delivery.total === 9 && delivery.delivery_fee === 2
|
||||
&& delivery.delivery_area === 'Centre' && delivery.sales_point === 'online_delivery', JSON.stringify(delivery))
|
||||
&& delivery.delivery_area === 'Centre' && delivery.delivery_area_id === 1 && delivery.sales_point === 'online_delivery', JSON.stringify(delivery))
|
||||
for (const status of ['accepted', 'preparing', 'out_for_delivery', 'delivered']) {
|
||||
await call('PATCH', `/api/orders/${delivery.id}/status`, { headers: siteH, body: { status } })
|
||||
const seen = await page.waitForFunction(st => document.querySelector('[data-testid="track"]')?.dataset.status === st, status, { timeout: 15_000 }).then(() => true).catch(() => false)
|
||||
|
||||
+20
-7
@@ -524,14 +524,18 @@ try {
|
||||
await api('PUT', '/api/platform/modules/connect_menu', { token: boss, body: { enabled: true } })
|
||||
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
|
||||
r.check('3.3d: online orders on → the counter gets an Online mode', await shown(page, 'mode-online', 10_000))
|
||||
const cloudOrder = (id, type, name) => ({
|
||||
// S.5: a delivery comes with its fee (€2.50 here, a line of its own), the customer's time and area
|
||||
const FEE = 2.5
|
||||
const cloudOrder = (id, type, name, fee = 0, extra = {}) => ({
|
||||
id, public_ref: `ORD-${String(id).padStart(4, '0')}`, order_type: type, customer_name: name, customer_phone: '6900000000',
|
||||
customer_address: type === 'delivery' ? 'Main square 3' : null, customer_notes: 'Ring twice', status: 'pending_acceptance',
|
||||
items_json: JSON.stringify([{ product_id: simple.id, name: simple.name, quantity: 2, unit_price: simple.price, options: [] }]),
|
||||
subtotal: 2 * simple.price, delivery_fee: 0, total: 2 * simple.price, created_at: new Date().toISOString(),
|
||||
subtotal: 2 * simple.price, delivery_fee: fee, total: 2 * simple.price + fee, created_at: new Date().toISOString(), ...extra,
|
||||
})
|
||||
const chimesBefore = Number(await page.getByTestId('pos-screen').getAttribute('data-chimes'))
|
||||
cloud.queue.push(cloudOrder(41, 'delivery', 'Nikos Online'))
|
||||
const forTime = new Date(Date.now() + 2 * 3600_000)
|
||||
forTime.setUTCMinutes(30, 0, 0)
|
||||
cloud.queue.push(cloudOrder(41, 'delivery', 'Nikos Online', FEE, { requested_for: forTime.toISOString(), delivery_area: 'Centre', delivery_area_id: 1 }))
|
||||
const rang = await page.waitForFunction(n => Number(document.querySelector('[data-testid="pos-screen"]')?.dataset.chimes) > n, chimesBefore, { timeout: 15_000 })
|
||||
.then(() => true).catch(() => false)
|
||||
const badged = await page.waitForFunction(() => document.querySelector('[data-testid="mode-online"]')?.dataset.badge === '1', null, { timeout: 5000 })
|
||||
@@ -548,8 +552,14 @@ try {
|
||||
r.check('3.3d: the order shows the customer (phone, address, note) and the items', await shown(page, 'online-panel', 5000)
|
||||
&& (await page.getByTestId('online-customer').textContent()).includes('Main square 3')
|
||||
&& (await page.getByTestId('online-customer').textContent()).includes('Ring twice')
|
||||
&& await page.getByTestId('online-line').count() === 1
|
||||
&& (await page.getByTestId('online-total').textContent()).includes((2 * simple.price).toFixed(2)))
|
||||
&& await page.getByTestId('online-line').count() === 1)
|
||||
const whenText = await page.getByTestId('online-when').textContent().catch(() => '')
|
||||
r.check('S.5: the delivery fee is its own line, in the total; the customer\'s time and area show',
|
||||
await page.getByTestId('online-fee').count() === 1
|
||||
&& (await page.getByTestId('online-total').textContent()).includes((2 * simple.price + FEE).toFixed(2))
|
||||
&& /\d\d:30/.test(whenText) && (await page.getByTestId('online-customer').textContent()).includes('Centre'), whenText)
|
||||
r.check('S.5: the venue\'s own fee rules differ (it has none) → the counter is warned, the customer still pays what they saw',
|
||||
await shown(page, 'online-price-diff', 3000))
|
||||
await page.screenshot({ path: path.join(OUT, 'terminal-pos-online.png') })
|
||||
const kdsHas = async () => (await api('GET', '/api/kds/orders', { token: boss })).orders.some(o => o.id === onlineId)
|
||||
r.check('3.3d: the kitchen doesn\'t see it before it is accepted', !(await kdsHas()))
|
||||
@@ -573,8 +583,11 @@ try {
|
||||
await page.waitForFunction(() => document.querySelector('[data-testid="online-panel"]')?.dataset.status === 'delivered', null, { timeout: 8000 }).catch(() => {})
|
||||
r.check('3.3d: the driver\'s cash taken at the counter → delivered', await page.getByTestId('online-panel').getAttribute('data-status') === 'delivered')
|
||||
for (let i = 0; i < 20 && drawerBytes.length === drawerBeforeOnline; i++) await sleep(100)
|
||||
r.check('3.3d: …the drawer opened and the items are paid', drawerBytes.length > drawerBeforeOnline
|
||||
&& (await api('GET', `/api/orders/${onlineId}`, { token: boss })).items.every(i => i.status === 'paid'))
|
||||
const paidOnline = await api('GET', `/api/orders/${onlineId}`, { token: boss })
|
||||
r.check('3.3d: …the drawer opened and the items are paid (S.5: the fee too)', drawerBytes.length > drawerBeforeOnline
|
||||
&& paidOnline.items.every(i => i.status === 'paid') && paidOnline.items.some(i => i.system_key === 'delivery_fee' && i.unit_price === FEE))
|
||||
r.check('S.5: …the kitchen never got the fee line', !(await api('GET', '/api/kds/orders', { token: boss })).orders
|
||||
.some(o => o.items.some(i => paidOnline.items.find(x => x.id === i.id)?.system_key)))
|
||||
for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 41 && x.status === 'delivered'); i++) await sleep(100)
|
||||
r.check('3.3d: …and the cloud heard every step', ['accepted', 'preparing', 'out_for_delivery', 'delivered']
|
||||
.every(st => cloud.statuses.some(x => x.id === 41 && x.status === st)), JSON.stringify(cloud.statuses))
|
||||
|
||||
Reference in New Issue
Block a user