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:
@@ -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)
|
||||
|
||||
|
||||
@@ -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
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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] = {}
|
||||
|
||||
Reference in New Issue
Block a user