diff --git a/docs/README.md b/docs/README.md index ea6a8c3..335c9d2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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 | diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 8a00e88..3b496b6 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -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."), diff --git a/local_backend/core/i18n/el.json b/local_backend/core/i18n/el.json index decfde9..3a15b13 100644 --- a/local_backend/core/i18n/el.json +++ b/local_backend/core/i18n/el.json @@ -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": "Μεταφορικά" } } diff --git a/local_backend/core/i18n/en.json b/local_backend/core/i18n/en.json index a73402f..4be6915 100644 --- a/local_backend/core/i18n/en.json +++ b/local_backend/core/i18n/en.json @@ -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" } } diff --git a/local_backend/migrations/versions/0019_online_order_site_side.py b/local_backend/migrations/versions/0019_online_order_site_side.py new file mode 100644 index 0000000..84cb125 --- /dev/null +++ b/local_backend/migrations/versions/0019_online_order_site_side.py @@ -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') diff --git a/local_backend/models/order.py b/local_backend/models/order.py index 17e9d6f..4c6fe2f 100644 --- a/local_backend/models/order.py +++ b/local_backend/models/order.py @@ -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" diff --git a/local_backend/models/product.py b/local_backend/models/product.py index 17cc179..67ec6da 100644 --- a/local_backend/models/product.py +++ b/local_backend/models/product.py @@ -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) diff --git a/local_backend/routers/connect_orders.py b/local_backend/routers/connect_orders.py index a79aaee..58b6aae 100644 --- a/local_backend/routers/connect_orders.py +++ b/local_backend/routers/connect_orders.py @@ -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), } diff --git a/local_backend/routers/data_transfer.py b/local_backend/routers/data_transfer.py index 8c7857a..c95ab4a 100644 --- a/local_backend/routers/data_transfer.py +++ b/local_backend/routers/data_transfer.py @@ -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() ) diff --git a/local_backend/routers/fees.py b/local_backend/routers/fees.py index 0828057..27ebfdd 100644 --- a/local_backend/routers/fees.py +++ b/local_backend/routers/fees.py @@ -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") diff --git a/local_backend/routers/kds.py b/local_backend/routers/kds.py index 4dfb4f4..4ad2a17 100644 --- a/local_backend/routers/kds.py +++ b/local_backend/routers/kds.py @@ -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, } diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index 44659a8..ca3b68e 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -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], diff --git a/local_backend/routers/products.py b/local_backend/routers/products.py index 6922d0c..aa747fd 100644 --- a/local_backend/routers/products.py +++ b/local_backend/routers/products.py @@ -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: diff --git a/local_backend/schemas/order.py b/local_backend/schemas/order.py index dd827c9..b1b0365 100644 --- a/local_backend/schemas/order.py +++ b/local_backend/schemas/order.py @@ -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 diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 09557c9..25f6fe7 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -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: diff --git a/local_backend/services/online_check.py b/local_backend/services/online_check.py new file mode 100644 index 0000000..39bda06 --- /dev/null +++ b/local_backend/services/online_check.py @@ -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)} diff --git a/local_backend/services/pos_cart.py b/local_backend/services/pos_cart.py index 15b3827..4d4dcb9 100644 --- a/local_backend/services/pos_cart.py +++ b/local_backend/services/pos_cart.py @@ -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: diff --git a/local_backend/services/printer_service.py b/local_backend/services/printer_service.py index c80ed1c..268b723 100644 --- a/local_backend/services/printer_service.py +++ b/local_backend/services/printer_service.py @@ -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: diff --git a/local_backend/services/system_products.py b/local_backend/services/system_products.py new file mode 100644 index 0000000..5b3802e --- /dev/null +++ b/local_backend/services/system_products.py @@ -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} diff --git a/local_backend/tests/test_online_site_side.py b/local_backend/tests/test_online_site_side.py new file mode 100644 index 0000000..c296e3e --- /dev/null +++ b/local_backend/tests/test_online_site_side.py @@ -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") diff --git a/manager_dashboard/src/pages/OnlineOrdersPage.jsx b/manager_dashboard/src/pages/OnlineOrdersPage.jsx index e72fd69..d0ed2fb 100644 --- a/manager_dashboard/src/pages/OnlineOrdersPage.jsx +++ b/manager_dashboard/src/pages/OnlineOrdersPage.jsx @@ -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 }) { - {isDelivery ? 'Delivery' : 'Dine-in'} + {isDelivery ? 'Delivery' : isTakeaway ? 'Takeaway' : 'Dine-in'} @@ -91,7 +100,15 @@ function OrderCard({ order, onAction }) {

{order.online_customer_phone}

)} {isDelivery && order.online_customer_address && ( -

{order.online_customer_address}

+

{order.online_customer_address}{order.online_delivery_area ? ` · ${order.online_delivery_area}` : ''}

+ )} + {(isDelivery || isTakeaway) && ( +

{when}

+ )} + {diff && ( +

+ {t('onlineOrders.priceDiff', { charged: formatMoney(diff.cloud_total), here: formatMoney(diff.site_total) })} +

)} {order.online_customer_notes && (

@@ -105,7 +122,9 @@ function OrderCard({ order, onAction }) {

{order.items.map((it, i) => (
- {it.quantity} × {it.product?.name ?? `#${it.product_id}`} + + {it.system_key ? (it.product_name ?? it.product?.name) : `${it.quantity} × ${it.product_name ?? it.product?.name ?? `#${it.product_id}`}`} + €{(((it.unit_price ?? 0) + (it.price_adjustment ?? 0)) * it.quantity).toFixed(2)}
))} diff --git a/manager_dashboard/src/pages/online/FeeProductCard.jsx b/manager_dashboard/src/pages/online/FeeProductCard.jsx new file mode 100644 index 0000000..3625342 --- /dev/null +++ b/manager_dashboard/src/pages/online/FeeProductCard.jsx @@ -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 ( +
+
+

{t('feeProduct.title')}

+

{t('feeProduct.intro')}

+
+ + setName(e.target.value)} data-testid="fee-product-name" /> + + + {groups.length ? ( + + ) : ( + setVat(e.target.value.replace(/\D/g, ''))} data-testid="fee-product-vat" /> + )} + +
+
+ ) +} diff --git a/manager_dashboard/src/pages/online/FeesPage.jsx b/manager_dashboard/src/pages/online/FeesPage.jsx index 4e1ff1f..3b491ae 100644 --- a/manager_dashboard/src/pages/online/FeesPage.jsx +++ b/manager_dashboard/src/pages/online/FeesPage.jsx @@ -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() { )} + {data.fee_product && }
diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index a2baa6a..6512674 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -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}} δεν είναι μία από τις ομάδες της φορολογικής μηχανής." } } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index daccc6b..3932bf4 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -541,5 +541,18 @@ }, "asap": "«Το συντομότερο»", "asapHint": "Όσο είναι ανοιχτά, οι πελάτες μπορούν να παραγγείλουν και για το συντομότερο." + }, + "onlineOrders": { + "for": "Για {{when}}", + "asap": "Το συντομότερο", + "priceDiff": "Χρεώθηκε {{charged}} online· με τις τωρινές τιμές του καταστήματος θα ήταν {{here}}. Ο πελάτης πληρώνει όσο χρεώθηκε." + }, + "feeProduct": { + "title": "Τα μεταφορικά στην απόδειξη", + "intro": "Τα μεταφορικά μιας παραγγελίας διανομής είναι ξεχωριστή γραμμή στον λογαριασμό και στη φορολογική απόδειξη. Δώστε της όνομα και ομάδα ΦΠΑ.", + "name": "Όνομα στον λογαριασμό και την απόδειξη", + "vat": "Ομάδα ΦΠΑ", + "vatNone": "Χωρίς ομάδα ΦΠΑ", + "noGroups": "Ορίστε τις ομάδες ΦΠΑ της φορολογικής μηχανής στις Ρυθμίσεις → Φορολογικά για να διαλέξετε εδώ." } } diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index a9816ec..cc4003d 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -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": { diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 9d515fa..b118cce 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -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." } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index b0f4893..c2458b7 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -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." } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index 634983d..1497152 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -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": { diff --git a/terminal/src/apps/kds/components/OrderCard.jsx b/terminal/src/apps/kds/components/OrderCard.jsx index 70d2a16..627ac3c 100644 --- a/terminal/src/apps/kds/components/OrderCard.jsx +++ b/terminal/src/apps/kds/components/OrderCard.jsx @@ -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 }) { {type === 'here' && tableName ? tableName : t(`kds.channel.${type}`)} + {/* an online order for a later time (phase 3S, S.5) */} + {requestedFor && {t('kds.card.for', { time: formatTime(requestedFor) })}} ) } @@ -159,14 +162,14 @@ export default function OrderCard({ order, age, ageText, layout, focused, dimmed {t('kds.card.items', { count: itemCount })} -
+
- #{order.id} + {order.online_ref || `#${order.id}`} {t(`kds.card.status.${order.kds_status === 'done' || order.kds_status === 'preparing' ? order.kds_status : 'pending'}`)} diff --git a/terminal/src/apps/pos/OnlinePanel.jsx b/terminal/src/apps/pos/OnlinePanel.jsx index f2335a9..ff99c41 100644 --- a/terminal/src/apps/pos/OnlinePanel.jsx +++ b/terminal/src/apps/pos/OnlinePanel.jsx @@ -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 }) {
{order.ref} - {delivery ?
{t(`pos.online.status.${order.status}`)} · {formatTime(order.opened_at)}
+ {kind !== 'dine_in' && }
{order.customer.name}
{order.customer.phone && {order.customer.phone}} - {order.customer.address && {order.customer.address}} + {order.customer.address && {order.customer.address}{order.area ? ` · ${order.area}` : ''}} {order.customer.notes && (
)}
+
{lines.map(l => ( -
+
- {qtyLabel(l.quantity, l.unitType)} {l.name} + {l.system ? l.name : `${qtyLabel(l.quantity, l.unitType)} ${l.name}`} {(l.options.length > 0 || l.notes) && ( {[...l.options, l.notes && `“${l.notes}”`].filter(Boolean).join(' · ')} )} @@ -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 ( +
+
+ ) +} + +/** 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 ( +
+

+

{t('pos.online.diff.body', { charged: formatMoney(diff.cloud_total), here: formatMoney(diff.site_total) })}

+
    + {rows.map(r => ( +
  • + {r.name ?? t('pos.online.diff.fee')}: {t(`pos.online.diff.reason.${r.reason}`, { online: money(r.cloud), here: money(r.site) })} +
  • + ))} +
+
+ ) +} + function Detail({ icon: Icon, children }) { return
} diff --git a/terminal/src/apps/pos/OnlineView.jsx b/terminal/src/apps/pos/OnlineView.jsx index 9142fd9..39904ec 100644 --- a/terminal/src/apps/pos/OnlineView.jsx +++ b/terminal/src/apps/pos/OnlineView.jsx @@ -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 (