Owner 2026-11-23 (plan 6F.6). Venue setting payments.split_amount (off | two_equal | two_custom |
multiple_equal, each level with the ones before; default off) and payments.split_max_parts (10);
key ordering.payments.split_amount (everyone who takes payments; Alembic 0050 grants it).
POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status 'split': sold, no shift,
no payment method) and adds part lines (system product split_part, "Split bill 1/3", printed and
served; equal parts with the remainder on the last, or two parts with part 1 typed). Parts are paid
like any line (cash, card, tab). POST .../split-bills/{bill}/undo while no part is paid or tabbed.
Counting (services/sales.py): settled lines are the sales, parts never (a refunded part comes off
the settled lines by share); drawers and payment methods count the parts. Older reports use
split_bills.sold_filter / counts_as_sale. Locks: parts can't be cancelled, moved, combined or
re-priced; settled lines are no longer active; closing or cancelling an order with unpaid parts is
refused. Fiscal: one receipt with the settled lines when the last part is paid, with each method's
amount (txt driver: CD per card amount, then CR for cash).
Waiter: Pay -> "Split the amount" (pre-filled from the customers), the split bill above the lines
with Undo. Counter: "By amount" in the payment (quick sale split and paid at once, Q-4; a table's
lines split then paid). Manager: the pay dialog splits, the order shows its split bills, Settings ->
Operation card. Shared rules in @xenia/ordering/split.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
321 lines
17 KiB
Python
321 lines
17 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)
|
|
# the line this one was cut from (6F.4): a split, a lowered quantity, a split payment; its moves
|
|
# before the cut are this line's too (services/moves.py)
|
|
split_from_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True)
|
|
# a split bill (6F.6): on the lines it settled (status "split") and on its part lines (the
|
|
# system product split_part, paid like any line); services/split_bills.py
|
|
split_bill_id = Column(Integer, ForeignKey("split_bills.id"), nullable=True, index=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
|
|
|
|
|
|
class OrderMove(Base):
|
|
"""Something moved between tables or orders (owner 2026-11-23, plan 6F.4, services/moves.py):
|
|
a whole order to another table (`table_transfer`), chosen lines to another order
|
|
(`items_moved`), or one order joined into another (`orders_merged`). Never deleted."""
|
|
__tablename__ = "order_moves"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
kind = Column(String, nullable=False, index=True) # table_transfer | items_moved | orders_merged
|
|
from_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
|
|
to_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
|
|
from_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
|
|
to_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
|
|
by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
|
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
|
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
|
|
note = Column(Text, nullable=True) # the importer / backfill: where it came from
|
|
|
|
items = relationship("OrderMoveItem", back_populates="move", cascade="all, delete-orphan")
|
|
|
|
|
|
class OrderMoveItem(Base):
|
|
"""A line that went with a move, and how much of it (its quantity at the time)."""
|
|
__tablename__ = "order_move_items"
|
|
|
|
move_id = Column(Integer, ForeignKey("order_moves.id", ondelete="CASCADE"), primary_key=True)
|
|
item_id = Column(Integer, ForeignKey("order_items.id"), primary_key=True, index=True)
|
|
quantity = Column(Float, nullable=True)
|
|
|
|
move = relationship("OrderMove", back_populates="items")
|
|
|
|
|
|
class SplitBill(Base):
|
|
"""A bill split by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py): chosen lines
|
|
settled together (status "split") and cut into `parts` part lines that are paid on their own.
|
|
Undone (undone_at) only while no part was paid or put on a tab."""
|
|
__tablename__ = "split_bills"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
|
total = Column(Float, nullable=False)
|
|
mode = Column(String, nullable=False) # equal | custom
|
|
parts = Column(Integer, nullable=False)
|
|
amounts = Column(Text, nullable=False) # JSON [4.5, 10.5]: each part, in order
|
|
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
|
undone_at = Column(UTCDateTime, nullable=True)
|
|
undone_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
|
receipt_issued_at = Column(UTCDateTime, nullable=True) # the fiscal receipt of the settled lines (last part paid)
|