Files
xenia-pos-local/local_backend/models/order.py
T
bonaminandClaude Opus 5.5 618fef53ef perf(backend): index the lookup columns and load order lines in batches
Order lines had no index on their order, orders none on their day/customer/status, and each
line's product was loaded to tell a fee apart: with ~3000 orders Customers took ~2 s and
Reports -> Days ~15 s. Migration 0038 adds the indexes (models carry index=True), Order.items
loads with selectin, sales.lines looks the fee products up once, cancellations and prep-zones
load their orders with the lines. Days 15 s -> 0.2 s (a month), customers 2 s -> 0.1 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:42:09 +02:00

264 lines
14 KiB
Python

from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Index, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from database import Base
class Order(Base):
__tablename__ = "orders"
# who opened what when (a shift's orders: migration 0038)
__table_args__ = (Index("ix_orders_opened_by_opened_at", "opened_by", "opened_at"),)
id = Column(Integer, primary_key=True, index=True)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True, index=True) # nullable for online orders
opened_by = Column(Integer, ForeignKey("users.id"), nullable=False)
opened_at = Column(UTCDateTime, default=utcnow, index=True)
status = Column(String, default="open", nullable=False, index=True) # 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, index=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, index=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", lazy="selectin")
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, index=True)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
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"
# what someone added when (a shift's lines, cancellations: migration 0038)
__table_args__ = (Index("ix_order_items_added_by_added_at", "added_by", "added_at"),)
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
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, index=True) # 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, index=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)
# where the line came from (plan step 4.8): waiter | counter | qr | online; NULL = before 4.8
source = Column(String, 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, index=True)
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, index=True)
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" | "handled" (6.10)
resolved_by = Column(Integer, nullable=True) # 6.10: who sent it elsewhere / marked it handled
redirected_to = Column(Integer, nullable=True) # 6.10: the printer it was sent to instead (status success)
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, index=True)
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, index=True)
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