Files
xenia-pos-local/local_backend/models/order.py
T
bonaminandClaude Opus 5.5 0ca700279a 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>
2026-11-15 15:38:25 +02:00

256 lines
13 KiB
Python

from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from database import Base
class Order(Base):
__tablename__ = "orders"
id = Column(Integer, primary_key=True, index=True)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True) # nullable for online orders
opened_by = Column(Integer, ForeignKey("users.id"), nullable=False)
opened_at = Column(UTCDateTime, default=utcnow)
status = Column(String, default="open", nullable=False) # open|partially_paid|paid|closed|cancelled
closed_at = Column(UTCDateTime, nullable=True)
closed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
notes = Column(Text, nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True)
# KDS
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done
kds_status_changed_at = Column(UTCDateTime, nullable=True)
order_type = Column(String, default="here", nullable=False) # here|takeaway|delivery
sales_point = Column(String, default="in_store", nullable=False) # core/sales_points.py (phase 3S)
# Xenia Connect — online order fields
source = Column(String, default="pos", nullable=False) # "pos" | "online"
online_order_ref = Column(String, nullable=True) # e.g. "ORD-0042"
online_order_cloud_id = Column(Integer, nullable=True) # cloud DB pk for status mirroring
online_status = Column(String, nullable=True) # mirrors cloud status
online_customer_name = Column(String, nullable=True)
online_customer_phone = Column(String, nullable=True)
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)
# Number of customers at the table for this order
customer_count = Column(Integer, nullable=True)
# Fiscal printer status: NULL = fiscal was off, "pending" | "success" | "failed"
fiscal_status = Column(String, nullable=True)
table = relationship("Table", back_populates="orders")
opener = relationship("User", foreign_keys=[opened_by], back_populates="orders_opened")
closer = relationship("User", foreign_keys=[closed_by], back_populates="orders_closed")
customer = relationship("Customer", back_populates="orders", foreign_keys=[customer_id])
items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan")
waiters = relationship("OrderWaiter", back_populates="order", cascade="all, delete-orphan")
print_logs = relationship("PrintLog", back_populates="order", cascade="all, delete-orphan")
print_jobs = relationship("PrintJob", back_populates="order", cascade="all, delete-orphan")
audit_logs = relationship("OrderAuditLog", back_populates="order", cascade="all, delete-orphan")
discounts = relationship("OrderDiscount", back_populates="order", cascade="all, delete-orphan")
class OrderWaiter(Base):
__tablename__ = "order_waiters"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
assigned_at = Column(UTCDateTime, default=utcnow)
order = relationship("Order", back_populates="waiters")
waiter = relationship("User", back_populates="order_assignments")
class OrderItem(Base):
__tablename__ = "order_items"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
added_by = Column(Integer, ForeignKey("users.id"), nullable=False)
quantity = Column(Float, nullable=False)
unit_price = Column(Float, nullable=False) # price snapshot at time of order
# Name snapshots (D-18, CS-4): what the item was called, and its category, when it was
# ordered. Reports read these, so renaming or moving a product never rewrites history.
# Filled automatically for every new item by the before_flush hook at the end of this
# file; never updated afterwards. category_id is a plain id (categories can be deleted).
product_name = Column(String, nullable=False)
category_id = Column(Integer, nullable=True, index=True)
category_name = Column(String, nullable=True)
selected_options = Column(Text, nullable=True) # JSON array of option ids
removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids
notes = Column(Text, nullable=True)
status = Column(String, default="active", nullable=False) # active|paid|cancelled
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done|served|declined
added_at = Column(UTCDateTime, default=utcnow)
printed = Column(Boolean, default=False, nullable=False)
# Payment tracking
paid_by = Column(Integer, ForeignKey("users.id"), nullable=True)
paid_at = Column(UTCDateTime, nullable=True)
payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use
paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True)
# Phase 2A — cost snapshot (copied from product at time of order, never updated)
unit_cost = Column(Float, nullable=True)
# On-the-fly price adjustment (positive = surcharge, negative = discount)
price_adjustment = Column(Float, nullable=False, default=0.0)
# Phase 2B — cancellation tracking
cancelled_by = Column(Integer, ForeignKey("users.id"), nullable=True)
cancelled_at = Column(UTCDateTime, nullable=True)
cancel_reason = Column(Text, nullable=True)
# KDS decline tracking
decline_note = Column(Text, nullable=True) # reason set by kitchen when declining
# KDS claim (plan step 3.2c): the cook working on this item; cleared when it moves on
claimed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
claimed_at = Column(UTCDateTime, nullable=True)
# Courses — optional course assignment for sequenced firing
course_id = Column(Integer, nullable=True)
# Deal binding — which deal created this item, and which original item it's linked to
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
linked_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
order = relationship("Order", back_populates="items")
product = relationship("Product", back_populates="order_items")
added_by_user = relationship("User", foreign_keys=[added_by], back_populates="order_items")
paid_by_user = relationship("User", foreign_keys=[paid_by], back_populates="items_paid")
claimed_by_user = relationship("User", foreign_keys=[claimed_by])
@property
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"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
printed_at = Column(UTCDateTime, default=utcnow)
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
success = Column(Boolean, nullable=False)
error_message = Column(Text, nullable=True)
order = relationship("Order", back_populates="print_logs")
printer = relationship("Printer", back_populates="print_logs")
class PrintJob(Base):
"""
One row per (order, printer, zone) print job. Tracks the full lifecycle:
pending → success or cancelled. PrintLog rows record each individual attempt.
"""
__tablename__ = "print_jobs"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
zone_id = Column(Integer, nullable=True) # prep zone id, NULL for legacy
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
copies = Column(Integer, nullable=False, default=1)
status = Column(String, nullable=False, default="pending") # pending|success|cancelled
retry_count = Column(Integer, nullable=False, default=0)
first_attempted_at = Column(UTCDateTime, default=utcnow)
last_attempted_at = Column(UTCDateTime, nullable=True)
succeeded_at = Column(UTCDateTime, nullable=True)
cancelled_at = Column(UTCDateTime, nullable=True)
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed"
order = relationship("Order", back_populates="print_jobs")
printer = relationship("Printer", back_populates="print_jobs")
class OrderAuditLog(Base):
"""Immutable append-only audit trail for every action on an order."""
__tablename__ = "order_audit_log"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
event_type = Column(String, nullable=False)
# ORDER_OPENED | ITEMS_ADDED | PAYMENT | PAYMENT_OFFLINE | ORDER_CLOSED | ORDER_CANCELLED | ITEM_CANCELLED
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=True)
item_ids = Column(Text, nullable=True) # JSON list of OrderItem ids
amount = Column(Float, nullable=True) # total value for PAYMENT events
payment_method = Column(String, nullable=True)
note = Column(Text, nullable=True)
created_at = Column(UTCDateTime, default=utcnow)
# Emergency offline payment fields
offline_uuid = Column(String, nullable=True) # client-generated UUID for dedup
offline_at = Column(String, nullable=True) # ISO timestamp from client
is_duplicate = Column(Integer, nullable=False, default=0) # 1 = duplicate payment flagged
order = relationship("Order", back_populates="audit_logs")
waiter = relationship("User")
@property
def waiter_name(self):
return self.waiter.username if self.waiter else None
class OrderDiscount(Base):
"""Records a discount applied to an order or a specific item."""
__tablename__ = "order_discounts"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL = whole-order discount
discount_type = Column(String, nullable=False) # 'percent' | 'fixed'
discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00
applied_by = Column(Integer, ForeignKey("users.id"), nullable=False)
applied_at = Column(UTCDateTime, default=utcnow)
reason = Column(Text, nullable=True)
order = relationship("Order", back_populates="discounts")
item = relationship("OrderItem")
applied_by_user = relationship("User")
# ── Name snapshots for new order items (D-18) ────────────────────────────────
from sqlalchemy import event as _event # noqa: E402
from sqlalchemy.orm import Session as _Session # noqa: E402
@_event.listens_for(_Session, "before_flush")
def _snapshot_item_names(session, flush_context, instances):
"""Every new OrderItem gets the product's current name and category, whoever creates
it (waiter, counter, online orders, deals, demo seed). An item created with a
product_name already set is left alone: the caller snapshots everything itself
(the v1 importer, plan 7.1)."""
from models.product import Category, Product
for obj in session.new:
if not isinstance(obj, OrderItem) or obj.product_name:
continue
product = session.get(Product, obj.product_id) if obj.product_id is not None else None
obj.product_name = product.name if product else f"#{obj.product_id}"
if obj.category_id is None and product is not None and product.primary_category_id is not None:
obj.category_id = product.primary_category_id # the PRIMARY category (D-23)
if obj.category_id is not None and obj.category_name is None:
cat = session.get(Category, obj.category_id)
obj.category_name = cat.name if cat else None