feat(backend,waiter,terminal,manager): split the bill by amount

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>
This commit is contained in:
2026-11-23 10:57:54 +02:00
co-authored by Claude Opus 5.5
parent 72e175ab73
commit 3eeafb565a
54 changed files with 1707 additions and 105 deletions
+7
View File
@@ -230,6 +230,13 @@ CODES: dict[str, tuple[int, str]] = {
"order.quantity_line": (400, "This line's quantity can't be changed here."),
"order.price_change_sent_off": (403, "Prices can only be changed before the items are sent."),
"order.price_reason_required": (400, "Say why the price changes."),
"split.not_allowed": (403, "Splitting a bill this way isn't turned on for this venue."),
"split.lines_changed": (409, "Some of these items were paid or changed meanwhile. Look again."),
"split.amount_invalid": (400, "Each part must be more than 0 and less than the total ({total})."),
"split.part_locked": (400, "This is part of a split bill: undo the split to change it."),
"split.not_found": (404, "That split bill isn't there any more."),
"split.paid_already": (409, "A part is already paid or on a tab: the split can't be undone."),
"split.parts_unpaid": (400, "Parts of a split bill are still unpaid: take their payment first."),
"order.nothing_paid": (404, "There are no paid items to undo."),
"order.cannot_close": (400, "This order can't be closed now ({status})."),
"order.no_active_items": (400, "None of these items are on the order any more."),
+7 -2
View File
@@ -53,7 +53,8 @@
"paid_total": "Πληρωμενο: {value:.2f}e",
"pending": "ΕΚΚΡΕΜΗ:",
"remaining": "Εκκρεμει: {value:.2f}e",
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ"
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ",
"split": "ΔΙΑΧΩΡΙΣΜΟΣ (ΕΞΟΦΛΕΙΤΑΙ ΑΠΟ ΤΑ ΜΕΡΗ):"
},
"ticket": {
"compact_guests": " | {count}ατ.",
@@ -92,7 +93,8 @@
}
},
"system_product": {
"delivery_fee": "Μεταφορικά"
"delivery_fee": "Μεταφορικά",
"split_part": "Διαχωρισμός λογαριασμού"
},
"qr": {
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
@@ -104,5 +106,8 @@
"order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.",
"order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.",
"bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό."
},
"split": {
"part_name": "Μέρος λογαριασμού {n}/{of}"
}
}
+7 -2
View File
@@ -53,7 +53,8 @@
"paid_total": "Paid: {value:.2f}e",
"pending": "PENDING:",
"remaining": "Remaining: {value:.2f}e",
"title": "ORDER SUMMARY"
"title": "ORDER SUMMARY",
"split": "SPLIT BILL (SETTLED BY THE PARTS):"
},
"ticket": {
"compact_guests": " | {count}pax",
@@ -92,7 +93,8 @@
}
},
"system_product": {
"delivery_fee": "Delivery fee"
"delivery_fee": "Delivery fee",
"split_part": "Split bill"
},
"qr": {
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
@@ -104,5 +106,8 @@
"order_sent": "Table {table} ordered from the tablet ({count} items): sent to the kitchen.",
"order_waiting": "Table {table} ordered from the tablet ({count} items): confirm it on the table.",
"bill_message": "Table {table}: the guests ask for the bill."
},
"split": {
"part_name": "Split bill {n}/{of}"
}
}
@@ -0,0 +1,59 @@
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
- split_bills: chosen lines settled together and cut into parts paid on their own.
- order_items.split_bill_id: on the settled lines (status 'split') and on the part lines.
- The key ordering.payments.split_amount for everyone who takes payments (holds
ordering.orders.close); the venue's setting payments.split_amount starts 'off'.
Revision ID: 0050_split_bills
Revises: 0049_one_more
Create Date: 2026-11-23 21:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0050_split_bills'
down_revision = '0049_one_more'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'split_bills',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=False),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('mode', sa.String(), nullable=False),
sa.Column('parts', sa.Integer(), nullable=False),
sa.Column('amounts', sa.Text(), nullable=False),
sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
sa.Column('undone_at', UTCDateTime(), nullable=True),
sa.Column('undone_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('receipt_issued_at', UTCDateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
for col in ('id', 'order_id', 'business_day_id'):
op.create_index(f'ix_split_bills_{col}', 'split_bills', [col])
with op.batch_alter_table('order_items') as b:
b.add_column(sa.Column('split_bill_id', sa.Integer(), nullable=True))
b.create_index('ix_order_items_split_bill_id', ['split_bill_id'])
b.create_foreign_key('fk_order_items_split_bill', 'split_bills', ['split_bill_id'], ['id'])
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select user_id, 'ordering.payments.split_amount' from user_permissions "
"where key = 'ordering.orders.close'"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.payments.split_amount'"))
with op.batch_alter_table('order_items') as b:
b.drop_constraint('fk_order_items_split_bill', type_='foreignkey')
b.drop_index('ix_order_items_split_bill_id')
b.drop_column('split_bill_id')
for col in ('id', 'order_id', 'business_day_id'):
op.drop_index(f'ix_split_bills_{col}', 'split_bills')
op.drop_table('split_bills')
+23
View File
@@ -136,6 +136,9 @@ class OrderItem(Base):
# 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")
@@ -295,3 +298,23 @@ class OrderMoveItem(Base):
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)
@@ -17,6 +17,7 @@ MODULE = Module(
Perm('ordering.prices.view_changes', 'See the prices changed by hand (who, when, why)', roles=('owner', 'store_manager')),
Perm('ordering.refunds', 'Refund payments from other shifts', roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.payments.revert', 'Turn paid items back to unpaid', roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.payments.split_amount', 'Split a bill by amount (equal parts or a ratio)', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter'), overridable=True),
Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')),
),
settings=(
@@ -32,6 +33,8 @@ MODULE = Module(
SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'),
SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'),
SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'),
SettingDef('payments.split_amount', 'off', "Splitting a bill by amount (6F.6), each level with the ones before: 'off' | 'two_equal' (half and half) | 'two_custom' (two parts in any ratio) | 'multiple_equal' (2 to payments.split_max_parts equal parts). Who may: ordering.payments.split_amount.", type='enum', choices=('off', 'two_equal', 'two_custom', 'multiple_equal')),
SettingDef('payments.split_max_parts', '10', 'The most equal parts a bill can be split into (6F.6, 2-50).', type='int'),
SettingDef('payments.card_enabled', 'false', "Allow waiters to record card payments (in addition to cash): 'true' | 'false'", type='bool'),
SettingDef('print.alert_after_failures', '2', 'Tell managers when a kitchen/bar ticket has failed to print this many times and is still retrying (0 = never; they are always told when a ticket is finally given up).', type='int'),
SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'),
+4 -2
View File
@@ -312,8 +312,9 @@ def business_day_summary(
if o.table_id:
waiter_tables.setdefault(o.opened_by, set()).add(o.table_id)
from services.split_bills import is_part
for item in all_items:
if item.status == "cancelled":
if item.status == "cancelled" or is_part(item): # 6F.6: a split bill's parts are money, not items ordered
continue
e = _waiter_entry(item.added_by)
e["items_ordered"] += item.quantity
@@ -407,7 +408,8 @@ def business_day_summary(
for item in o.items:
if item.status == "cancelled":
continue
entry["items"] += item.quantity
if not is_part(item):
entry["items"] += item.quantity
if item.status == "paid":
entry["revenue"] += gross(item)
+1 -1
View File
@@ -299,7 +299,7 @@ def bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"
return {"lines": [], "total": 0, "paid": 0, "due": 0}
lines = []
for i in order.items:
if i.status == "cancelled":
if i.status in ("cancelled", "split"): # 6F.6: a split bill's parts stand for the lines it settled
continue
unit = (i.unit_price or 0) + (i.price_adjustment or 0)
texts = menu_languages.product_texts(i.product, customer=False) if i.product else {}
+109 -11
View File
@@ -61,6 +61,7 @@ from core.access.deps import require
from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket
from models.settings import PosSettings
from services.ws_bus import broadcast_sync
from services import split_bills
router = APIRouter()
@@ -370,6 +371,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
"deal_id": i.deal_id, "linked_item_id": i.linked_item_id,
"split_from_id": i.split_from_id, # 6F.4: the line it was cut from
"cancel_reason": i.cancel_reason,
"split_bill_id": i.split_bill_id, # 6F.6: settled into a split bill (status split) or one of its parts
}
def fmt_log(l):
@@ -422,6 +424,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
"requested_for": _iso(order.requested_for),
"online_delivery_area": order.online_delivery_area,
"items": [fmt_item(i) for i in order.items],
"split_bills": [split_bills.bill_out(b, order.items) for b in split_bills.live_bills(db, order.id)], # 6F.6
"waiters": [{"waiter_id": w.waiter_id} for w in order.waiters],
"audit_logs": [fmt_log(l) for l in order.audit_logs],
}
@@ -923,6 +926,9 @@ def cancel_item(
raise XeniaError("order.item_not_found")
if item.status == "paid":
raise XeniaError("order.item_paid")
if item.status not in ("active", "ready"):
raise XeniaError("order.item_not_active")
split_bills.refuse_parts([item]) # 6F.6: undo the split instead
now = utcnow()
item.status = "cancelled"
@@ -973,10 +979,13 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
OrderItem.status.in_(["active", "ready"]), # ready items are also payable
).all()
# Fiscal validation: if enabled, all items must have VAT group assigned before payment
# Fiscal validation: if enabled, all items must have VAT group assigned before payment.
# A split bill's parts (6F.6) aren't on a receipt themselves: the settled lines are, once the
# last part is paid (checked when the bill was made).
fiscal_on = is_fiscal_enabled(db)
if fiscal_on and items:
missing = validate_items_for_fiscal(items, db)
own = [i for i in items if not split_bills.is_part(i)]
if fiscal_on and own:
missing = validate_items_for_fiscal(own, db)
if missing:
names = ", ".join(missing)
raise XeniaError("pos.fiscal_vat_missing", names=names)
@@ -1020,7 +1029,12 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
order.closed_by = user.id
auto_closed = True
if fiscal_on and items:
bills_due = split_bills.receipts_due(db, items) # 6F.6: the last part of a split bill
for due in bills_due:
_audit(db, order_id, "SPLIT_SETTLED", waiter_id=user.id, item_ids=[i.id for i in due["lines"]],
amount=due["bill"].total, note=" + ".join(f"{p['method']} {p['amount']:.2f}" for p in due["payments"]))
fiscal_sent = fiscal_on and (bool(own) or bool(bills_due))
if fiscal_sent:
order.fiscal_status = "pending"
db.commit()
@@ -1028,18 +1042,25 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
if auto_closed:
broadcast_sync("order_closed", {"order_id": order_id, "table_id": order.table_id, "auto_closed": True})
if fiscal_on and items:
if fiscal_on and own:
from database import SessionLocal
fiscal_items = build_fiscal_items(items)
send_fiscal_receipt_background(fiscal_items, effective_method, total_paid, db,
fiscal_items = build_fiscal_items(own)
own_total = sum((i.unit_price + (i.price_adjustment or 0.0)) * i.quantity for i in own)
send_fiscal_receipt_background(fiscal_items, effective_method, own_total, db,
order_id=order_id, db_factory=SessionLocal,
timeout_seconds=60)
if fiscal_on:
from database import SessionLocal
for due in bills_due: # the settled lines as if paid normally, with each method's amount (Q-3)
send_fiscal_receipt_background(build_fiscal_items(due["lines"]), effective_method, due["bill"].total, db,
order_id=order_id, db_factory=SessionLocal, timeout_seconds=60,
payments=due["payments"])
return {
"status": order.status,
"paid_item_ids": paid_ids,
"auto_closed": auto_closed,
"fiscal": "pending" if fiscal_on and items else None,
"fiscal": "pending" if fiscal_sent else None,
}
@@ -1100,6 +1121,8 @@ def close_order(order_id: int, request: Request, db: Session = Depends(get_db),
raise XeniaError("order.not_yours")
if order.status not in ("paid", "open", "partially_paid"):
raise XeniaError("order.cannot_close", status=order.status)
if split_bills.has_unpaid_parts(db, order_id): # 6F.6: never written off: the settled lines were sold
raise XeniaError("split.parts_unpaid")
now = utcnow()
@@ -1256,6 +1279,8 @@ def cancel_order(
if not is_manager and not _waiter_can_cancel(user, db):
# a manager may approve this one cancellation with their PIN (D-10)
approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
if split_bills.has_unpaid_parts(db, order_id): # 6F.6: undo the split first
raise XeniaError("split.parts_unpaid")
now = utcnow()
@@ -1319,11 +1344,12 @@ def cancel_items_bulk(
OrderItem.order_id == order_id,
).all()
split_bills.refuse_parts(items) # 6F.6: undo the split instead
now = utcnow()
cancelled_ids = []
skipped_paid = []
for item in items:
if item.status == "paid":
if item.status not in ("active", "ready"): # paid, on a tab, settled by a split bill (6F.6)
skipped_paid.append(item.id)
continue
item.status = "cancelled"
@@ -1436,6 +1462,8 @@ def print_order(
if item.status == "cancelled":
continue
product_name = item.product.name if item.product else f"#{item.product_id}"
if item.split_bill_id is not None and item.status != "split":
product_name = item.product_name # 6F.6: "Split bill 1/3"
adj = getattr(item, 'price_adjustment', 0.0) or 0.0
effective_price = item.unit_price + adj
items_data.append({
@@ -1447,7 +1475,7 @@ def print_order(
"status": item.status,
})
grand_total = sum(i["total"] for i in items_data)
grand_total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them
receipt = {
"order_id": order.id,
@@ -1552,6 +1580,8 @@ def merge_order(
for item in source.items:
item.order_id = target.id
moved_item_ids.append(item.id)
from models.order import SplitBill # 6F.6: a split bill goes with its lines
db.query(SplitBill).filter(SplitBill.order_id == source.id).update({SplitBill.order_id: target.id}, synchronize_session=False)
# Copy source waiters to target (no duplicates)
existing_waiter_ids = {w.waiter_id for w in target.waiters}
@@ -1589,6 +1619,68 @@ def merge_order(
return target
# ─── Split the bill by amount (6F.6, services/split_bills.py) ─────────────────
class SplitBillRequest(BaseModel):
item_ids: List[int] = Field(min_length=1, max_length=500)
mode: str = "equal" # equal | custom (two parts)
parts: int = Field(default=2, ge=2, le=50)
first_amount: Optional[float] = Field(default=None, gt=0, le=1000000) # custom: part 1, part 2 is the rest
@router.post("/{order_id}/split-bills")
def create_split_bill(order_id: int, body: SplitBillRequest, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""Settle the chosen unpaid lines into a split bill and cut it into parts paid on their own
(equal parts, the remainder on the last; or two parts, part 1 typed). The venue's
payments.split_amount decides which splits exist; the key ordering.payments.split_amount (a
manager may approve it once, D-10) who may. The parts are paid with POST /pay like any line."""
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}")
if not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
if order.status not in ("open", "partially_paid"):
raise XeniaError("order.not_open")
ids = sorted(set(body.item_ids))
items = db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.id.in_(ids)).order_by(OrderItem.id).all()
if len(items) != len(ids):
raise XeniaError("split.lines_changed")
bill = split_bills.create(db, order, items, mode=body.mode, parts=body.parts, first=body.first_amount, user=user)
amounts = json.loads(bill.amounts)
note = f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts)
approved = _approval_note(approval)
_audit(db, order_id, "SPLIT_CREATED", waiter_id=user.id, item_ids=ids, amount=bill.total,
note=f"{note}; {approved}" if approved else note)
db.commit()
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_created"})
db.refresh(order)
return split_bills.bill_out(bill, order.items)
@router.post("/{order_id}/split-bills/{bill_id}/undo")
def undo_split_bill(order_id: int, bill_id: int, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""Undo a split while none of its parts is paid or on a tab (Q-2): the parts are cancelled
("split undone"), the lines are unpaid again. Same key as splitting."""
from models.order import SplitBill
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}")
if not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
bill = db.get(SplitBill, bill_id)
if bill is None:
raise XeniaError("split.not_found")
back = split_bills.undo(db, order, bill, user)
_audit(db, order_id, "SPLIT_UNDONE", waiter_id=user.id, item_ids=back, amount=bill.total, note=_approval_note(approval))
db.commit()
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_undone"})
return {"item_ids": back}
# ─── Split a stacked item into two rows ──────────────────────────────────────
@router.post("/{order_id}/items/{item_id}/split", response_model=List[OrderItemOut])
@@ -1787,6 +1879,7 @@ def adjust_item_price(
raise XeniaError("order.item_not_found")
if item.status != "active":
raise XeniaError("order.item_not_active")
split_bills.refuse_parts([item]) # 6F.6
order = db.query(Order).filter(Order.id == order_id).first()
if not _can_access_order(order, user, db):
@@ -1873,6 +1966,7 @@ def apply_waiter_discount(
).all()
if not items:
raise XeniaError("order.no_active_items", status=404)
split_bills.refuse_parts(items) # 6F.6
item_unit_prices = {i.id: i.unit_price + i.price_adjustment for i in items}
@@ -2100,6 +2194,7 @@ def move_items(
).all()
if not items:
raise XeniaError("order.no_active_items")
split_bills.refuse_parts(items) # 6F.6: a part stays with its bill
from services import moves # 6F.4
moves.record(db, kind="items_moved", source=source, target=target, items=items, user_id=user.id)
@@ -2166,6 +2261,8 @@ def print_synopsis(
if item.status == "cancelled":
continue
product_name = item.product.name if item.product else f"#{item.product_id}"
if item.split_bill_id is not None and item.status != "split":
product_name = item.product_name # 6F.6: "Split bill 1/3"
adj = getattr(item, 'price_adjustment', 0.0) or 0.0
effective_price = item.unit_price + adj
items_data.append({
@@ -2177,7 +2274,7 @@ def print_synopsis(
"status": item.status,
})
total = sum(i["total"] for i in items_data)
total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them
paid_total = sum(i["total"] for i in items_data if i["status"] == "paid")
synopsis = {
@@ -2290,6 +2387,7 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
raise XeniaError("order.items_not_combinable", reason="not_found")
if any(i.status != "active" for i in items):
raise XeniaError("order.items_not_combinable", reason="not_unpaid")
split_bills.refuse_parts(items) # 6F.6
if any(i.deal_id or i.linked_item_id for i in items) or \
db.query(OrderItem).filter(OrderItem.linked_item_id.in_(ids)).first() is not None:
raise XeniaError("order.items_not_combinable", reason="deal")
+68 -5
View File
@@ -141,10 +141,12 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi
by_point = {sp: pos_cart.unit_prices(db, products, sp) for sp in sales_points.IN_PERSON}
default = pos_cart.point_for(settings["default_order_type"])
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
from services import price_changes
from services import price_changes, split_bills
return {
# + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount
"settings": {**settings, "price_change": price_changes.mode(db)},
"settings": {**settings, "price_change": price_changes.mode(db),
# 6F.6: splitting a bill by amount (the level and the most equal parts)
"split_amount": split_bills.level(db), "split_max_parts": split_bills.max_parts(db)},
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
for c in cats],
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON})
@@ -180,14 +182,25 @@ class Payment(BaseModel):
lines: Optional[List[int]] = None # indexes into `lines`; None = all of them
class SaleSplit(BaseModel):
"""A quick sale split by amount (6F.6, Q-4): the parts and how each is paid, all now."""
mode: Literal["equal", "custom"] = "equal"
parts: int = Field(default=2, ge=2, le=50)
first_amount: Optional[float] = Field(default=None, gt=0, le=1000000)
methods: List[Literal["cash", "card"]] = Field(min_length=2, max_length=50) # one per part
class SaleBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(min_length=1, max_length=200)
payments: List[Payment] = Field(min_length=1, max_length=2)
payments: List[Payment] = Field(default_factory=list, max_length=2) # without `split`: at least one
split: Optional[SaleSplit] = None
cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
def _payment_groups(body: SaleBody, n: int) -> list:
if not body.payments:
raise XeniaError("pos.payment_invalid", reason="lines")
if len(body.payments) == 1 and body.payments[0].lines is None:
return [(body.payments[0].method, list(range(n)))]
seen = [i for pay in body.payments for i in (pay.lines or [])]
@@ -211,12 +224,14 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
_require_shift(db, user)
orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
groups = _payment_groups(body, len(lines))
groups = _payment_groups(body, len(lines)) if body.split is None else []
approved_by = _check_discounts(request, db, user, lines)
_check_fiscal(db, {line.product for line in lines})
priced = pos_cart.price_lines(db, lines, body.order_type)
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)]
if body.split is not None:
return _split_sale(body, request, db, user, lines, adjs, approved_by, totals)
cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2)
_check_cash(body.cash_given, cash_due)
@@ -239,6 +254,53 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
}
def _split_sale(body, request, db, user, lines, adjs, approved_by, totals):
"""A quick sale split by amount (6F.6, Q-4): the order and its lines as any quick sale, then
the lines settled into a split bill and each part paid now by its own method (one payment per
method). The fiscal receipt is the lines themselves, issued with the last part (Q-3)."""
from models.order import OrderItem
from routers import orders as orders_api
from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest
from services import split_bills
sp = body.split
orders_api._need(request, db, user, "ordering.payments.split_amount", target="pos sale")
if len(sp.methods) != sp.parts:
raise XeniaError("pos.payment_invalid", reason="lines")
if not split_bills.allowed(split_bills.level(db), sp.mode, sp.parts, split_bills.max_parts(db)):
raise XeniaError("split.not_allowed")
total = round(sum(totals), 2)
if total < 0.01 * sp.parts:
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
amounts = split_bills.amounts(total, sp.mode, sp.parts, sp.first_amount)
cash_due = round(sum(a for a, m in zip(amounts, sp.methods) if m == "cash"), 2)
_check_cash(body.cash_given, cash_due)
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
items = db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()
bill = split_bills.create(db, order, items, mode=sp.mode, parts=sp.parts, first=sp.first_amount, user=user)
orders_api._audit(db, order.id, "SPLIT_CREATED", waiter_id=user.id, item_ids=[i.id for i in items], amount=bill.total,
note=f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts))
db.commit()
parts = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id, OrderItem.status == "active").order_by(OrderItem.id).all()
paid, fiscal = [], None
for method in ("cash", "card"):
ids = [p.id for p, m in zip(parts, sp.methods) if m == method]
if not ids:
continue
res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=ids, payment_method=method), request, db, user)
paid.append({"method": method, "amount": round(sum(a for a, m in zip(amounts, sp.methods) if m == method), 2),
"item_ids": res["paid_item_ids"]})
fiscal = res.get("fiscal") or fiscal
drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none"
change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None
return {
"order_id": order.id, "total": total, "payments": paid, "split": {"id": bill.id, "amounts": amounts, "methods": sp.methods},
"cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal,
"print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []),
}
# ── shared checks (3.3b, 3.3c) ─────────────────────────────────────────────────
def _require_shift(db, user):
@@ -458,7 +520,8 @@ def pos_order_pay(order_id: int, body: OrderPayBody, request: Request, db: Sessi
items = {i.id: i for i in db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.id.in_(wanted)).all()}
if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()):
raise XeniaError("pos.items_changed")
_check_fiscal(db, {i.product for i in items.values()})
from services.split_bills import is_part
_check_fiscal(db, {i.product for i in items.values() if not is_part(i)}) # 6F.6: the settled lines were checked
amount = {pay.method: round(sum(_item_total(items[i]) for i in pay.item_ids), 2) for pay in body.payments}
cash_due = amount.get("cash", 0.0)
_check_cash(body.cash_given, cash_due)
+13 -13
View File
@@ -2,7 +2,7 @@ from core.access.queries import holders_filter
from core.errors import XeniaError
from core.modules.entitlements import clamp_start, history_floor, history_since, limit
from core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow
from services import tab_books
from services import split_bills, tab_books # split_bills: 6F.6, settled lines count, parts never
import csv
import io
import json
@@ -164,7 +164,7 @@ def shift_orders_summary(
user: User = Depends(require_reports),
):
"""Items sent (added) per waiter — regardless of payment status."""
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
start = end = None # 6.12a: with a business day there is no window (was a crash)
if business_day_id:
q = q.join(Order).filter(Order.business_day_id == business_day_id)
@@ -496,7 +496,7 @@ def printer_totals(
item_ids = []
for item_id in item_ids:
item = db.query(OrderItem).filter(OrderItem.id == item_id).first()
if item and item.status in ("active", "paid"):
if item and split_bills.counts_as_sale(item):
summary[pid]["items"] += item.quantity
val = _item_val(item)
summary[pid]["total"] += val
@@ -565,7 +565,7 @@ def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, m
item_ids = []
for item_id in item_ids:
item = db.query(OrderItem).filter(OrderItem.id == item_id).first()
if item and item.status in ("active", "paid"):
if item and split_bills.counts_as_sale(item):
items_count += item.quantity
val = _item_val(item)
grand_total += val
@@ -633,7 +633,7 @@ def print_waiter(
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
order_data = []
for o in orders:
active_items = [i for i in o.items if i.status in ("active", "paid")]
active_items = [i for i in o.items if split_bills.counts_as_sale(i)]
total = sum(_item_val(i) for i in active_items)
order_data.append({
"id": o.id,
@@ -648,7 +648,7 @@ def print_waiter(
})
items_count = sum(
i.quantity for o in orders for i in o.items if i.status in ("active", "paid")
i.quantity for o in orders for i in o.items if split_bills.counts_as_sale(i)
)
grand_total = sum(d["total"] for d in order_data)
@@ -778,7 +778,7 @@ def print_products(
period_label, period_is_workday = _analytics_period(body, db)
# Build sold-item summary
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
if body.business_day_id:
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
elif body.from_dt and body.to_dt:
@@ -837,7 +837,7 @@ def print_categories(
period_label, period_is_workday = _analytics_period(body, db)
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
if body.business_day_id:
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
elif body.from_dt and body.to_dt:
@@ -974,7 +974,7 @@ def product_performance(
from models.product import Product
from models.waste import WasteLog
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
_since = history_since(from_dt, 'reports')
if _since:
q = q.filter(OrderItem.added_at >= _since)
@@ -1337,7 +1337,7 @@ def category_performance(
):
from models.product import Product, Category
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
_since = history_since(from_dt, 'reports')
if _since:
q = q.filter(OrderItem.added_at >= _since)
@@ -1504,7 +1504,7 @@ def printer_history(
order_total = sum(
_item_val(i)
for i in order.items
if i.status in ("active", "paid")
if split_bills.counts_as_sale(i)
)
if log.success and log.order_id not in seen_order_totals:
seen_order_totals[log.order_id] = order_total
@@ -1713,7 +1713,7 @@ def prep_zones_report(
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
if business_day_id:
q = q.filter(Order.business_day_id == business_day_id)
q = q.filter(OrderItem.status.in_(["active", "paid"]))
q = q.filter(split_bills.sold_filter())
items = q.all()
# Aggregate per zone
@@ -1839,7 +1839,7 @@ def print_prep_zone(
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
if body.business_day_id:
q = q.filter(Order.business_day_id == body.business_day_id)
q = q.filter(OrderItem.status.in_(["active", "paid"]))
q = q.filter(split_bills.sold_filter())
items = q.all()
product_counts: dict[str, dict] = {}
+2 -1
View File
@@ -43,7 +43,8 @@ def card(db, customer) -> dict:
from models.table import Table
orders = db.query(Order).filter(Order.customer_id == customer.id).order_by(Order.opened_at.desc()).all()
done = [o for o in orders if o.status in ("closed", "paid")]
live = lambda o: [i for i in o.items if i.status in ("active", "paid")] # noqa: E731
from services.split_bills import counts_as_sale
live = lambda o: [i for i in o.items if counts_as_sale(i)] # noqa: E731 (6F.6: settled lines, not parts)
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
return {
"id": customer.id, "name": customer.name, "nickname": customer.nickname, "phone": customer.phone,
+5 -4
View File
@@ -125,13 +125,14 @@ def _in_background(db_factory, model, row_id: int, prepare, timeout_seconds: int
def send_fiscal_receipt_background(items: list[dict], payment_method: str, total: float, db, order_id: int,
db_factory, timeout_seconds: int = 60) -> None:
db_factory, timeout_seconds: int = 60, payments: list[dict] | None = None) -> None:
"""Issue the receipt through the venue's driver in a background thread; order.fiscal_status
becomes success or failed when the device answers (or the wait times out)."""
becomes success or failed when the device answers (or the wait times out). `payments`
[{"method", "amount"}]: a receipt paid in several ways (a split bill's parts, 6F.6)."""
from models.order import Order
driver = driver_for(db)
_in_background(db_factory, Order, order_id, lambda: driver.prepare_receipt(db, items, payment_method, total),
timeout_seconds)
_in_background(db_factory, Order, order_id,
lambda: driver.prepare_receipt(db, items, payment_method, total, payments=payments), timeout_seconds)
def send_credit_note_background(items: list[dict], method: str, total: float, db, refund_id: int, original: dict,
+3 -2
View File
@@ -28,8 +28,9 @@ class FiscalDriver:
# cashier is told to issue the credit note on the machine itself (owner decision 2026-11-15).
credit_notes: bool = False
def prepare_receipt(self, db, items: list[dict], method: str, total: float) -> Send:
"""A sales receipt, ready to send."""
def prepare_receipt(self, db, items: list[dict], method: str, total: float, payments: list[dict] | None = None) -> Send:
"""A sales receipt, ready to send. `payments` [{"method", "amount"}] when it was paid in
several ways (a split bill, 6F.6); else all of it by `method`."""
raise NotImplementedError
def prepare_credit_note(self, db, items: list[dict], method: str, total: float, original: dict | None = None) -> Send:
+12 -4
View File
@@ -62,7 +62,7 @@ def _get_folders(db) -> tuple[str, str]:
return out_folder, in_folder
def _build_command_file(items: list[dict], payment_method: str, total: float, db) -> str:
def _build_command_file(items: list[dict], payment_method: str, total: float, db, payments: list[dict] | None = None) -> str:
"""
Build the fiscal command file content as a string.
@@ -98,7 +98,15 @@ def _build_command_file(items: list[dict], payment_method: str, total: float, db
if msg_line.strip():
lines.append(f"FM|{i}|{msg_line.upper()}")
if payment_method == "card":
if payments and len(payments) > 1:
# Paid in several ways (a split bill, 6F.6; the driver manual's "multiple ways to close"):
# each card amount through the EFT/POS first, then cash closes the rest.
card = [p for p in payments if p.get("method") == "card" and p.get("amount", 0) > 0]
for p in card:
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{p['amount']:.2f}")
if round(sum(p.get("amount", 0) for p in payments if p not in card), 2) > 0:
lines.append(f"CR|{clerk_id}")
elif (payments[0].get("method") if payments else payment_method) == "card":
total_str = f"{total:.2f}"
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{total_str}")
else:
@@ -177,11 +185,11 @@ class TxtFileDriver(FiscalDriver):
name = "dTEC100extra (text-file bridge)"
credit_notes = False
def prepare_receipt(self, db, items, method, total):
def prepare_receipt(self, db, items, method, total, payments=None):
out_folder, in_folder = _get_folders(db)
os.makedirs(out_folder, exist_ok=True)
os.makedirs(in_folder, exist_ok=True)
content = _build_command_file(items, method, total, db)
content = _build_command_file(items, method, total, db, payments)
filename = _unique_filename()
return lambda timeout_seconds: _write_and_poll(out_folder, in_folder, content, filename, timeout_seconds)
+30 -3
View File
@@ -7,6 +7,10 @@ in every report, on screen, printed and exported.
- A line's **value** = (unit price + its price change) × quantity, then **minus what was refunded**
of it (services/refunds.py: refunds are per line and quantity, so they come off the line, the
product, the category, the table, the hour and the day they belong to).
- **A split bill** (6F.6, services/split_bills.py): the lines it settled (`split`) are sold like
paid lines; its **part lines** are the money for them, never a sale (left out here; the shifts'
drawers, payment methods and tabs count them). A refund of a part comes off the settled lines
by their share of the bill.
- **Fees** (lines the system adds, `system_key` set: the delivery fee) are counted apart: they are
money taken, but not a product sold. `revenue` everywhere is products only; `fees` is beside it;
`takings` = revenue + fees.
@@ -17,7 +21,7 @@ from __future__ import annotations
from dataclasses import dataclass
SOLD = ("active", "paid", "tabbed")
SOLD = ("active", "paid", "tabbed", "split")
def gross(item, quantity: float | None = None) -> float:
@@ -58,17 +62,40 @@ def lines(db, items) -> list[Line]:
"""Sold lines (see the module doc) with their refunds taken off. A line refunded in full
stays (quantity 0, value 0) so its refund is counted; `sold()` leaves it out of lists."""
from services.refunds import refunded_quantities
sold = [i for i in items if i.status in SOLD]
from services.split_bills import is_part
sold = [i for i in items if i.status in SOLD and not is_part(i)]
back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"])
shares = _split_refunds(db, {i.split_bill_id for i in sold if i.status == "split"})
fees = _fee_products(db) if sold else set()
out = []
for i in sold:
r = min(back.get(i.id, 0.0), i.quantity)
if i.status == "split":
r = i.quantity * shares.get(i.split_bill_id, 0.0)
else:
r = min(back.get(i.id, 0.0), i.quantity)
q = max(i.quantity - r, 0.0)
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=i.product_id in fees))
return out
def _split_refunds(db, bill_ids) -> dict[int, float]:
"""{split_bill_id: the share of the bill refunded} from its parts' refunds (6F.6)."""
from models.order import OrderItem, SplitBill
from services.refunds import refunded_quantities
ids = {b for b in bill_ids if b is not None}
if not ids:
return {}
parts = db.query(OrderItem).filter(OrderItem.split_bill_id.in_(ids), OrderItem.status == "paid").all()
back = refunded_quantities(db, [p.id for p in parts])
if not back:
return {}
totals = {b.id: b.total for b in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all()}
value: dict[int, float] = {}
for p in parts:
value[p.split_bill_id] = value.get(p.split_bill_id, 0.0) + gross(p, min(back.get(p.id, 0.0), p.quantity))
return {b: min(v / totals[b], 1.0) for b, v in value.items() if totals.get(b)}
@dataclass
class Totals:
revenue: float = 0.0 # products, net of refunds
+228
View File
@@ -0,0 +1,228 @@
"""Split a bill by amount (owner 2026-11-23, plan 6F.6). One rule for every app:
- The chosen unpaid lines are **settled** at once into a split bill: status `split` (sold, settled by
the bill; `paid_at` / `paid_by` say when and who split, no shift, no payment method), so no
drawer, payment method or person is charged for them.
- `parts` **part lines** appear on the order: the system product `split_part`, named "Split bill
1/3", one each, already printed and served (the kitchen never sees them). They are paid like any
line (cash, card, on a tab, at different times, by different people): they are the money.
- Counting (services/sales.py): the settled lines are the sales (products, categories, costs);
parts are settlement lines, never sales, but money taken (shifts' drawers, payment methods,
tabs, the day's takings), so nothing is counted twice. A refund of a part comes off the settled
lines by their share.
- Locks: settled lines are no longer `active`, so cancelling, moving, combining, re-pricing and
splitting them is refused everywhere; parts can't be moved, re-priced, combined or cancelled one
by one (undo the split instead).
- Undo while no part is paid or on a tab (Q-2): parts cancelled ("split undone"), lines back to
unpaid. Refused once any payment was taken.
- Fiscal (Greece, Q-3): a split is whole lines, so the receipt is the settled lines themselves, as
if paid normally: issued once, when the **last part is paid**, with each method's amount as the
receipt's payments (`receipts_due`). A part on a tab: no receipt from the split (like any line
on a tab) — open point for the accountant (plan 6F.6).
Venue setting `payments.split_amount` (levels include the ones before, Q-1): off | two_equal |
two_custom | multiple_equal (2…`payments.split_max_parts` equal parts). Key
`ordering.payments.split_amount`.
"""
from __future__ import annotations
import json
from core.errors import XeniaError
LEVELS = ("off", "two_equal", "two_custom", "multiple_equal")
PART_KEY = "split_part"
def _setting(db, key: str, default: str) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row is not None and row.value not in (None, "") else default
def level(db) -> str:
v = _setting(db, "payments.split_amount", "off")
return v if v in LEVELS else "off"
def max_parts(db) -> int:
try:
n = int(_setting(db, "payments.split_max_parts", "10"))
except ValueError:
n = 10
return max(2, min(50, n))
def allowed(lvl: str, mode: str, parts: int, most: int) -> bool:
"""Whether the venue's level allows this split (each level includes the ones before)."""
rank = LEVELS.index(lvl) if lvl in LEVELS else 0
if mode == "custom":
return parts == 2 and rank >= LEVELS.index("two_custom")
if parts == 2:
return rank >= LEVELS.index("two_equal")
return rank >= LEVELS.index("multiple_equal") and 2 < parts <= most
def amounts(total: float, mode: str, parts: int, first: float | None = None) -> list[float]:
"""Each part, to the cent. Equal: the remainder goes on the last part (10.00 / 3 = 3.33 + 3.33
+ 3.34). Custom (two parts): `first` is part 1, part 2 the rest."""
cents = round(total * 100)
if mode == "custom":
a = round((first or 0) * 100)
if not 0 < a < cents:
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
return [a / 100, (cents - a) / 100]
base = cents // parts
return [base / 100] * (parts - 1) + [(cents - base * (parts - 1)) / 100]
def is_part(item) -> bool:
"""A split bill's part line (money for the settled lines), not a sale."""
return getattr(item, "split_bill_id", None) is not None and item.status != "split"
def counts_as_sale(item, statuses=("active", "paid")) -> bool:
"""For the older reports that pick lines by status: a settled line counts, a part never."""
return item.status == "split" or (item.status in statuses and not is_part(item))
def sold_filter(statuses=("active", "paid")):
"""The same as SQL (OrderItem): settled lines, or lines in `statuses` that aren't parts."""
from sqlalchemy import and_, or_
from models.order import OrderItem
return or_(OrderItem.status == "split", and_(OrderItem.status.in_(statuses), OrderItem.split_bill_id.is_(None)))
def refuse_parts(items) -> None:
if any(is_part(i) for i in items):
raise XeniaError("split.part_locked")
def live_bills(db, order_id: int) -> list:
from models.order import SplitBill
return db.query(SplitBill).filter(SplitBill.order_id == order_id, SplitBill.undone_at.is_(None)).order_by(SplitBill.id).all()
def has_unpaid_parts(db, order_id: int) -> bool:
from models.order import OrderItem
return db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.split_bill_id.isnot(None),
OrderItem.status.in_(("active", "ready"))).first() is not None
def create(db, order, items, *, mode: str, parts: int, first: float | None, user) -> object:
"""Settle `items` (unpaid lines of `order`) into a split bill with `parts` part lines.
The caller checked the key; this checks the venue's level, the lines and fiscal."""
from core.i18n import t, venue_language
from core.timeutil import utcnow
from models.order import OrderItem, SplitBill
from services import system_products
from services.sales import gross
if mode not in ("equal", "custom"):
raise XeniaError("validation.choice", field="mode", value=mode)
if not allowed(level(db), mode, parts, max_parts(db)):
raise XeniaError("split.not_allowed")
if not items or any(i.order_id != order.id or i.status not in ("active", "ready") for i in items):
raise XeniaError("split.lines_changed")
refuse_parts(items)
total = round(sum(gross(i) for i in items), 2)
if total < 0.01 * parts:
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
split = amounts(total, mode, parts, first)
from services.fiscal import is_fiscal_enabled, validate_items_for_fiscal
if is_fiscal_enabled(db):
missing = validate_items_for_fiscal(items, db)
if missing:
raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
now = utcnow()
bill = SplitBill(order_id=order.id, total=total, mode=mode, parts=parts, amounts=json.dumps(split),
created_by=user.id, created_at=now, business_day_id=order.business_day_id)
db.add(bill)
db.flush()
for i in items:
i.status = "split"
i.split_bill_id = bill.id
i.paid_at = now
i.paid_by = user.id
i.payment_method = None
i.paid_in_shift_id = None
product = system_products.get(db, PART_KEY)
lang = venue_language()
for n, amount in enumerate(split, start=1):
db.add(OrderItem(order_id=order.id, product_id=product.id, added_by=user.id, quantity=1, unit_price=amount,
price_adjustment=0.0, status="active", printed=True, kds_status="served", split_bill_id=bill.id,
product_name=t("split.part_name", lang, n=n, of=parts), source=items[0].source))
db.flush()
return bill
def undo(db, order, bill, user) -> list[int]:
"""Undo a split while no part was paid or put on a tab (Q-2). Returns the lines given back."""
from core.timeutil import utcnow
from models.order import OrderItem
if bill.undone_at is not None or bill.order_id != order.id:
raise XeniaError("split.not_found")
rows = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id).all()
parts = [i for i in rows if i.status != "split"]
if any(p.status not in ("active", "ready", "cancelled") for p in parts):
raise XeniaError("split.paid_already")
now = utcnow()
for p in parts:
if p.status != "cancelled":
p.status = "cancelled"
p.cancelled_at = now
p.cancelled_by = user.id
p.cancel_reason = "split undone"
back = []
for i in rows:
if i.status == "split":
i.status = "active"
i.split_bill_id = None
i.paid_at = None
i.paid_by = None
back.append(i.id)
bill.undone_at = now
bill.undone_by = user.id
db.flush()
return back
def receipts_due(db, paid_items) -> list[dict]:
"""After parts were paid: the split bills whose last part is now paid get their fiscal receipt
(marked issued here). [{"bill", "lines", "payments": [{"method", "amount"}]}]."""
from core.timeutil import utcnow
from models.order import OrderItem, SplitBill
ids = {i.split_bill_id for i in paid_items if is_part(i)}
out = []
for bill in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all() if ids else []:
if bill.undone_at is not None or bill.receipt_issued_at is not None:
continue
rows = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id).order_by(OrderItem.id).all()
parts = [i for i in rows if i.status not in ("split", "cancelled")]
if not parts or any(p.status != "paid" for p in parts):
continue # unpaid, or on a tab: no receipt from the split (open point, plan 6F.6)
by_method: dict[str, float] = {}
for p in parts:
m = p.payment_method or "cash"
by_method[m] = round(by_method.get(m, 0.0) + (p.unit_price or 0.0) * p.quantity, 2)
bill.receipt_issued_at = utcnow()
out.append({"bill": bill, "lines": [i for i in rows if i.status == "split"],
"payments": [{"method": m, "amount": a} for m, a in by_method.items()]})
return out
def bill_out(bill, rows) -> dict:
"""What the apps show: the bill, its settled lines and its parts (with how each was paid)."""
parts = [i for i in rows if i.split_bill_id == bill.id and i.status != "split" and i.status != "cancelled"]
return {
"id": bill.id, "total": bill.total, "mode": bill.mode, "parts": bill.parts,
"amounts": json.loads(bill.amounts or "[]"),
"created_by": bill.created_by,
"created_at": bill.created_at.isoformat() + "Z" if bill.created_at and bill.created_at.tzinfo is None else (bill.created_at.isoformat() if bill.created_at else None),
"line_ids": [i.id for i in rows if i.split_bill_id == bill.id and i.status == "split"],
"part_ids": [p.id for p in parts],
"paid": round(sum((p.unit_price or 0.0) * p.quantity for p in parts if p.status == "paid"), 2),
"can_undo": all(p.status in ("active", "ready") for p in parts),
"receipt_issued": bill.receipt_issued_at is not None,
}
+2 -1
View File
@@ -21,7 +21,8 @@ from __future__ import annotations
from collections import Counter
DELIVERY_FEE = "delivery_fee"
KEYS = (DELIVERY_FEE,)
SPLIT_PART = "split_part" # a split bill's part line (6F.6, services/split_bills.py)
KEYS = (DELIVERY_FEE, SPLIT_PART)
def _usual_vat_group(db):
+1 -1
View File
@@ -189,7 +189,7 @@ def test_fiscal_driver_with_credit_notes_issues_one(client, db, till, menu, on_s
class Machine(FiscalDriver):
key, credit_notes = "test_machine", True
def prepare_receipt(self, db, items, method, total):
def prepare_receipt(self, db, items, method, total, payments=None):
return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
def prepare_credit_note(self, db, items, method, total, original=None):
+237
View File
@@ -0,0 +1,237 @@
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
- POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status split) and adds part
lines (the system product split_part), paid like any line; the venue's level and the key decide.
- Undo while no part is paid; parts can't be cancelled, moved or re-priced on their own.
- Counting: the settled lines are the sales, the parts are the money (drawers), never both.
- Fiscal: one receipt with the settled lines, when the last part is paid, with each method's amount.
- The counter: a quick sale split and paid at once (Q-4).
"""
import json
import pytest
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import burger_line, drawer_printer, menu, on_shift, sale, till # noqa: F401 (fixtures)
from tests.test_pos_refunds import fiscal_on, refund, shift_of, wait_for
def setting(db, key, value):
from models.settings import PosSettings
row = db.get(PosSettings, key)
if row is None:
db.add(PosSettings(key=key, value=value))
else:
row.value = value
db.commit()
@pytest.fixture
def table_order(db, till, menu, on_shift):
"""The cashier's order with a 10.00 burger and a 5.00 (two coffees at 2.50), nothing paid."""
from models.order import Order, OrderItem, OrderWaiter
o = Order(opened_by=till["cashier"].id, order_type="here", status="open", business_day_id=on_shift.business_day_id)
db.add(o)
db.flush()
db.add(OrderWaiter(order_id=o.id, waiter_id=till["cashier"].id))
items = [OrderItem(order_id=o.id, product_id=menu["burger"].id, added_by=till["cashier"].id, quantity=1, unit_price=10.0,
printed=True, kds_status="preparing", unit_cost=3.5),
OrderItem(order_id=o.id, product_id=menu["coffee"].id, added_by=till["cashier"].id, quantity=2, unit_price=2.5,
printed=True)]
db.add_all(items)
db.commit()
return {"order": o, "items": items}
def split(client, till, order_id, ids, **body):
return client.post(f"/api/orders/{order_id}/split-bills", headers=till["h"], json={"item_ids": ids, **body})
def rows(db, order_id):
from models.order import OrderItem
db.expire_all()
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
def pay(client, till, order_id, method, ids):
return client.post(f"/api/pos/orders/{order_id}/pay", headers=till["h"], json={"payments": [{"method": method, "item_ids": ids}]})
def test_amounts_and_levels():
from services.split_bills import allowed, amounts
assert amounts(10.0, "equal", 3) == [3.33, 3.33, 3.34]
assert amounts(15.0, "equal", 2) == [7.5, 7.5]
assert amounts(15.0, "custom", 2, 4.5) == [4.5, 10.5]
assert sum(amounts(17.21, "equal", 7)) == pytest.approx(17.21)
# each level includes the ones before; multiple ways are equal parts only (Q-1)
assert not allowed("off", "equal", 2, 10)
assert allowed("two_equal", "equal", 2, 10) and not allowed("two_equal", "custom", 2, 10)
assert allowed("two_custom", "custom", 2, 10) and not allowed("two_custom", "equal", 3, 10)
assert allowed("multiple_equal", "equal", 10, 10) and not allowed("multiple_equal", "equal", 11, 10)
assert allowed("multiple_equal", "custom", 2, 10) and not allowed("multiple_equal", "custom", 3, 10)
def test_split_30_70_paid_cash_and_card(client, db, till, table_order):
"""10 + 5 into 4.50 + 10.50: the lines settled, two parts paid apart; the drawer counts the
parts, the sales count the lines, never both."""
from services import sales
o, items = table_order["order"], table_order["items"]
ids = [i.id for i in items]
assert err(split(client, till, o.id, ids, mode="custom", first_amount=4.5)) == "split.not_allowed" # off by default
setting(db, "payments.split_amount", "two_custom")
r = split(client, till, o.id, ids, mode="custom", first_amount=4.5)
assert r.status_code == 200, r.text
bill = r.json()
assert (bill["total"], bill["amounts"], bill["parts"], bill["can_undo"]) == (15.0, [4.5, 10.5], 2, True)
lines = rows(db, o.id)
settled = [i for i in lines if i.status == "split"]
parts = [i for i in lines if i.split_bill_id and i.status != "split"]
assert {i.id for i in settled} == set(ids) and all(i.paid_in_shift_id is None and i.payment_method is None for i in settled)
assert [(p.product_name, p.unit_price, p.status, p.printed, p.kds_status) for p in parts] == [
("Split bill 1/2", 4.5, "active", True, "served"), ("Split bill 2/2", 10.5, "active", True, "served")]
assert parts[0].product.system_key == "split_part"
# the settled burger is still cooking: the kitchen state is untouched
assert next(i for i in settled if i.unit_price == 10.0).kds_status == "preparing"
got = client.get(f"/api/orders/{o.id}", headers=till["h"]).json()
assert got["split_bills"][0]["part_ids"] == [p.id for p in parts]
assert pay(client, till, o.id, "cash", [parts[0].id]).status_code == 200
# undo refused once a part is paid (Q-2)
assert err(client.post(f"/api/orders/{o.id}/split-bills/{bill['id']}/undo", headers=till["h"])) == "split.paid_already"
r = pay(client, till, o.id, "card", [parts[1].id])
assert r.status_code == 200 and r.json()["status"] in ("paid", "closed"), r.text
s = shift_of(client, till)
assert (s["cash_sales"], s["card_sales"]) == (4.5, 10.5)
money = sales.totals(sales.lines(db, rows(db, o.id))).out()
assert (money["revenue"], money["fees"], money["takings"], money["total_cost"]) == (15.0, 0.0, 15.0, 3.5)
assert {p["product_name"] for p in sales.products(db, rows(db, o.id)).values()} == {"Burger", "Freddo"}
def test_equal_parts_levels_and_the_key(client, db, till, table_order, login, make_user):
o, items = table_order["order"], table_order["items"]
ids = [i.id for i in items]
setting(db, "payments.split_amount", "two_equal")
assert err(split(client, till, o.id, ids, parts=3)) == "split.not_allowed"
assert err(split(client, till, o.id, ids, mode="custom", first_amount=5)) == "split.not_allowed"
setting(db, "payments.split_amount", "multiple_equal")
setting(db, "payments.split_max_parts", "4")
assert err(split(client, till, o.id, ids, parts=5)) == "split.not_allowed"
# the key: someone without it is refused (a manager could approve it, D-10)
from models.user import WaiterZone
w = make_user(role="waiter", remove=("ordering.payments.split_amount",))
db.add(WaiterZone(waiter_id=w.id, group_id=None))
db.commit()
r = client.post(f"/api/orders/{o.id}/split-bills", headers=login(w, client="waiter"), json={"item_ids": ids, "parts": 3})
assert err(r) in ("access.denied", "access.override_possible")
r = split(client, till, o.id, ids, parts=4)
assert r.status_code == 200 and r.json()["amounts"] == [3.75, 3.75, 3.75, 3.75]
# the same lines can't be split twice
assert err(split(client, till, o.id, ids, parts=2)) == "split.lines_changed"
def test_locks_close_and_undo(client, db, till, table_order):
from models.order import OrderAuditLog
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "multiple_equal")
bill = split(client, till, o.id, [i.id for i in items], parts=3).json()
assert bill["amounts"] == [5.0, 5.0, 5.0]
part = bill["part_ids"][0]
h = till["h"]
assert err(client.delete(f"/api/orders/{o.id}/items/{part}", headers=h)) in ("split.part_locked", "access.override_possible")
assert err(client.patch(f"/api/orders/{o.id}/items/{part}/price-adjust", headers=h, json={"price_adjustment": -1})) == "split.part_locked"
assert err(client.post(f"/api/orders/{o.id}/items/combine", headers=h, json={"item_ids": bill["part_ids"][:2]})) == "split.part_locked"
assert err(client.patch(f"/api/orders/{o.id}/items/{items[0].id}/price-adjust", headers=h, json={"price_adjustment": -1})) == "order.item_not_active"
setting(db, "orders.close_with_unpaid", "true")
assert err(client.post(f"/api/orders/{o.id}/close", headers=h)) == "split.parts_unpaid" # never written off
# undo: the parts cancelled, the lines unpaid again
r = client.post(f"/api/orders/{o.id}/split-bills/{bill['id']}/undo", headers=h)
assert r.status_code == 200, r.text
lines = rows(db, o.id)
assert [i.status for i in lines if i.id in (items[0].id, items[1].id)] == ["active", "active"]
assert all(i.split_bill_id is None and i.paid_at is None for i in lines if i.id in (items[0].id, items[1].id))
assert [(i.status, i.cancel_reason) for i in lines if i.id in bill["part_ids"]] == [("cancelled", "split undone")] * 3
assert client.get(f"/api/orders/{o.id}", headers=h).json()["split_bills"] == []
events = [a.event_type for a in db.query(OrderAuditLog).filter(OrderAuditLog.order_id == o.id).order_by(OrderAuditLog.id)]
assert events[-2:] == ["SPLIT_CREATED", "SPLIT_UNDONE"]
def test_the_fiscal_receipt_is_the_lines_when_the_last_part_is_paid(client, db, till, menu, table_order, tmp_path, monkeypatch):
from services import fiscal
from services.fiscal.base import FiscalDriver
issued = []
class Machine(FiscalDriver):
key = "test_machine"
def prepare_receipt(self, db, items, method, total, payments=None):
issued.append((items, method, total, payments))
return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
monkeypatch.setitem(fiscal.DRIVERS, "test_machine", Machine())
monkeypatch.setattr(fiscal, "_set_status", lambda *a: None)
fiscal_on(db, tmp_path)
setting(db, "fiscal.type", "test_machine")
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "two_custom")
assert err(split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5)) == "pos.fiscal_vat_missing"
menu["burger"].fiscal_vat_group_id = 1
menu["coffee"].fiscal_vat_group_id = 2
db.commit()
bill = split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5).json()
r = pay(client, till, o.id, "cash", [bill["part_ids"][0]])
assert r.status_code == 200 and r.json()["fiscal"] is None and issued == [] # part 1: no receipt yet
r = pay(client, till, o.id, "card", [bill["part_ids"][1]])
assert r.status_code == 200 and r.json()["fiscal"] == "pending"
assert wait_for(lambda: issued)
lines, _method, total, payments = issued[0]
assert sorted((x["name"], x["qty"], x["unit_price"], x["vat_group_id"]) for x in lines) == [("Burger", 1, 10.0, 1), ("Freddo", 2, 2.5, 2)]
assert total == 15.0 and sorted((p["method"], p["amount"]) for p in payments) == [("card", 10.5), ("cash", 4.5)]
assert sum(x["qty"] * x["unit_price"] for x in lines) == pytest.approx(sum(p["amount"] for p in payments))
assert len(issued) == 1
def test_the_text_file_closes_with_card_then_cash(db, tmp_path):
from services.fiscal.txt_file import _build_command_file
fiscal_on(db, tmp_path)
out = _build_command_file([{"name": "Burger", "qty": 1, "unit_price": 10.0, "vat_group_id": 1}], "cash", 10.0, db,
payments=[{"method": "cash", "amount": 4.5}, {"method": "card", "amount": 5.5}])
assert out.split("\r\n")[-3:] == ["CD|2|1|1|5.50", "CR|2", ""]
out = _build_command_file([{"name": "Burger", "qty": 1, "unit_price": 10.0, "vat_group_id": 1}], "cash", 10.0, db,
payments=[{"method": "card", "amount": 10.0}])
assert out.split("\r\n")[-2:] == ["CD|2|1|1|10.00", ""]
def test_a_refunded_part_comes_off_the_settled_lines(client, db, till, table_order, drawer_printer):
from services import sales
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "two_custom")
bill = split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5).json()
assert pay(client, till, o.id, "cash", bill["part_ids"]).status_code == 200
r = refund(client, till, o.id, [{"item_id": bill["part_ids"][0], "quantity": 1}], reason="Overcharged")
assert r.status_code == 201, r.text
money = sales.totals(sales.lines(db, rows(db, o.id))).out()
assert (money["revenue"], money["refunded"]) == (10.5, 4.5)
assert shift_of(client, till)["cash_refunds"] == 4.5
def test_a_quick_sale_split_and_paid_at_once(client, db, till, menu, on_shift, drawer_printer):
"""Q-4: the counter splits a quick sale into equal parts, each paid its own way now."""
from models.order import Order
setting(db, "payments.split_amount", "multiple_equal")
lines = [{"product_id": menu["coffee"].id, "quantity": 3}, burger_line(menu)]
r = sale(client, till, lines, [], split={"mode": "equal", "parts": 3, "methods": ["cash", "card", "cash"]}, cash_given=20)
assert r.status_code == 201, r.text
body = r.json()
assert body["total"] == 19.0 and body["split"]["amounts"] == [6.33, 6.33, 6.34]
assert sorted((p["method"], p["amount"]) for p in body["payments"]) == [("card", 6.33), ("cash", 12.67)]
assert body["change"] == 7.33
db.expire_all()
assert db.get(Order, body["order_id"]).status in ("paid", "closed")
s = shift_of(client, till)
assert (s["cash_sales"], s["card_sales"]) == (12.67, 6.33)
# off at this venue → refused before anything is written
setting(db, "payments.split_amount", "two_equal")
n = db.query(Order).count()
r = sale(client, till, lines, [], split={"mode": "equal", "parts": 3, "methods": ["cash", "card", "cash"]})
assert err(r) == "split.not_allowed" and db.query(Order).count() == n