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.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_change_sent_off": (403, "Prices can only be changed before the items are sent."),
"order.price_reason_required": (400, "Say why the price changes."), "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.nothing_paid": (404, "There are no paid items to undo."),
"order.cannot_close": (400, "This order can't be closed now ({status})."), "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."), "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", "paid_total": "Πληρωμενο: {value:.2f}e",
"pending": "ΕΚΚΡΕΜΗ:", "pending": "ΕΚΚΡΕΜΗ:",
"remaining": "Εκκρεμει: {value:.2f}e", "remaining": "Εκκρεμει: {value:.2f}e",
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ" "title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ",
"split": "ΔΙΑΧΩΡΙΣΜΟΣ (ΕΞΟΦΛΕΙΤΑΙ ΑΠΟ ΤΑ ΜΕΡΗ):"
}, },
"ticket": { "ticket": {
"compact_guests": " | {count}ατ.", "compact_guests": " | {count}ατ.",
@@ -92,7 +93,8 @@
} }
}, },
"system_product": { "system_product": {
"delivery_fee": "Μεταφορικά" "delivery_fee": "Μεταφορικά",
"split_part": "Διαχωρισμός λογαριασμού"
}, },
"qr": { "qr": {
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.", "order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
@@ -104,5 +106,8 @@
"order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.", "order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.",
"order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.", "order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.",
"bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό." "bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό."
},
"split": {
"part_name": "Μέρος λογαριασμού {n}/{of}"
} }
} }
+7 -2
View File
@@ -53,7 +53,8 @@
"paid_total": "Paid: {value:.2f}e", "paid_total": "Paid: {value:.2f}e",
"pending": "PENDING:", "pending": "PENDING:",
"remaining": "Remaining: {value:.2f}e", "remaining": "Remaining: {value:.2f}e",
"title": "ORDER SUMMARY" "title": "ORDER SUMMARY",
"split": "SPLIT BILL (SETTLED BY THE PARTS):"
}, },
"ticket": { "ticket": {
"compact_guests": " | {count}pax", "compact_guests": " | {count}pax",
@@ -92,7 +93,8 @@
} }
}, },
"system_product": { "system_product": {
"delivery_fee": "Delivery fee" "delivery_fee": "Delivery fee",
"split_part": "Split bill"
}, },
"qr": { "qr": {
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.", "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_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.", "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." "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 # 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) # before the cut are this line's too (services/moves.py)
split_from_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True) 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") order = relationship("Order", back_populates="items")
product = relationship("Product", back_populates="order_items") product = relationship("Product", back_populates="order_items")
@@ -295,3 +298,23 @@ class OrderMoveItem(Base):
quantity = Column(Float, nullable=True) quantity = Column(Float, nullable=True)
move = relationship("OrderMove", back_populates="items") 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.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.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.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')), Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')),
), ),
settings=( 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', '[]', '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.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('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('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.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'), SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'),
+3 -1
View File
@@ -312,8 +312,9 @@ def business_day_summary(
if o.table_id: if o.table_id:
waiter_tables.setdefault(o.opened_by, set()).add(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: 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 continue
e = _waiter_entry(item.added_by) e = _waiter_entry(item.added_by)
e["items_ordered"] += item.quantity e["items_ordered"] += item.quantity
@@ -407,6 +408,7 @@ def business_day_summary(
for item in o.items: for item in o.items:
if item.status == "cancelled": if item.status == "cancelled":
continue continue
if not is_part(item):
entry["items"] += item.quantity entry["items"] += item.quantity
if item.status == "paid": if item.status == "paid":
entry["revenue"] += gross(item) 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} return {"lines": [], "total": 0, "paid": 0, "due": 0}
lines = [] lines = []
for i in order.items: 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 continue
unit = (i.unit_price or 0) + (i.price_adjustment or 0) unit = (i.unit_price or 0) + (i.price_adjustment or 0)
texts = menu_languages.product_texts(i.product, customer=False) if i.product else {} 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 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 models.settings import PosSettings
from services.ws_bus import broadcast_sync from services.ws_bus import broadcast_sync
from services import split_bills
router = APIRouter() 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, "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 "split_from_id": i.split_from_id, # 6F.4: the line it was cut from
"cancel_reason": i.cancel_reason, "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): 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), "requested_for": _iso(order.requested_for),
"online_delivery_area": order.online_delivery_area, "online_delivery_area": order.online_delivery_area,
"items": [fmt_item(i) for i in order.items], "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], "waiters": [{"waiter_id": w.waiter_id} for w in order.waiters],
"audit_logs": [fmt_log(l) for l in order.audit_logs], "audit_logs": [fmt_log(l) for l in order.audit_logs],
} }
@@ -923,6 +926,9 @@ def cancel_item(
raise XeniaError("order.item_not_found") raise XeniaError("order.item_not_found")
if item.status == "paid": if item.status == "paid":
raise XeniaError("order.item_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() now = utcnow()
item.status = "cancelled" 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 OrderItem.status.in_(["active", "ready"]), # ready items are also payable
).all() ).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) fiscal_on = is_fiscal_enabled(db)
if fiscal_on and items: own = [i for i in items if not split_bills.is_part(i)]
missing = validate_items_for_fiscal(items, db) if fiscal_on and own:
missing = validate_items_for_fiscal(own, db)
if missing: if missing:
names = ", ".join(missing) names = ", ".join(missing)
raise XeniaError("pos.fiscal_vat_missing", names=names) 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 order.closed_by = user.id
auto_closed = True 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" order.fiscal_status = "pending"
db.commit() db.commit()
@@ -1028,18 +1042,25 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
if auto_closed: if auto_closed:
broadcast_sync("order_closed", {"order_id": order_id, "table_id": order.table_id, "auto_closed": True}) 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 from database import SessionLocal
fiscal_items = build_fiscal_items(items) fiscal_items = build_fiscal_items(own)
send_fiscal_receipt_background(fiscal_items, effective_method, total_paid, db, 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, order_id=order_id, db_factory=SessionLocal,
timeout_seconds=60) 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 { return {
"status": order.status, "status": order.status,
"paid_item_ids": paid_ids, "paid_item_ids": paid_ids,
"auto_closed": auto_closed, "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") raise XeniaError("order.not_yours")
if order.status not in ("paid", "open", "partially_paid"): if order.status not in ("paid", "open", "partially_paid"):
raise XeniaError("order.cannot_close", status=order.status) 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() now = utcnow()
@@ -1256,6 +1279,8 @@ def cancel_order(
if not is_manager and not _waiter_can_cancel(user, db): if not is_manager and not _waiter_can_cancel(user, db):
# a manager may approve this one cancellation with their PIN (D-10) # 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}") 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() now = utcnow()
@@ -1319,11 +1344,12 @@ def cancel_items_bulk(
OrderItem.order_id == order_id, OrderItem.order_id == order_id,
).all() ).all()
split_bills.refuse_parts(items) # 6F.6: undo the split instead
now = utcnow() now = utcnow()
cancelled_ids = [] cancelled_ids = []
skipped_paid = [] skipped_paid = []
for item in items: 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) skipped_paid.append(item.id)
continue continue
item.status = "cancelled" item.status = "cancelled"
@@ -1436,6 +1462,8 @@ def print_order(
if item.status == "cancelled": if item.status == "cancelled":
continue continue
product_name = item.product.name if item.product else f"#{item.product_id}" 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 adj = getattr(item, 'price_adjustment', 0.0) or 0.0
effective_price = item.unit_price + adj effective_price = item.unit_price + adj
items_data.append({ items_data.append({
@@ -1447,7 +1475,7 @@ def print_order(
"status": item.status, "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 = { receipt = {
"order_id": order.id, "order_id": order.id,
@@ -1552,6 +1580,8 @@ def merge_order(
for item in source.items: for item in source.items:
item.order_id = target.id item.order_id = target.id
moved_item_ids.append(item.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) # Copy source waiters to target (no duplicates)
existing_waiter_ids = {w.waiter_id for w in target.waiters} existing_waiter_ids = {w.waiter_id for w in target.waiters}
@@ -1589,6 +1619,68 @@ def merge_order(
return target 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 ────────────────────────────────────── # ─── Split a stacked item into two rows ──────────────────────────────────────
@router.post("/{order_id}/items/{item_id}/split", response_model=List[OrderItemOut]) @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") raise XeniaError("order.item_not_found")
if item.status != "active": if item.status != "active":
raise XeniaError("order.item_not_active") raise XeniaError("order.item_not_active")
split_bills.refuse_parts([item]) # 6F.6
order = db.query(Order).filter(Order.id == order_id).first() order = db.query(Order).filter(Order.id == order_id).first()
if not _can_access_order(order, user, db): if not _can_access_order(order, user, db):
@@ -1873,6 +1966,7 @@ def apply_waiter_discount(
).all() ).all()
if not items: if not items:
raise XeniaError("order.no_active_items", status=404) 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} item_unit_prices = {i.id: i.unit_price + i.price_adjustment for i in items}
@@ -2100,6 +2194,7 @@ def move_items(
).all() ).all()
if not items: if not items:
raise XeniaError("order.no_active_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 from services import moves # 6F.4
moves.record(db, kind="items_moved", source=source, target=target, items=items, user_id=user.id) 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": if item.status == "cancelled":
continue continue
product_name = item.product.name if item.product else f"#{item.product_id}" 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 adj = getattr(item, 'price_adjustment', 0.0) or 0.0
effective_price = item.unit_price + adj effective_price = item.unit_price + adj
items_data.append({ items_data.append({
@@ -2177,7 +2274,7 @@ def print_synopsis(
"status": item.status, "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") paid_total = sum(i["total"] for i in items_data if i["status"] == "paid")
synopsis = { 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") raise XeniaError("order.items_not_combinable", reason="not_found")
if any(i.status != "active" for i in items): if any(i.status != "active" for i in items):
raise XeniaError("order.items_not_combinable", reason="not_unpaid") 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 \ 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: db.query(OrderItem).filter(OrderItem.linked_item_id.in_(ids)).first() is not None:
raise XeniaError("order.items_not_combinable", reason="deal") 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} 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"]) default = pos_cart.point_for(settings["default_order_type"])
cats = db.query(Category).order_by(Category.sort_order, Category.name).all() 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 { return {
# + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount # + 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} "categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
for c in cats], for c in cats],
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON}) "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 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): class SaleBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway" order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(min_length=1, max_length=200) 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) cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
def _payment_groups(body: SaleBody, n: int) -> list: 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: if len(body.payments) == 1 and body.payments[0].lines is None:
return [(body.payments[0].method, list(range(n)))] return [(body.payments[0].method, list(range(n)))]
seen = [i for pay in body.payments for i in (pay.lines or [])] 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) _require_shift(db, user)
orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key 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)] 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) approved_by = _check_discounts(request, db, user, lines)
_check_fiscal(db, {line.product for line in lines}) _check_fiscal(db, {line.product for line in lines})
priced = pos_cart.price_lines(db, lines, body.order_type) 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)] 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)] 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) 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) _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) ───────────────────────────────────────────────── # ── shared checks (3.3b, 3.3c) ─────────────────────────────────────────────────
def _require_shift(db, user): 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()} 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()): if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()):
raise XeniaError("pos.items_changed") 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} 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) cash_due = amount.get("cash", 0.0)
_check_cash(body.cash_given, cash_due) _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.errors import XeniaError
from core.modules.entitlements import clamp_start, history_floor, history_since, limit 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 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 csv
import io import io
import json import json
@@ -164,7 +164,7 @@ def shift_orders_summary(
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
"""Items sent (added) per waiter — regardless of payment status.""" """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) start = end = None # 6.12a: with a business day there is no window (was a crash)
if business_day_id: if business_day_id:
q = q.join(Order).filter(Order.business_day_id == business_day_id) q = q.join(Order).filter(Order.business_day_id == business_day_id)
@@ -496,7 +496,7 @@ def printer_totals(
item_ids = [] item_ids = []
for item_id in item_ids: for item_id in item_ids:
item = db.query(OrderItem).filter(OrderItem.id == item_id).first() 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 summary[pid]["items"] += item.quantity
val = _item_val(item) val = _item_val(item)
summary[pid]["total"] += val summary[pid]["total"] += val
@@ -565,7 +565,7 @@ def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, m
item_ids = [] item_ids = []
for item_id in item_ids: for item_id in item_ids:
item = db.query(OrderItem).filter(OrderItem.id == item_id).first() 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 items_count += item.quantity
val = _item_val(item) val = _item_val(item)
grand_total += val 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()} tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
order_data = [] order_data = []
for o in orders: 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) total = sum(_item_val(i) for i in active_items)
order_data.append({ order_data.append({
"id": o.id, "id": o.id,
@@ -648,7 +648,7 @@ def print_waiter(
}) })
items_count = sum( 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) 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) period_label, period_is_workday = _analytics_period(body, db)
# Build sold-item summary # 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: if body.business_day_id:
q = q.join(Order).filter(Order.business_day_id == 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: elif body.from_dt and body.to_dt:
@@ -837,7 +837,7 @@ def print_categories(
period_label, period_is_workday = _analytics_period(body, db) 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: if body.business_day_id:
q = q.join(Order).filter(Order.business_day_id == 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: elif body.from_dt and body.to_dt:
@@ -974,7 +974,7 @@ def product_performance(
from models.product import Product from models.product import Product
from models.waste import WasteLog 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') _since = history_since(from_dt, 'reports')
if _since: if _since:
q = q.filter(OrderItem.added_at >= _since) q = q.filter(OrderItem.added_at >= _since)
@@ -1337,7 +1337,7 @@ def category_performance(
): ):
from models.product import Product, Category 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') _since = history_since(from_dt, 'reports')
if _since: if _since:
q = q.filter(OrderItem.added_at >= _since) q = q.filter(OrderItem.added_at >= _since)
@@ -1504,7 +1504,7 @@ def printer_history(
order_total = sum( order_total = sum(
_item_val(i) _item_val(i)
for i in order.items 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: if log.success and log.order_id not in seen_order_totals:
seen_order_totals[log.order_id] = order_total 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)) q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
if business_day_id: if business_day_id:
q = q.filter(Order.business_day_id == 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() items = q.all()
# Aggregate per zone # Aggregate per zone
@@ -1839,7 +1839,7 @@ def print_prep_zone(
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt)) q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
if body.business_day_id: if body.business_day_id:
q = q.filter(Order.business_day_id == 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() items = q.all()
product_counts: dict[str, dict] = {} product_counts: dict[str, dict] = {}
+2 -1
View File
@@ -43,7 +43,8 @@ def card(db, customer) -> dict:
from models.table import Table from models.table import Table
orders = db.query(Order).filter(Order.customer_id == customer.id).order_by(Order.opened_at.desc()).all() 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")] 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()} tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
return { return {
"id": customer.id, "name": customer.name, "nickname": customer.nickname, "phone": customer.phone, "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, 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 """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 from models.order import Order
driver = driver_for(db) driver = driver_for(db)
_in_background(db_factory, Order, order_id, lambda: driver.prepare_receipt(db, items, payment_method, total), _in_background(db_factory, Order, order_id,
timeout_seconds) 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, 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). # cashier is told to issue the credit note on the machine itself (owner decision 2026-11-15).
credit_notes: bool = False credit_notes: bool = False
def prepare_receipt(self, db, items: list[dict], method: str, total: float) -> 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.""" """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 raise NotImplementedError
def prepare_credit_note(self, db, items: list[dict], method: str, total: float, original: dict | None = None) -> Send: 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 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. 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(): if msg_line.strip():
lines.append(f"FM|{i}|{msg_line.upper()}") 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}" total_str = f"{total:.2f}"
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{total_str}") lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{total_str}")
else: else:
@@ -177,11 +185,11 @@ class TxtFileDriver(FiscalDriver):
name = "dTEC100extra (text-file bridge)" name = "dTEC100extra (text-file bridge)"
credit_notes = False 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) out_folder, in_folder = _get_folders(db)
os.makedirs(out_folder, exist_ok=True) os.makedirs(out_folder, exist_ok=True)
os.makedirs(in_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() filename = _unique_filename()
return lambda timeout_seconds: _write_and_poll(out_folder, in_folder, content, filename, timeout_seconds) return lambda timeout_seconds: _write_and_poll(out_folder, in_folder, content, filename, timeout_seconds)
+29 -2
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** - 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 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). 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 - **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; money taken, but not a product sold. `revenue` everywhere is products only; `fees` is beside it;
`takings` = revenue + fees. `takings` = revenue + fees.
@@ -17,7 +21,7 @@ from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
SOLD = ("active", "paid", "tabbed") SOLD = ("active", "paid", "tabbed", "split")
def gross(item, quantity: float | None = None) -> float: 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 """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.""" stays (quantity 0, value 0) so its refund is counted; `sold()` leaves it out of lists."""
from services.refunds import refunded_quantities 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"]) 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() fees = _fee_products(db) if sold else set()
out = [] out = []
for i in sold: for i in sold:
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) r = min(back.get(i.id, 0.0), i.quantity)
q = max(i.quantity - r, 0.0) 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)) 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 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 @dataclass
class Totals: class Totals:
revenue: float = 0.0 # products, net of refunds 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 from collections import Counter
DELIVERY_FEE = "delivery_fee" 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): 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): class Machine(FiscalDriver):
key, credit_notes = "test_machine", True 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} return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
def prepare_credit_note(self, db, items, method, total, original=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
@@ -69,9 +69,36 @@ function OrderingSettings() {
</SettingsCard> </SettingsCard>
<PriceChangeSettings s={s} /> <PriceChangeSettings s={s} />
<QuantitySettings s={s} /> <QuantitySettings s={s} />
<SplitSettings s={s} />
</>) </>)
} }
/** Splitting a bill by amount (6F.6), each level with the ones before. Who may:
* ordering.payments.split_amount ("What each role may do", a person's permissions). */
function SplitSettings({ s }) {
const { t } = useTranslation('manager')
const q = k => t(`settings.split.${k}`)
const id = useId()
const maxId = useId()
const level = s.get('payments.split_amount', 'off')
return (
<SettingsCard title={q('title')} description={q('intro')} testId="settings-split">
<SettingRow label={q('when')} hint={q('whenHint')} tip={q('whenTip')} htmlFor={id}>
<Select id={id} value={level} disabled={s.saving} data-testid="setting-payments.split_amount"
onChange={e => s.save('payments.split_amount', e.target.value)}
options={['off', 'two_equal', 'two_custom', 'multiple_equal'].map(v => ({ value: v, label: q(`levels.${v}`) }))} />
</SettingRow>
{level === 'multiple_equal' && (
<SettingRow label={q('max')} hint={q('maxHint')} htmlFor={maxId}>
<Select id={maxId} value={String(s.get('payments.split_max_parts', '10'))} disabled={s.saving} data-testid="setting-payments.split_max_parts"
onChange={e => s.save('payments.split_max_parts', e.target.value)}
options={[3, 4, 5, 6, 8, 10, 12, 15, 20].map(n => ({ value: String(n), label: String(n) }))} />
</SettingRow>
)}
</SettingsCard>
)
}
/** A sent line's quantity changed without a new ticket (6F.5). Who may: ordering.items.change_quantity; /** A sent line's quantity changed without a new ticket (6F.5). Who may: ordering.items.change_quantity;
* lowering also needs ordering.orders.cancel ("What each role may do", a person's permissions). */ * lowering also needs ordering.orders.cancel ("What each role may do", a person's permissions). */
function QuantitySettings({ s }) { function QuantitySettings({ s }) {
@@ -22,7 +22,9 @@ import OrderPeople from './OrderPeople'
import PayDialog from './PayDialog' import PayDialog from './PayDialog'
import PrintProblemsCard from './PrintProblemsCard' import PrintProblemsCard from './PrintProblemsCard'
import { AuditList, MoveList, PriceEventList } from './OrderHistory' import { AuditList, MoveList, PriceEventList } from './OrderHistory'
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic' import { closeStep, isSplitPart, totals, unpaidIds, venueRules } from './orderLogic'
import { SplitBillsCard } from './SplitAmount'
import { useCan } from '@xenia/access'
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated'] const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' } const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
@@ -78,6 +80,7 @@ function OrderView({ orderId }) {
const venue = useVenue() const venue = useVenue()
const [tab, setTab] = useState('order') const [tab, setTab] = useState('order')
const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after } const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after }
const maySplit = useCan('ordering.payments.split_amount') // 6F.6
const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel' const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel'
const [printerId, setPrinterId] = useState('') const [printerId, setPrinterId] = useState('')
@@ -156,6 +159,7 @@ function OrderView({ orderId }) {
</div> </div>
<PrintProblemsCard orderId={order.id} /> <PrintProblemsCard orderId={order.id} />
<SplitBillsCard order={order} canUndo={maySplit} onChanged={refresh} />
{tab === 'order' && ( {tab === 'order' && (
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}> <div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
@@ -172,6 +176,9 @@ function OrderView({ orderId }) {
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>} {tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose} {paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
split={venue.split.on && maySplit && !paying.thenClose && !order.items.some(i => paying.ids.includes(i.id) && isSplitPart(i))
? { choices: venue.split, customerCount: order.customer_count } : null}
onSplit={() => { toast.success(t('orders.split.done')); paying.after?.(); setPaying(null); refresh() }}
onClose={() => setPaying(null)} onClose={() => setPaying(null)}
onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />} onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
@@ -3,17 +3,20 @@
// "instant-pay close": the rest is paid and the order closed in one go, for venues that don't // "instant-pay close": the rest is paid and the order closed in one go, for venues that don't
// close with unpaid items (orders.close_with_unpaid, 4.8). // close with unpaid items (orders.close_with_unpaid, 4.8).
import { useState } from 'react' import { useState } from 'react'
import { Banknote, CreditCard } from 'lucide-react' import { Banknote, CreditCard, Divide } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog } from '@xenia/ui' import { Button, Dialog } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { SplitAmountForm } from './SplitAmount'
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, onClose, onDone }) { /** `split` ({ choices, customerCount }, 6F.6): offers "Split the amount" instead of paying now. */
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, split = null, onSplit, onClose, onDone }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const [busy, setBusy] = useState(null) const [busy, setBusy] = useState(null)
const [error, setError] = useState(null) const [error, setError] = useState(null)
const [splitting, setSplitting] = useState(false)
async function pay(method) { async function pay(method) {
setBusy(method) setBusy(method)
@@ -44,6 +47,13 @@ export default function PayDialog({ orderId, itemIds, amount, card = true, thenC
</Button> </Button>
</div> </div>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>} {error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
{split && !splitting && (
<Button variant="ghost" icon={<Divide size={18} />} disabled={!!busy} onClick={() => setSplitting(true)} data-testid="pay-split">{t('orders.split.button')}</Button>
)}
{split && splitting && (
<SplitAmountForm orderId={orderId} itemIds={itemIds} amount={amount} choices={split.choices} customerCount={split.customerCount}
onCancel={() => setSplitting(false)} onDone={onSplit} />
)}
</div> </div>
</Dialog> </Dialog>
) )
@@ -0,0 +1,113 @@
// Splitting a bill by amount in the manager (plan 6F.6), as the phones and the counter do: the chosen
// lines are settled into a split bill and cut into equal parts (pre-filled from the customers) or, for
// two parts, any amounts; each part is then paid like any line. Undo while no part is paid.
import { useState } from 'react'
import { Minus, Plus, Undo2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { defaultParts, splitAmounts } from '@xenia/ordering/split'
import { Button, IconButton, Input } from '@xenia/ui'
import toast from 'react-hot-toast'
import client from '../../api/client'
/** The part of the pay dialog that splits instead of paying (choices from splitChoices()). */
export function SplitAmountForm({ orderId, itemIds, amount, choices, customerCount, onDone, onCancel }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [parts, setParts] = useState(() => defaultParts(customerCount, choices.maxParts))
const [mode, setMode] = useState('equal')
const [first, setFirst] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState(null)
const uneven = mode === 'custom' && parts === 2
const typed = first.trim() ? parseNumber(first, { decimals: 2, allowNegative: false }) : null
const amounts = splitAmounts(amount, uneven ? 'custom' : 'equal', parts, typed)
const step = d => { setParts(p => Math.max(2, Math.min(choices.maxParts, p + d))); setMode('equal') }
async function split() {
setBusy(true)
setError(null)
try {
await client.post(`/api/orders/${orderId}/split-bills`, uneven
? { item_ids: itemIds, mode: 'custom', parts: 2, first_amount: amounts[0] }
: { item_ids: itemIds, mode: 'equal', parts })
onDone()
} catch (err) {
setError(errorMessage(err, t))
} finally { setBusy(false) }
}
return (
<div className="grid gap-3 border-t border-line pt-3" data-testid="split-form">
{choices.maxParts > 2 && (
<div className="flex items-center justify-center gap-4">
<IconButton label={t('orders.split.fewer')} variant="secondary" disabled={parts <= 2} onClick={() => step(-1)}><Minus size={18} /></IconButton>
<span className="text-display font-semibold min-w-16 text-center tabular-nums" data-testid="split-parts">{parts}</span>
<IconButton label={t('orders.split.more')} variant="secondary" disabled={parts >= choices.maxParts} onClick={() => step(1)} data-testid="split-more"><Plus size={18} /></IconButton>
</div>
)}
{choices.custom && parts === 2 && (
<div className="grid grid-cols-2 gap-2">
{['equal', 'custom'].map(m => (
<Button key={m} size="sm" variant={mode === m ? 'primary' : 'secondary'} aria-pressed={mode === m} onClick={() => setMode(m)} data-testid={`split-${m}`}>
{t(`orders.split.${m}`)}
</Button>
))}
</div>
)}
{uneven && (
<label className="grid gap-1 text-label text-ink-2">
{t('orders.split.first')}
<Input inputMode="decimal" value={first} onChange={e => setFirst(e.target.value)} placeholder={formatMoney(Math.round(amount * 50) / 100)} data-testid="split-first" />
</label>
)}
{amounts ? (
<ul className="grid gap-0.5 text-body" data-testid="split-preview">
{amounts.map((a, i) => (
<li key={i} className="flex justify-between"><span>{t('orders.split.part', { n: i + 1, of: amounts.length })}</span><span className="tabular-nums font-medium">{formatMoney(a)}</span></li>
))}
</ul>
) : <p className="text-label text-danger-ink">{t('orders.split.invalid')}</p>}
<p className="text-caption text-ink-2">{t('orders.split.hint')}</p>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={onCancel} disabled={busy}>{t('orders.back')}</Button>
<Button loading={busy} disabled={!amounts} onClick={split} data-testid="split-confirm">{t('orders.split.confirm', { count: amounts?.length ?? parts })}</Button>
</div>
</div>
)
}
/** The order's split bills: parts, paid so far, and Undo while nothing is paid. */
export function SplitBillsCard({ order, canUndo, onChanged }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [busy, setBusy] = useState(null)
const bills = order.split_bills ?? []
if (!bills.length) return null
async function undo(bill) {
setBusy(bill.id)
try {
await client.post(`/api/orders/${order.id}/split-bills/${bill.id}/undo`)
toast.success(t('orders.split.undone'))
onChanged()
} catch (err) {
toast.error(errorMessage(err, t))
} finally { setBusy(null) }
}
return (
<section className="rounded-card border border-line bg-surface shadow-raised p-3 grid gap-2" data-testid="split-bills">
{bills.map(b => (
<div key={b.id} className="flex flex-wrap items-center gap-3" data-testid="split-bill">
<span className="flex-1 min-w-0">
<span className="block text-body font-medium text-ink">{t('orders.split.bill', { count: b.parts, total: formatMoney(b.total) })}</span>
<span className="block text-label text-ink-2">{t('orders.split.paid', { paid: formatMoney(b.paid), due: formatMoney(Math.max(0, b.total - b.paid)) })}</span>
</span>
{canUndo && b.can_undo && (
<Button size="sm" variant="secondary" icon={<Undo2 size={16} />} loading={busy === b.id} onClick={() => undo(b)} data-testid="split-undo">{t('orders.split.undo')}</Button>
)}
</div>
))}
</section>
)
}
@@ -3,6 +3,8 @@
// items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise // items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise
// the rest is paid first. // the rest is paid first.
import { splitChoices, splitLevel, splitMax } from '@xenia/ordering/split'
export const OPEN_STATUSES = ['open', 'partially_paid', 'paid'] export const OPEN_STATUSES = ['open', 'partially_paid', 'paid']
export const isOpen = order => !!order && OPEN_STATUSES.includes(order.status) export const isOpen = order => !!order && OPEN_STATUSES.includes(order.status)
@@ -59,9 +61,13 @@ export function closeStep(order, closeWithUnpaid) {
/** The venue's settings rows (GET /api/settings/) → the two that matter here. */ /** The venue's settings rows (GET /api/settings/) → the two that matter here. */
export function venueRules(settings) { export function venueRules(settings) {
const v = key => settings?.[key]?.value const v = key => settings?.[key]?.value
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false' } return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false',
split: splitChoices(splitLevel(settings), splitMax(settings)) } // 6F.6
} }
/** A split bill's part line (6F.6): paid on its own, never split again. */
export const isSplitPart = item => item?.split_bill_id != null && item.status !== 'split'
/** The cart's lines as the server takes them, plus the order's note (POST /api/orders/{id}/items). */ /** The cart's lines as the server takes them, plus the order's note (POST /api/orders/{id}/items). */
export function sendBody(cart, note) { export function sendBody(cart, note) {
return { lines: cart.map(c => c.line), order_note: note?.trim() || null } return { lines: cart.map(c => c.line), order_note: note?.trim() || null }
+6 -2
View File
@@ -28,8 +28,12 @@ test('close: nothing unpaid closes; unpaid lines are paid first unless the venue
assert.equal(closeStep(order, false), 'payFirst') assert.equal(closeStep(order, false), 'payFirst')
assert.equal(closeStep(order, true), 'writeOff') assert.equal(closeStep(order, true), 'writeOff')
assert.equal(closeStep({ items: [item(1, 'paid', 5)] }, false), 'close') assert.equal(closeStep({ items: [item(1, 'paid', 5)] }, false), 'close')
assert.deepEqual(venueRules({ 'orders.close_with_unpaid': { value: 'true' } }), { closeWithUnpaid: true, card: true }) const off = { on: false, maxParts: 2, custom: false }
assert.deepEqual(venueRules({ 'payments.card_enabled': { value: 'false' } }), { closeWithUnpaid: false, card: false }) assert.deepEqual(venueRules({ 'orders.close_with_unpaid': { value: 'true' } }), { closeWithUnpaid: true, card: true, split: off })
assert.deepEqual(venueRules({ 'payments.card_enabled': { value: 'false' } }), { closeWithUnpaid: false, card: false, split: off })
// 6F.6: splitting by amount, the venue's level and the most parts
assert.deepEqual(venueRules({ 'payments.split_amount': { value: 'multiple_equal' }, 'payments.split_max_parts': { value: '6' } }).split,
{ on: true, maxParts: 6, custom: true })
}) })
test('what a line has, the body sent (ids only), waiters to add', () => { test('what a line has, the body sent (ids only), waiters to add', () => {
+9
View File
@@ -375,5 +375,14 @@
"scene": { "scene": {
"not_found": "Η σκηνή δεν βρέθηκε.", "not_found": "Η σκηνή δεν βρέθηκε.",
"until_past": "Αυτή η ώρα έχει περάσει: διαλέξτε μια μεταγενέστερη." "until_past": "Αυτή η ώρα έχει περάσει: διαλέξτε μια μεταγενέστερη."
},
"split": {
"not_allowed": "Αυτός ο διαχωρισμός λογαριασμού δεν είναι ενεργός σε αυτό το κατάστημα.",
"lines_changed": "Κάποια από αυτά πληρώθηκαν ή άλλαξαν στο μεταξύ. Δείτε ξανά.",
"amount_invalid": "Κάθε μέρος πρέπει να είναι πάνω από 0 και κάτω από το σύνολο ({{total}}).",
"part_locked": "Αυτό είναι μέρος διαχωρισμένου λογαριασμού: αναιρέστε τον διαχωρισμό για να το αλλάξετε.",
"not_found": "Αυτός ο διαχωρισμός δεν υπάρχει πια.",
"paid_already": "Ένα μέρος έχει ήδη πληρωθεί ή μπει σε καρτέλα: ο διαχωρισμός δεν αναιρείται.",
"parts_unpaid": "Μέρη διαχωρισμένου λογαριασμού είναι ακόμα απλήρωτα: πληρώστε τα πρώτα."
} }
} }
+40 -2
View File
@@ -771,6 +771,21 @@
"add_only": "Μόνο προσθήκη", "add_only": "Μόνο προσθήκη",
"add_and_remove": "Προσθήκη και αφαίρεση" "add_and_remove": "Προσθήκη και αφαίρεση"
} }
},
"split": {
"title": "Διαχωρισμός λογαριασμού με ποσά",
"intro": "Το προσωπικό χωρίζει έναν λογαριασμό σε μέρη που πληρώνονται χωριστά: οι γραμμές εξοφλούνται μαζί και κάθε μέρος πληρώνεται μετρητά, με κάρτα ή σε καρτέλα.",
"when": "Το προσωπικό μπορεί να χωρίσει",
"whenHint": "Ποιος: «Τι επιτρέπεται σε κάθε ρόλο» και τα δικαιώματα κάθε ατόμου.",
"whenTip": "Κάθε επιλογή περιλαμβάνει τις προηγούμενες. Μισά μισά: δύο ίσα μέρη. Δύο μέρη, όποια ποσά: και αναλογία ή τι πληρώνει το μέρος 1. Σε ίσα μέρη: από 2 έως το μέγιστο παρακάτω, το υπόλοιπο λεπτό στο τελευταίο μέρος. Ο διαχωρισμός αναιρείται μέχρι να πληρωθεί ένα μέρος. Η απόδειξη είναι οι ίδιες οι γραμμές και τυπώνεται όταν πληρωθεί το τελευταίο μέρος.",
"levels": {
"off": "Καθόλου",
"two_equal": "Μισά μισά",
"two_custom": "Δύο μέρη, όποια ποσά",
"multiple_equal": "Σε ίσα μέρη (και δύο με όποια ποσά)"
},
"max": "Μέγιστα ίσα μέρη",
"maxHint": "Τα μέρη ξεκινούν από τους πελάτες του τραπεζιού, όταν υπάρχουν."
} }
}, },
"logs": { "logs": {
@@ -3348,7 +3363,8 @@
"paid": "Πληρώθηκε", "paid": "Πληρώθηκε",
"cancelled": "Ακυρώθηκε", "cancelled": "Ακυρώθηκε",
"tabbed": "Στην καρτέλα", "tabbed": "Στην καρτέλα",
"closed": "Απλήρωτο" "closed": "Απλήρωτο",
"split": "Σε διαχωρισμό"
}, },
"without": "Χωρίς {{list}}", "without": "Χωρίς {{list}}",
"added": "{{time}} · {{name}}", "added": "{{time}} · {{name}}",
@@ -3409,7 +3425,10 @@
"PRICE_CHANGED": "Αλλαγή τιμής", "PRICE_CHANGED": "Αλλαγή τιμής",
"PRICE_SET_BY_HAND": "Τιμή με το χέρι (εγκρίθηκε)", "PRICE_SET_BY_HAND": "Τιμή με το χέρι (εγκρίθηκε)",
"QUANTITY_CHANGED": "Αλλαγή ποσότητας", "QUANTITY_CHANGED": "Αλλαγή ποσότητας",
"ITEM_REORDERED": "Άλλο ένα" "ITEM_REORDERED": "Άλλο ένα",
"SPLIT_CREATED": "Διαχωρισμός λογαριασμού",
"SPLIT_UNDONE": "Αναίρεση διαχωρισμού",
"SPLIT_SETTLED": "Εξόφληση διαχωρισμού"
}, },
"price": { "price": {
"modifier_applied": "Κανόνας τιμής", "modifier_applied": "Κανόνας τιμής",
@@ -3485,6 +3504,25 @@
"items_moved": "Μεταφορά γραμμών", "items_moved": "Μεταφορά γραμμών",
"orders_merged": "Ένωση τραπεζιών" "orders_merged": "Ένωση τραπεζιών"
} }
},
"split": {
"button": "Διαχωρισμός ποσού",
"fewer": "Ένα μέρος λιγότερο",
"more": "Ένα μέρος ακόμη",
"equal": "Ίσα μέρη",
"custom": "Διαφορετικά ποσά",
"first": "Το μέρος 1 πληρώνει",
"part": "Μέρος {{n}} από {{of}}",
"invalid": "Αυτό το ποσό δεν μοιράζεται έτσι.",
"hint": "Οι γραμμές εξοφλούνται μαζί· κάθε μέρος πληρώνεται μετά χωριστά (μετρητά, κάρτα ή καρτέλα). Αναιρείται μέχρι να πληρωθεί ένα μέρος.",
"confirm_one": "Διαχωρισμός σε {{count}} μέρος",
"confirm_other": "Διαχωρισμός σε {{count}} μέρη",
"done": "Ο λογαριασμός διαχωρίστηκε: πληρώστε κάθε μέρος χωριστά.",
"undone": "Ο διαχωρισμός αναιρέθηκε.",
"bill_one": "Διαχωρισμός · {{count}} μέρος από {{total}}",
"bill_other": "Διαχωρισμός · {{count}} μέρη από {{total}}",
"paid": "Πληρώθηκαν {{paid}} · απομένουν {{due}}",
"undo": "Αναίρεση διαχωρισμού"
} }
}, },
"printing": { "printing": {
+2 -1
View File
@@ -463,7 +463,8 @@
}, },
"refunds": "Επιστροφή χρημάτων για πληρωμές άλλων βαρδιών", "refunds": "Επιστροφή χρημάτων για πληρωμές άλλων βαρδιών",
"payments": { "payments": {
"revert": "Αναίρεση πληρωμής (πληρωμένα → απλήρωτα)" "revert": "Αναίρεση πληρωμής (πληρωμένα → απλήρωτα)",
"split_amount": "Διαχωρισμός λογαριασμού με ποσά (ίσα μέρη ή αναλογία)"
}, },
"items": { "items": {
"change_quantity": "Αλλαγή ποσότητας σταλμένης γραμμής (χωρίς νέο δελτίο)" "change_quantity": "Αλλαγή ποσότητας σταλμένης γραμμής (χωρίς νέο δελτίο)"
+16 -2
View File
@@ -215,7 +215,20 @@
"given": "Μετρητά που δόθηκαν", "given": "Μετρητά που δόθηκαν",
"exact": "Ακριβώς: {{amount}}", "exact": "Ακριβώς: {{amount}}",
"change": "Ρέστα: {{amount}}", "change": "Ρέστα: {{amount}}",
"short": "Είναι λιγότερα από το ποσό που οφείλεται" "short": "Είναι λιγότερα από το ποσό που οφείλεται",
"amount": "Με ποσά",
"confirmAmount_one": "Είσπραξη {{count}} μέρους",
"confirmAmount_other": "Είσπραξη των {{count}} μερών",
"fewerParts": "Ένα μέρος λιγότερο",
"moreParts": "Ένα μέρος ακόμη",
"share": {
"equal": "Ίσα μέρη",
"custom": "Διαφορετικά ποσά"
},
"firstPart": "Το μέρος 1 πληρώνει",
"part": "Μέρος {{n}} από {{of}}",
"splitInvalid": "Αυτό το ποσό δεν μοιράζεται έτσι.",
"amountHint": "Τα είδη εξοφλούνται μαζί και κάθε μέρος πληρώνεται τώρα, μετρητά ή κάρτα."
}, },
"done": { "done": {
"paid": "Πληρώθηκαν {{total}}", "paid": "Πληρώθηκαν {{total}}",
@@ -281,7 +294,8 @@
"cash": "πληρώθηκε · μετρητά", "cash": "πληρώθηκε · μετρητά",
"card": "πληρώθηκε · κάρτα" "card": "πληρώθηκε · κάρτα"
}, },
"readyItem": "έτοιμο" "readyItem": "έτοιμο",
"settled": "Στον διαχωρισμό"
}, },
"online": { "online": {
"arrived_one": "Νέα online παραγγελία", "arrived_one": "Νέα online παραγγελία",
+28
View File
@@ -918,5 +918,33 @@
"noChange": "Αλλάξτε τη με − και +", "noChange": "Αλλάξτε τη με − και +",
"onlyUp": "Σε αυτό το κατάστημα οι ποσότητες μόνο αυξάνονται.", "onlyUp": "Σε αυτό το κατάστημα οι ποσότητες μόνο αυξάνονται.",
"sendCancel": "Αποστολή ακύρωσης στην κουζίνα" "sendCancel": "Αποστολή ακύρωσης στην κουζίνα"
},
"split": {
"button": "Διαχωρισμός ποσού",
"title": "Διαχωρισμός ποσού",
"items_one": "{{count}} είδος",
"items_other": "{{count}} είδη",
"partsLabel": "μέρη",
"fewer": "Ένα μέρος λιγότερο",
"more": "Ένα μέρος ακόμη",
"equal": "Ίσα μέρη",
"custom": "Διαφορετικά ποσά",
"ratio": "Πώς μοιράζεται",
"firstAmount": "Το μέρος 1 πληρώνει",
"part": "Μέρος {{n}} από {{of}}",
"invalid": "Αυτό το ποσό δεν μοιράζεται έτσι.",
"howItWorks": "Τα είδη εξοφλούνται μαζί· κάθε μέρος πληρώνεται μετά χωριστά (μετρητά, κάρτα ή καρτέλα). Αναιρείται μέχρι να πληρωθεί ένα μέρος.",
"confirm_one": "Διαχωρισμός σε {{count}} μέρος",
"confirm_other": "Διαχωρισμός σε {{count}} μέρη",
"bill_one": "Διαχωρισμός · {{count}} μέρος από {{total}}",
"bill_other": "Διαχωρισμός · {{count}} μέρη από {{total}}",
"billPaid": "Πληρώθηκαν {{paid}} · απομένουν {{due}}",
"undo": "Αναίρεση",
"settled": "Διαχωρισμός",
"settledHint": "Εξοφλείται από διαχωρισμένο λογαριασμό: τα μέρη του το πληρώνουν.",
"err": {
"split": "Ο λογαριασμός δεν διαχωρίστηκε.",
"undo": "Ο διαχωρισμός δεν αναιρέθηκε."
}
} }
} }
+9
View File
@@ -375,5 +375,14 @@
"scene": { "scene": {
"not_found": "Scene not found.", "not_found": "Scene not found.",
"until_past": "That time has already passed: pick a later one." "until_past": "That time has already passed: pick a later one."
},
"split": {
"not_allowed": "Splitting a bill this way isn't turned on for this venue.",
"lines_changed": "Some of these items were paid or changed meanwhile. Look again.",
"amount_invalid": "Each part must be more than 0 and less than the total ({{total}}).",
"part_locked": "This is part of a split bill: undo the split to change it.",
"not_found": "That split bill isn't there any more.",
"paid_already": "A part is already paid or on a tab: the split can't be undone.",
"parts_unpaid": "Parts of a split bill are still unpaid: take their payment first."
} }
} }
+40 -2
View File
@@ -771,6 +771,21 @@
"add_only": "Only add", "add_only": "Only add",
"add_and_remove": "Add and remove" "add_and_remove": "Add and remove"
} }
},
"split": {
"title": "Splitting a bill by amount",
"intro": "Staff split a bill into parts that are paid on their own: the lines are settled together and each part is paid in cash, by card or on a tab.",
"when": "Staff may split",
"whenHint": "Who may: \"What each role may do\" and each person's permissions.",
"whenTip": "Each choice includes the ones before. Half and half: two equal parts. Two parts, any amounts: also a ratio, or what part 1 pays. Into equal parts: 2 up to the most below, the remainder of a cent on the last part. A split can be undone until a part is paid. The receipt is the lines themselves, printed when the last part is paid.",
"levels": {
"off": "Not at all",
"two_equal": "Half and half",
"two_custom": "Two parts, any amounts",
"multiple_equal": "Into equal parts (and two any amounts)"
},
"max": "The most equal parts",
"maxHint": "The parts start at the table's customers when it has some."
} }
}, },
"logs": { "logs": {
@@ -3348,7 +3363,8 @@
"paid": "Paid", "paid": "Paid",
"cancelled": "Cancelled", "cancelled": "Cancelled",
"tabbed": "On the tab", "tabbed": "On the tab",
"closed": "Written off" "closed": "Written off",
"split": "In a split bill"
}, },
"without": "Without {{list}}", "without": "Without {{list}}",
"added": "{{time}} · {{name}}", "added": "{{time}} · {{name}}",
@@ -3409,7 +3425,10 @@
"PRICE_CHANGED": "Price changed", "PRICE_CHANGED": "Price changed",
"PRICE_SET_BY_HAND": "Price set by hand (approved)", "PRICE_SET_BY_HAND": "Price set by hand (approved)",
"QUANTITY_CHANGED": "Quantity changed", "QUANTITY_CHANGED": "Quantity changed",
"ITEM_REORDERED": "One more" "ITEM_REORDERED": "One more",
"SPLIT_CREATED": "Bill split",
"SPLIT_UNDONE": "Split undone",
"SPLIT_SETTLED": "Split bill paid"
}, },
"price": { "price": {
"modifier_applied": "Price rule", "modifier_applied": "Price rule",
@@ -3485,6 +3504,25 @@
"items_moved": "Lines moved", "items_moved": "Lines moved",
"orders_merged": "Tables joined" "orders_merged": "Tables joined"
} }
},
"split": {
"button": "Split the amount",
"fewer": "One part less",
"more": "One part more",
"equal": "Equal parts",
"custom": "Different amounts",
"first": "Part 1 pays",
"part": "Part {{n}} of {{of}}",
"invalid": "This amount can't be split that way.",
"hint": "The lines are settled together; each part is then paid on its own (cash, card or a tab). It can be undone until a part is paid.",
"confirm_one": "Split into {{count}} part",
"confirm_other": "Split into {{count}} parts",
"done": "The bill is split: pay each part on its own.",
"undone": "The split was undone.",
"bill_one": "Split bill · {{count}} part of {{total}}",
"bill_other": "Split bill · {{count}} parts of {{total}}",
"paid": "Paid {{paid}} · still due {{due}}",
"undo": "Undo the split"
} }
}, },
"printing": { "printing": {
+2 -1
View File
@@ -463,7 +463,8 @@
}, },
"refunds": "Refund payments from other shifts", "refunds": "Refund payments from other shifts",
"payments": { "payments": {
"revert": "Turn paid items back to unpaid" "revert": "Turn paid items back to unpaid",
"split_amount": "Split a bill by amount (equal parts or a ratio)"
}, },
"items": { "items": {
"change_quantity": "Change a sent line's quantity (no new ticket)" "change_quantity": "Change a sent line's quantity (no new ticket)"
+16 -2
View File
@@ -215,7 +215,20 @@
"given": "Cash given", "given": "Cash given",
"exact": "Exact: {{amount}}", "exact": "Exact: {{amount}}",
"change": "Change: {{amount}}", "change": "Change: {{amount}}",
"short": "That's less than the amount due" "short": "That's less than the amount due",
"amount": "By amount",
"confirmAmount_one": "Take {{count}} part",
"confirmAmount_other": "Take the {{count}} parts",
"fewerParts": "One part less",
"moreParts": "One part more",
"share": {
"equal": "Equal parts",
"custom": "Different amounts"
},
"firstPart": "Part 1 pays",
"part": "Part {{n}} of {{of}}",
"splitInvalid": "This amount can't be split that way.",
"amountHint": "The items are settled together and each part is paid now, by cash or card."
}, },
"done": { "done": {
"paid": "Paid {{total}}", "paid": "Paid {{total}}",
@@ -281,7 +294,8 @@
"cash": "paid · cash", "cash": "paid · cash",
"card": "paid · card" "card": "paid · card"
}, },
"readyItem": "ready" "readyItem": "ready",
"settled": "In the split bill"
}, },
"online": { "online": {
"arrived_one": "New online order", "arrived_one": "New online order",
+28
View File
@@ -918,5 +918,33 @@
"noChange": "Use − and + to change it", "noChange": "Use − and + to change it",
"onlyUp": "At this venue quantities only go up.", "onlyUp": "At this venue quantities only go up.",
"sendCancel": "Send a cancellation to the kitchen" "sendCancel": "Send a cancellation to the kitchen"
},
"split": {
"button": "Split the amount",
"title": "Split the amount",
"items_one": "{{count}} item",
"items_other": "{{count}} items",
"partsLabel": "parts",
"fewer": "One part less",
"more": "One part more",
"equal": "Equal parts",
"custom": "Different amounts",
"ratio": "How it is shared",
"firstAmount": "Part 1 pays",
"part": "Part {{n}} of {{of}}",
"invalid": "This amount can't be split that way.",
"howItWorks": "The items are settled together; each part is then paid on its own (cash, card or a tab). You can undo it until a part is paid.",
"confirm_one": "Split into {{count}} part",
"confirm_other": "Split into {{count}} parts",
"bill_one": "Split bill · {{count}} part of {{total}}",
"bill_other": "Split bill · {{count}} parts of {{total}}",
"billPaid": "Paid {{paid}} · still due {{due}}",
"undo": "Undo",
"settled": "Split",
"settledHint": "Settled by a split bill: its parts pay for it.",
"err": {
"split": "The bill wasn't split.",
"undo": "The split wasn't undone."
}
} }
} }
+2 -1
View File
@@ -8,7 +8,8 @@
"exports": { "exports": {
".": "./src/index.js", ".": "./src/index.js",
"./cart": "./src/cart.js", "./cart": "./src/cart.js",
"./printProblems": "./src/printProblems.js" "./printProblems": "./src/printProblems.js",
"./split": "./src/split.js"
}, },
"dependencies": { "dependencies": {
"@xenia/access": "^0.0.0", "@xenia/access": "^0.0.0",
+1
View File
@@ -6,4 +6,5 @@ export * from './cart.js'
export { ProductDialog } from './ProductDialog.jsx' export { ProductDialog } from './ProductDialog.jsx'
export { useQuote } from './useQuote.js' export { useQuote } from './useQuote.js'
export * from './printProblems.js' export * from './printProblems.js'
export * from './split.js'
export { PrintProblemsPanel } from './PrintProblemsPanel.jsx' export { PrintProblemsPanel } from './PrintProblemsPanel.jsx'
+55
View File
@@ -0,0 +1,55 @@
// Split the bill by amount (plan 6F.6; the server's rules are local_backend/services/split_bills.py), shared by
// the waiter app, the counter and the manager. Plain JS so Node tests can import it (@xenia/ordering/split).
export const LEVELS = ['off', 'two_equal', 'two_custom', 'multiple_equal']
/** The venue's payments.split_amount (each level includes the ones before). */
export function splitLevel(settings) {
const v = settings?.['payments.split_amount']?.value
return LEVELS.includes(v) ? v : 'off'
}
/** The most equal parts (payments.split_max_parts, 2…50). */
export function splitMax(settings) {
const n = parseInt(settings?.['payments.split_max_parts']?.value ?? '10', 10)
return Number.isFinite(n) ? Math.max(2, Math.min(50, n)) : 10
}
const rank = level => Math.max(0, LEVELS.indexOf(level))
/** What the dialog offers at this level: the most parts, and whether two parts may be uneven. */
export function splitChoices(level, max) {
return {
on: rank(level) >= 1,
maxParts: rank(level) >= 3 ? max : 2,
custom: rank(level) >= 2,
}
}
/** Each part to the cent; equal parts put the remainder on the last (10.00 / 3 = 3.33 + 3.33 + 3.34);
* custom: `first` is part 1 and part 2 the rest. null when it can't be split that way. */
export function splitAmounts(total, mode, parts, first) {
const cents = Math.round(total * 100)
if (mode === 'custom') {
const a = Math.round((first ?? 0) * 100)
return a > 0 && a < cents ? [a / 100, (cents - a) / 100] : null
}
if (parts < 2 || cents < parts) return null
const base = Math.floor(cents / parts)
return [...Array(parts - 1).fill(base / 100), (cents - base * (parts - 1)) / 100]
}
/** The parts pre-filled from the order's customers when there are some (owner OK), else 2. */
export function defaultParts(customerCount, maxParts) {
const n = Number(customerCount)
return Number.isInteger(n) && n >= 2 ? Math.min(n, maxParts) : 2
}
/** A split bill's part line (the money for the settled lines). */
export const isPart = item => item?.split_bill_id != null && item.status !== 'split'
/** A line settled by a split bill (sold; its parts pay for it). */
export const isSettled = item => item?.status === 'split'
/** The value that counts in an order's total: settled lines are counted through their parts. */
export const countsInTotal = item => item.status !== 'cancelled' && item.status !== 'split'
+38
View File
@@ -0,0 +1,38 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { countsInTotal, defaultParts, isPart, isSettled, splitAmounts, splitChoices, splitLevel, splitMax } from '../src/split.js'
test('the venue level and its choices, each including the ones before (6F.6)', () => {
assert.equal(splitLevel({}), 'off')
assert.equal(splitLevel({ 'payments.split_amount': { value: 'two_custom' } }), 'two_custom')
assert.equal(splitLevel({ 'payments.split_amount': { value: 'nonsense' } }), 'off')
assert.equal(splitMax({ 'payments.split_max_parts': { value: '80' } }), 50)
assert.deepEqual(splitChoices('off', 10), { on: false, maxParts: 2, custom: false })
assert.deepEqual(splitChoices('two_equal', 10), { on: true, maxParts: 2, custom: false })
assert.deepEqual(splitChoices('two_custom', 10), { on: true, maxParts: 2, custom: true })
assert.deepEqual(splitChoices('multiple_equal', 6), { on: true, maxParts: 6, custom: true })
})
test('the amounts match the server: remainder on the last part, custom = part 1 + the rest', () => {
assert.deepEqual(splitAmounts(10, 'equal', 3), [3.33, 3.33, 3.34])
assert.deepEqual(splitAmounts(15, 'custom', 2, 4.5), [4.5, 10.5])
assert.equal(splitAmounts(15, 'custom', 2, 15), null)
assert.equal(splitAmounts(0.02, 'equal', 3), null)
})
test('pre-filled from the customers, within the most parts', () => {
assert.equal(defaultParts(4, 10), 4)
assert.equal(defaultParts(12, 10), 10)
assert.equal(defaultParts(null, 10), 2)
assert.equal(defaultParts(1, 10), 2)
})
test('parts and settled lines: totals count the parts, never both', () => {
const settled = { status: 'split', split_bill_id: 3 }
const part = { status: 'active', split_bill_id: 3 }
assert.equal(isSettled(settled), true)
assert.equal(isPart(part), true)
assert.equal(isPart(settled), false)
assert.equal(countsInTotal(settled), false)
assert.equal(countsInTotal(part), true)
})
+79 -9
View File
@@ -3,27 +3,41 @@
// by row. The caller's `submit({ method, rowMethods, cashGiven })` makes the one call: a quick // by row. The caller's `submit({ method, rowMethods, cashGiven })` makes the one call: a quick
// sale (POST /api/pos/sales, rows = cart lines) or a table's items (POST /api/pos/orders/{id}/pay, // sale (POST /api/pos/sales, rows = cart lines) or a table's items (POST /api/pos/orders/{id}/pay,
// rows = order items). Cash with the exact amount is pre-selected: Charge → Take = two taps. // rows = order items). Cash with the exact amount is pre-selected: Charge → Take = two taps.
// "Split the amount" (6F.6): the total cut into equal parts (or two parts in any ratio), each paid
// now by cash or card: `submit({ method: 'amount', split: { mode, parts, first_amount, methods } })`.
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { Banknote, Check, CreditCard, Split } from 'lucide-react' import { Banknote, Check, CreditCard, Divide, Minus, Plus, Split } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n' import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input } from '@xenia/ui' import { defaultParts, splitAmounts } from '@xenia/ordering/split'
import { Button, Dialog, IconButton, Input } from '@xenia/ui'
import { changeFor, quickAmounts, splitPayments } from './logic/cart' import { changeFor, quickAmounts, splitPayments } from './logic/cart'
import { useDisplay } from './usePos' import { useDisplay } from './usePos'
const tab = on => `flex-1 min-h-[var(--x-control-lg)] rounded-control flex items-center justify-center gap-2 text-body-lg font-medium transition-colors duration-fast const tab = on => `flex-1 min-h-[var(--x-control-lg)] rounded-control flex items-center justify-center gap-2 text-body-lg font-medium transition-colors duration-fast
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}` ${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
/** rows: [{ label, total }]; submit({ method: 'cash'|'card'|'split', rowMethods, payments, cashGiven }) /** rows: [{ label, total }]; submit({ method: 'cash'|'card'|'split'|'amount', rowMethods, payments, split, cashGiven })
* → the result passed to onPaid. `payments` are by row index (splitPayments). */ * → the result passed to onPaid. `payments` are by row index (splitPayments). `amountSplit`
export default function PaymentDialog({ total, rows, submit, onPaid, onClose }) { * ({ choices, customerCount }, 6F.6) offers "Split the amount" when the venue and the key allow it. */
export default function PaymentDialog({ total, rows, submit, onPaid, onClose, amountSplit = null }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const totals = rows.map(r => r.total) const totals = rows.map(r => r.total)
const [method, setMethod] = useState('cash') const [method, setMethod] = useState('cash')
const [split, setSplit] = useState(() => rows.map(() => 'card')) const [split, setSplit] = useState(() => rows.map(() => 'card'))
const parts = splitPayments(split, totals) const parts = splitPayments(split, totals)
const cashDue = method === 'cash' ? total : method === 'split' ? parts.cash : 0 // 6F.6: by amount
const maxParts = amountSplit?.choices.maxParts ?? 2
const [nParts, setNParts] = useState(() => defaultParts(amountSplit?.customerCount, maxParts))
const [shareMode, setShareMode] = useState('equal')
const [firstText, setFirstText] = useState('')
const [partMethods, setPartMethods] = useState(() => Array(50).fill('cash'))
const uneven = shareMode === 'custom' && nParts === 2
const firstAmount = firstText.trim() ? parseNumber(firstText, { decimals: 2, allowNegative: false }) : null
const amounts = method === 'amount' ? splitAmounts(total, uneven ? 'custom' : 'equal', nParts, firstAmount) : null
const amountCash = amounts ? Math.round(amounts.reduce((s, a, i) => s + (partMethods[i] === 'cash' ? a : 0), 0) * 100) / 100 : 0
const cashDue = method === 'cash' ? total : method === 'split' ? parts.cash : method === 'amount' ? amountCash : 0
const [givenText, setGivenText] = useState('') // empty = the exact amount const [givenText, setGivenText] = useState('') // empty = the exact amount
const given = givenText.trim() === '' ? null : parseNumber(givenText, { decimals: 2, allowNegative: false }) const given = givenText.trim() === '' ? null : parseNumber(givenText, { decimals: 2, allowNegative: false })
const change = cashDue > 0 ? changeFor(given ?? cashDue, cashDue) : null const change = cashDue > 0 ? changeFor(given ?? cashDue, cashDue) : null
@@ -43,8 +57,11 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
setBusy(true) setBusy(true)
setError('') setError('')
const payments = method === 'split' ? parts.payments : [{ method, lines: rows.map((_, i) => i) }] const payments = method === 'split' ? parts.payments : [{ method, lines: rows.map((_, i) => i) }]
const bySplit = method === 'amount'
? { mode: uneven ? 'custom' : 'equal', parts: amounts.length, first_amount: uneven ? amounts[0] : undefined, methods: partMethods.slice(0, amounts.length) }
: undefined
try { try {
const result = await submit({ method, rowMethods: split, payments, cashGiven: cashDue > 0 ? (given ?? cashDue) : null }) const result = await submit({ method, rowMethods: split, payments, split: bySplit, cashGiven: cashDue > 0 ? (given ?? cashDue) : null })
paidRef.current = true paidRef.current = true
display({ mode: 'paid', total, paid: result?.cash_given ?? total, change: result?.change ?? 0 }) display({ mode: 'paid', total, paid: result?.cash_given ?? total, change: result?.change ?? 0 })
onPaid(result) onPaid(result)
@@ -59,16 +76,18 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
<Dialog open onClose={busy ? undefined : onClose} size="md" title={t('pos.pay.title', { total: formatMoney(total) })} <Dialog open onClose={busy ? undefined : onClose} size="md" title={t('pos.pay.title', { total: formatMoney(total) })}
footer={<> footer={<>
<Button variant="secondary" size="lg" onClick={onClose} disabled={busy}>{t('pos.dialog.close')}</Button> <Button variant="secondary" size="lg" onClick={onClose} disabled={busy}>{t('pos.dialog.close')}</Button>
<Button size="lg" icon={<Check size={18} />} loading={busy} disabled={short || (method === 'split' && (!parts.cash || !parts.card))} <Button size="lg" icon={<Check size={18} />} loading={busy}
disabled={short || (method === 'split' && (!parts.cash || !parts.card)) || (method === 'amount' && !amounts)}
onClick={pay} data-testid="pay-confirm"> onClick={pay} data-testid="pay-confirm">
{method === 'card' ? t('pos.pay.confirmCard', { amount: formatMoney(total) }) {method === 'card' ? t('pos.pay.confirmCard', { amount: formatMoney(total) })
: method === 'cash' ? t('pos.pay.confirmCash', { amount: formatMoney(total) }) : method === 'cash' ? t('pos.pay.confirmCash', { amount: formatMoney(total) })
: method === 'amount' ? t('pos.pay.confirmAmount', { count: amounts?.length ?? nParts })
: t('pos.pay.confirmSplit')} : t('pos.pay.confirmSplit')}
</Button> </Button>
</>}> </>}>
<div className="grid gap-4" data-testid="payment-dialog"> <div className="grid gap-4" data-testid="payment-dialog">
<div className="flex gap-2" role="radiogroup" aria-label={t('pos.pay.method')}> <div className="flex gap-2" role="radiogroup" aria-label={t('pos.pay.method')}>
{[['cash', Banknote], ['card', CreditCard], ['split', Split]].map(([m, Icon]) => ( {[['cash', Banknote], ['card', CreditCard], ['split', Split], ...(amountSplit ? [['amount', Divide]] : [])].map(([m, Icon]) => (
<button key={m} type="button" role="radio" aria-checked={method === m} className={tab(method === m)} onClick={() => { setMethod(m); setGivenText('') }} data-testid={`pay-${m}`}> <button key={m} type="button" role="radio" aria-checked={method === m} className={tab(method === m)} onClick={() => { setMethod(m); setGivenText('') }} data-testid={`pay-${m}`}>
<Icon size={18} />{t(`pos.pay.${m}`)} <Icon size={18} />{t(`pos.pay.${m}`)}
</button> </button>
@@ -99,6 +118,57 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
</div> </div>
)} )}
{method === 'amount' && (
<div className="grid gap-3" data-testid="amount-split">
{maxParts > 2 && (
<div className="flex items-center justify-center gap-4">
<IconButton label={t('pos.pay.fewerParts')} variant="secondary" disabled={nParts <= 2}
onClick={() => { setNParts(n => Math.max(2, n - 1)); setShareMode('equal') }} data-testid="amount-fewer"><Minus size={18} /></IconButton>
<span className="text-display font-semibold min-w-16 text-center" data-testid="amount-parts">{nParts}</span>
<IconButton label={t('pos.pay.moreParts')} variant="secondary" disabled={nParts >= maxParts}
onClick={() => { setNParts(n => Math.min(maxParts, n + 1)); setShareMode('equal') }} data-testid="amount-more"><Plus size={18} /></IconButton>
</div>
)}
{amountSplit.choices.custom && nParts === 2 && (
<div className="flex gap-2">
{['equal', 'custom'].map(m => (
<button key={m} type="button" aria-pressed={shareMode === m} onClick={() => setShareMode(m)} data-testid={`amount-${m}`}
className={`flex-1 min-h-[var(--x-control-md)] rounded-control text-body font-medium ${shareMode === m ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
{t(`pos.pay.share.${m}`)}
</button>
))}
</div>
)}
{uneven && (
<label className="grid gap-1 text-label text-ink-2">
{t('pos.pay.firstPart')}
<Input inputMode="decimal" value={firstText} onChange={e => setFirstText(e.target.value)} data-testid="amount-first"
placeholder={formatMoney(Math.round(total * 50) / 100)} />
</label>
)}
{amounts ? (
<div className="grid gap-1 max-h-60 overflow-y-auto">
{amounts.map((a, i) => (
<div key={i} className="flex items-center gap-2 py-1 border-b border-line" data-testid="amount-part">
<span className="flex-1 text-body text-ink">{t('pos.pay.part', { n: i + 1, of: amounts.length })}</span>
<span className="text-body font-medium">{formatMoney(a)}</span>
<span className="flex gap-1">
{['cash', 'card'].map(m => (
<button key={m} type="button" aria-pressed={partMethods[i] === m} data-part={`${i}-${m}`}
onClick={() => setPartMethods(pm => pm.map((x, j) => (j === i ? m : x)))}
className={`px-3 min-h-[var(--x-control-sm)] rounded-control text-label font-medium ${partMethods[i] === m ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
{t(`pos.pay.${m}`)}
</button>
))}
</span>
</div>
))}
</div>
) : <p className="text-label text-danger-ink">{t('pos.pay.splitInvalid')}</p>}
<p className="text-caption text-ink-2">{t('pos.pay.amountHint')}</p>
</div>
)}
{method === 'card' && <p className="text-body text-ink-2">{t('pos.pay.cardHint', { amount: formatMoney(total) })}</p>} {method === 'card' && <p className="text-body text-ink-2">{t('pos.pay.cardHint', { amount: formatMoney(total) })}</p>}
{cashDue > 0 && ( {cashDue > 0 && (
+8 -3
View File
@@ -14,7 +14,8 @@
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { Globe, Info, LayoutGrid, Receipt, Search, ShoppingBag, X } from 'lucide-react' import { Globe, Info, LayoutGrid, Receipt, Search, ShoppingBag, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n' import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { useCan, useModule } from '@xenia/access' import { useAllowed, useCan, useModule } from '@xenia/access'
import { splitChoices as splitChoicesOf } from '@xenia/ordering/split'
import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui' import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui'
import { useLiveEvent } from '../../device/context' import { useLiveEvent } from '../../device/context'
import { playChime } from './chime' import { playChime } from './chime'
@@ -65,6 +66,10 @@ function Counter({ menu, t }) {
// a discount is a price changed in the cart (6F.3): none when the venue turned that off // a discount is a price changed in the cart (6F.3): none when the venue turned that off
const mayDiscount = useCan('ordering.prices.modify') const mayDiscount = useCan('ordering.prices.modify')
const canDiscount = menu.settings.price_change === 'off' ? null : mayDiscount // null: no discount at all const canDiscount = menu.settings.price_change === 'off' ? null : mayDiscount // null: no discount at all
// 6F.6: splitting a bill by amount (the venue's level, the key; a manager may approve it once)
const splitAccess = useAllowed('ordering.payments.split_amount')
const splitChoices = splitChoicesOf(menu.settings.split_amount, menu.settings.split_max_parts ?? 10)
const amountSplit = splitChoices.on && splitAccess !== 'no' ? { choices: splitChoices } : null
const toast = useToast() const toast = useToast()
const onlineModule = useModule('connect_orders') const onlineModule = useModule('connect_orders')
const handlesOnline = useCan('connect_orders.manage') const handlesOnline = useCan('connect_orders.manage')
@@ -249,9 +254,9 @@ function Counter({ menu, t }) {
</div> </div>
</main> </main>
{atTable {atTable
? <TablePanel key={table.id} table={table} cart={tableCart} setCart={setTableCart} byId={byId} canDiscount={canDiscount} ? <TablePanel key={table.id} table={table} cart={tableCart} setCart={setTableCart} byId={byId} canDiscount={canDiscount} amountSplit={amountSplit}
onBack={leaveTable} onTablesChanged={tables.reload} /> onBack={leaveTable} onTablesChanged={tables.reload} />
: <SaleCart cart={saleCart} setCart={setSaleCart} orderType={orderType} setOrderType={setOrderType} byId={byId} canDiscount={canDiscount} />} : <SaleCart cart={saleCart} setCart={setSaleCart} orderType={orderType} setOrderType={setOrderType} byId={byId} canDiscount={canDiscount} amountSplit={amountSplit} />}
</> </>
)} )}
+6 -4
View File
@@ -11,7 +11,7 @@ import { setLineQty } from './logic/cart'
import PaymentDialog from './PaymentDialog' import PaymentDialog from './PaymentDialog'
import { useDisplay, useQuote } from './usePos' import { useDisplay, useQuote } from './usePos'
export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount }) { export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount, amountSplit = null }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const toast = useToast() const toast = useToast()
@@ -36,8 +36,10 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId,
}, [cart, ready, quote.quote, paying, byId, display]) }, [cart, ready, quote.quote, paying, byId, display])
useEffect(() => () => display({ mode: 'idle' }), [display]) useEffect(() => () => display({ mode: 'idle' }), [display])
const submit = async ({ method, payments, cashGiven }) => (await client.post('/api/pos/sales', { const submit = async ({ method, payments, split, cashGiven }) => (await client.post('/api/pos/sales', {
order_type: orderType, lines: cart, payments: method === 'split' ? payments : [{ method }], cash_given: cashGiven, order_type: orderType, lines: cart, cash_given: cashGiven,
// 6F.6: split by amount, every part paid now (Q-4)
...(method === 'amount' ? { payments: [], split } : { payments: method === 'split' ? payments : [{ method }] }),
})).data })).data
return ( return (
@@ -76,7 +78,7 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId,
</div> </div>
{paying && quote.quote && ( {paying && quote.quote && (
<PaymentDialog total={quote.quote.total} submit={submit} <PaymentDialog total={quote.quote.total} submit={submit} amountSplit={amountSplit}
rows={cart.map((l, i) => ({ label: `${l.quantity}× ${byId.get(l.product_id)?.name ?? ''}`, total: quote.quote.lines[i].total }))} rows={cart.map((l, i) => ({ label: `${l.quantity}× ${byId.get(l.product_id)?.name ?? ''}`, total: quote.quote.lines[i].total }))}
onClose={() => setPaying(false)} onClose={() => setPaying(false)}
onPaid={result => { onPaid={result => {
+18 -7
View File
@@ -11,13 +11,13 @@ import { Button, Dialog, EmptyState, IconButton, Spinner, useToast } from '@xeni
import client from '../../api/client' import client from '../../api/client'
import CartLine from './CartLine' import CartLine from './CartLine'
import { setLineQty } from './logic/cart' import { setLineQty } from './logic/cart'
import { itemPayments, orderLines, orderSums, qtyLabel, tableState, toPay } from './logic/tables' import { itemPayments, orderLines, orderSums, partPayments, qtyLabel, tableState, toPay } from './logic/tables'
import OneMore from './OneMore' import OneMore from './OneMore'
import PaymentDialog from './PaymentDialog' import PaymentDialog from './PaymentDialog'
import { PaidSummary } from './SaleCart' import { PaidSummary } from './SaleCart'
import { useOrder, useQuote } from './usePos' import { useOrder, useQuote } from './usePos'
export default function TablePanel({ table, cart, setCart, byId, canDiscount, onBack, onTablesChanged }) { export default function TablePanel({ table, cart, setCart, byId, canDiscount, onBack, onTablesChanged, amountSplit = null }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat() const { formatMoney, formatTime } = useFormat()
const toast = useToast() const toast = useToast()
@@ -75,11 +75,20 @@ export default function TablePanel({ table, cart, setCart, byId, canDiscount, on
reload() reload()
}) })
const payRows = chosen.map(l => ({ id: l.id, label: `${qtyLabel(l.quantity, l.unitType)} ${l.name}`, total: l.total })) const payRows = chosen.map(l => ({ id: l.id, label: `${qtyLabel(l.quantity, l.unitType)} ${l.name}`, total: l.total, part: l.part }))
const submitPay = async ({ method, payments, cashGiven }) => (await client.post(`/api/pos/orders/${orderId}/pay`, { const submitPay = async ({ method, payments, split, cashGiven }) => {
payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }], let body
cash_given: cashGiven, if (method === 'amount') {
// 6F.6: settle the lines into a split bill, then pay every part now, each by its method
const bill = (await client.post(`/api/orders/${orderId}/split-bills`, {
item_ids: paying.map(r => r.id), mode: split.mode, parts: split.parts, first_amount: split.first_amount,
})).data })).data
body = { payments: partPayments(bill.part_ids, split.methods) }
} else {
body = { payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }] }
}
return (await client.post(`/api/pos/orders/${orderId}/pay`, { ...body, cash_given: cashGiven })).data
}
const toggle = id => setSelected(sel => (sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id])) const toggle = id => setSelected(sel => (sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id]))
@@ -179,6 +188,7 @@ export default function TablePanel({ table, cart, setCart, byId, canDiscount, on
{paying && ( {paying && (
<PaymentDialog total={orderSums(paying).total} rows={paying} submit={submitPay} <PaymentDialog total={orderSums(paying).total} rows={paying} submit={submitPay}
amountSplit={amountSplit && !paying.some(r => r.part) ? { ...amountSplit, customerCount: order?.customer_count } : null}
onClose={() => setPaying(null)} onClose={() => setPaying(null)}
onPaid={result => { onPaid={result => {
setPaying(null) setPaying(null)
@@ -231,7 +241,8 @@ function OrderLine({ line, selected, onToggle }) {
</span> </span>
<span className="text-body text-right"> <span className="text-body text-right">
{formatMoney(line.total)} {formatMoney(line.total)}
{line.paid && <span className="block text-caption text-success-ink">{t(`pos.table.paidBy.${line.method === 'card' ? 'card' : 'cash'}`)}</span>} {line.paid && !line.settled && <span className="block text-caption text-success-ink">{t(`pos.table.paidBy.${line.method === 'card' ? 'card' : 'cash'}`)}</span>}
{line.settled && <span className="block text-caption text-info-ink">{t('pos.table.settled')}</span>}
{!line.paid && line.kds === 'done' && <span className="block text-caption text-success-ink">{t('pos.table.readyItem')}</span>} {!line.paid && line.kds === 'done' && <span className="block text-caption text-success-ink">{t('pos.table.readyItem')}</span>}
</span> </span>
</span> </span>
+17 -6
View File
@@ -41,25 +41,28 @@ export function optionNames(selected) {
} }
/** An order's items as the counter lists them (cancelled and written-off ones left out), /** An order's items as the counter lists them (cancelled and written-off ones left out),
* unpaid first, each with its total. */ * unpaid first, each with its total. A split bill (6F.6): its parts are lines like any other
* (`part`), the lines it settled show with the paid ones (`settled`) and add up to nothing. */
export function orderLines(order) { export function orderLines(order) {
if (!order?.items) return [] if (!order?.items) return []
const lines = order.items const lines = order.items
.filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid') .filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid' || i.status === 'split')
.map(i => ({ .map(i => ({
id: i.id, id: i.id,
name: i.product_name ?? i.product?.name ?? '', name: i.product_name ?? i.product?.name ?? '',
quantity: i.quantity, quantity: i.quantity,
unitType: i.unit_type, unitType: i.unit_type,
total: round2((i.unit_price + (i.price_adjustment || 0)) * i.quantity), total: round2((i.unit_price + (i.price_adjustment || 0)) * i.quantity),
paid: i.status === 'paid', paid: i.status === 'paid' || i.status === 'split',
settled: i.status === 'split',
part: i.split_bill_id != null && i.status !== 'split',
method: i.payment_method, method: i.payment_method,
options: optionNames(i.selected_options), options: optionNames(i.selected_options),
notes: i.notes, notes: i.notes,
kds: i.kds_status ?? 'pending', kds: i.kds_status ?? 'pending',
system: i.system_key ?? null, // a line the system added: 'delivery_fee' (phase 3S) system: i.system_key ?? null, // a line the system added: 'delivery_fee' (phase 3S)
// "+1" (6F.5): the product allows it, in pieces, not a deal's line // "+1" (6F.5): the product allows it, in pieces, not a deal's line
oneMore: !!i.product?.one_more_enabled && (i.unit_type ?? 'piece') === 'piece' && !i.deal_id && !i.linked_item_id, oneMore: !!i.product?.one_more_enabled && (i.unit_type ?? 'piece') === 'piece' && !i.deal_id && !i.linked_item_id && i.status !== 'split',
})) }))
return [...lines.filter(l => !l.paid), ...lines.filter(l => l.paid)] return [...lines.filter(l => !l.paid), ...lines.filter(l => l.paid)]
} }
@@ -67,8 +70,16 @@ export function orderLines(order) {
/** { total, paid, unpaid, unpaidIds } of the lines. */ /** { total, paid, unpaid, unpaidIds } of the lines. */
export function orderSums(lines) { export function orderSums(lines) {
const sum = ls => round2(ls.reduce((s, l) => s + l.total, 0)) const sum = ls => round2(ls.reduce((s, l) => s + l.total, 0))
const open = lines.filter(l => !l.paid) const counted = lines.filter(l => !l.settled) // 6F.6: the parts pay for the settled lines
return { total: sum(lines), paid: sum(lines.filter(l => l.paid)), unpaid: sum(open), unpaidIds: open.map(l => l.id) } const open = counted.filter(l => !l.paid)
return { total: sum(counted), paid: sum(counted.filter(l => l.paid)), unpaid: sum(open), unpaidIds: open.map(l => l.id) }
}
/** A split bill's parts paid now (6F.6): one payment per method, as POST /api/pos/orders/{id}/pay takes. */
export function partPayments(partIds, methods) {
return ['cash', 'card']
.map(method => ({ method, item_ids: partIds.filter((_, i) => (methods[i] ?? 'cash') === method) }))
.filter(p => p.item_ids.length)
} }
/** What "Pay" takes: the selected unpaid lines, or every unpaid line when none is selected. */ /** What "Pay" takes: the selected unpaid lines, or every unpaid line when none is selected. */
+15
View File
@@ -129,6 +129,21 @@ test('tables at the counter: state, zones, order lines, what Pay takes (3.3c)',
assert.equal(qtyLabel(0.5, 'liter'), '0.5 L') assert.equal(qtyLabel(0.5, 'liter'), '0.5 L')
}) })
test('a split bill at the counter: parts are lines, settled lines add up to nothing (6F.6)', async () => {
const { orderLines, orderSums, partPayments, toPay } = await import('../src/apps/pos/logic/tables.js')
const order = { items: [
{ id: 1, product_name: 'Burger', quantity: 1, unit_price: 10, status: 'split', split_bill_id: 4 },
{ id: 2, product_name: 'Freddo', quantity: 2, unit_price: 2.5, status: 'split', split_bill_id: 4 },
{ id: 3, product_name: 'Split bill 1/2', quantity: 1, unit_price: 4.5, status: 'paid', payment_method: 'cash', split_bill_id: 4 },
{ id: 4, product_name: 'Split bill 2/2', quantity: 1, unit_price: 10.5, status: 'active', split_bill_id: 4 },
] }
const lines = orderLines(order)
assert.deepEqual(lines.map(l => [l.id, l.paid, !!l.settled, !!l.part]), [[4, false, false, true], [1, true, true, false], [2, true, true, false], [3, true, false, true]])
assert.deepEqual(orderSums(lines), { total: 15, paid: 4.5, unpaid: 10.5, unpaidIds: [4] })
assert.deepEqual(toPay(lines, []).map(l => l.id), [4])
assert.deepEqual(partPayments([7, 8, 9], ['cash', 'card', 'cash']), [{ method: 'cash', item_ids: [7, 9] }, { method: 'card', item_ids: [8] }])
})
test('online orders: the next step and finding an order (3.3d)', async () => { test('online orders: the next step and finding an order (3.3d)', async () => {
const { findOnline, minutesSince, nextStep } = await import('../src/apps/pos/logic/online.js') const { findOnline, minutesSince, nextStep } = await import('../src/apps/pos/logic/online.js')
assert.deepEqual(nextStep({ status: 'pending_acceptance' }), { kind: 'answer' }) assert.deepEqual(nextStep({ status: 'pending_acceptance' }), { kind: 'answer' })
+11 -1
View File
@@ -755,8 +755,18 @@ try {
for (let i = 0; i < 30 && qMode !== 'add_only'; i++) { await sleep(150); qMode = await settingValue2('orders.quantity_change') } for (let i = 0; i < 30 && qMode !== 'add_only'; i++) { await sleep(150); qMode = await settingValue2('orders.quantity_change') }
r.check(`${st6} Operation: quantity changes "only add"`, qMode === 'add_only') r.check(`${st6} Operation: quantity changes "only add"`, qMode === 'add_only')
await page.getByTestId('setting-orders.quantity_change').selectOption('off') await page.getByTestId('setting-orders.quantity_change').selectOption('off')
await page.getByTestId('settings-price-changes').getByRole('switch').first().click() // by keyboard: the stack of "saved" toasts can cover the switch, depending on the cards' layout
await page.getByTestId('settings-price-changes').getByRole('switch').first().focus()
await page.keyboard.press('Space')
await sleep(500) await sleep(500)
// 6F.6: splitting a bill by amount; the most parts only shows for equal parts
await page.getByTestId('setting-payments.split_amount').selectOption('multiple_equal')
await page.getByTestId('setting-payments.split_max_parts').selectOption('6', { timeout: 5000 }).catch(() => {})
let sMax = ''
for (let i = 0; i < 30 && sMax !== '6'; i++) { await sleep(150); sMax = await settingValue2('payments.split_max_parts') }
r.check(`${st6} Operation: splitting by amount into up to 6 equal parts`, await settingValue2('payments.split_amount') === 'multiple_equal' && sMax === '6')
await page.getByTestId('setting-payments.split_amount').selectOption('off')
r.check(`${st6} …"the most parts" hides when equal parts are off`, await page.getByTestId('setting-payments.split_max_parts').waitFor({ state: 'detached', timeout: 5000 }).then(() => true).catch(() => false))
await page.getByTestId('flag-new').click() await page.getByTestId('flag-new').click()
await page.getByTestId('flag-save').click() await page.getByTestId('flag-save').click()
r.check(`${st6} a table flag needs a name`, (await page.getByTestId('flag-dialog').textContent()).includes('Enter a name')) r.check(`${st6} a table flag needs a name`, (await page.getByTestId('flag-dialog').textContent()).includes('Enter a name'))
+24
View File
@@ -75,6 +75,7 @@ async function pairFromManager(page, boss, body) {
try { try {
const boss = await supportLogin(backend.url) const boss = await supportLogin(backend.url)
await api('PUT', '/api/settings/payments.split_amount', { token: boss, body: { value: 'multiple_equal' } }) // 6F.6
const chef = await api('POST', '/api/waiters/', { token: boss, body: { username: 'term_chef', full_name: 'Maria Chef', pin: '4747', role: 'chef', is_active: true } }) const chef = await api('POST', '/api/waiters/', { token: boss, body: { username: 'term_chef', full_name: 'Maria Chef', pin: '4747', role: 'chef', is_active: true } })
await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: true } }) await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: true } })
// Staff get no password from the Staff page yet (phase 6): the demo's store manager has one // Staff get no password from the Staff page yet (phase 6): the demo's store manager has one
@@ -434,6 +435,29 @@ try {
await sleep(300) await sleep(300)
r.check('3.3b: …and the drawer stayed shut', drawerBytes.length === drawerBefore) r.check('3.3b: …and the drawer stayed shut', drawerBytes.length === drawerBefore)
// ── 6F.6: a quick sale split by amount, each part paid its own way (Q-4) ──
await page.getByTestId('same-again').click()
await page.waitForFunction(x => document.querySelector('[data-testid="cart-total"]')?.textContent.includes(x), expected, { timeout: 5000 }).catch(() => {})
await page.getByTestId('charge').click()
await page.getByTestId('pay-amount').click()
r.check('6F.6: "Split the amount" starts with two equal parts', await page.getByTestId('amount-part').count() === 2)
await page.getByTestId('amount-more').click()
await page.locator('[data-part="1-card"]').click()
const cents = Math.round(cartTotal * 100)
const base = Math.floor(cents / 3)
const wantParts = [base, base, cents - 2 * base].map(c => (c / 100).toFixed(2))
const partsText = await page.getByTestId('amount-part').allTextContents()
r.check('6F.6: three parts, the remainder on the last', partsText.length === 3 && partsText.every((x, i) => x.includes(wantParts[i])), JSON.stringify(partsText))
await page.screenshot({ path: path.join(OUT, 'terminal-pos-split.png') })
await page.getByTestId('pay-confirm').click()
const splitDone = await page.getByTestId('sale-done').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)
const splitOrder = splitDone ? await api('GET', `/api/orders/${Number(await page.getByTestId('sale-done').getAttribute('data-order'))}`, { token: boss }) : null
const splitParts = splitOrder?.items.filter(i => i.split_bill_id && i.status !== 'split') ?? []
r.check('6F.6: paid → the lines are settled and the three parts paid cash, card, cash', splitDone
&& splitOrder.items.filter(i => i.status === 'split').length === 2
&& JSON.stringify(splitParts.map(i => [i.status, i.payment_method])) === JSON.stringify([['paid', 'cash'], ['paid', 'card'], ['paid', 'cash']]),
JSON.stringify(splitParts.map(i => [i.product_name, i.status, i.payment_method])))
// ── 3.3c: tables at the counter, with a waiter's phone on the same table ─ // ── 3.3c: tables at the counter, with a waiter's phone on the same table ─
// the phone: Maria's live connection (as the waiter app opens it) and her API calls // the phone: Maria's live connection (as the waiter app opens it) and her API calls
const phoneEvents = [] const phoneEvents = []
+56
View File
@@ -429,6 +429,62 @@ try {
await setting(boss, 'orders.close_with_unpaid', 'false') await setting(boss, 'orders.close_with_unpaid', 'false')
} }
// ── 6F.6: split the amount: pre-filled from the customers, undo, pay one part ────────
{
await setting(boss, 'payments.split_amount', 'multiple_equal')
const busyNow = new Set((await api('GET', '/api/orders/', { token: boss })).map(o => o.table_id))
const ts = (await api('GET', '/api/tables/', { token: boss })).find(x => x.is_active !== false && !busyNow.has(x.id))
const os = await api('POST', '/api/orders/', { token: tokenA, body: { table_id: ts.id } })
await api('POST', `/api/orders/${os.id}/items`, { token: tokenA, body: { lines: [{ product_id: plain.id, quantity: 1 }, { product_id: other.id, quantity: 2 }] } })
await api('PATCH', `/api/orders/${os.id}/customer-count`, { token: tokenA, body: { customer_count: 3 } })
const get = () => api('GET', `/api/orders/${os.id}`, { token: boss })
const before = await get()
const total = Math.round(before.items.reduce((x, i) => x + (i.unit_price + (i.price_adjustment || 0)) * i.quantity, 0) * 100) / 100
const openSplit = async () => {
await a.goto(`${APP}/tables/${ts.id}`)
await a.reload()
await a.getByTestId('pay-button').click({ timeout: 10_000 })
await a.getByTestId('pay-split').click({ timeout: 5000 })
await a.getByTestId('split-sheet').waitFor({ timeout: 5000 })
}
await openSplit()
r.check('6F.6: "Split the amount" starts at the table\'s 3 customers', (await a.getByTestId('split-parts').textContent()) === '3')
await a.screenshot({ path: path.join(OUT, 'waiter-split.png') })
await a.getByTestId('split-confirm').click()
const split3 = await waitFor(async () => { const o = await get(); return o.split_bills?.length === 1 && o }, 10_000, 500)
const cents = Math.round(total * 100)
const b3 = Math.floor(cents / 3)
r.check('6F.6: the lines are settled, three parts appear (the cent on the last)', !!split3
&& split3.items.filter(i => i.status === 'split').length === 2
&& JSON.stringify(split3.split_bills[0].amounts) === JSON.stringify([b3 / 100, b3 / 100, (cents - 2 * b3) / 100]), JSON.stringify(split3?.split_bills))
await a.getByTestId('split-bill').waitFor({ timeout: 10_000 })
r.check('6F.6: the table shows the split bill and its parts as lines', (await a.locator('.order-item').allTextContents()).filter(x => x.includes('Split bill')).length === 3)
// undo while nothing is paid
await a.getByTestId('split-undo').click()
const undone = await waitFor(async () => { const o = await get(); return o.split_bills?.length === 0 && o }, 10_000, 500)
r.check('6F.6: Undo: the lines are unpaid again, the parts cancelled', !!undone
&& undone.items.filter(i => i.status === 'active').length === 2 && undone.items.filter(i => i.cancel_reason === 'split undone').length === 3)
// split in two, pay one part
await openSplit()
await a.getByTestId('split-fewer').click()
await a.getByTestId('split-confirm').click()
const split2 = await waitFor(async () => { const o = await get(); return o.split_bills?.length === 1 && o }, 10_000, 500)
await a.getByTestId('split-bill').waitFor({ timeout: 10_000 })
const part1 = split2.items.find(i => i.id === split2.split_bills[0].part_ids[0])
await a.locator('.order-item', { hasText: part1.product_name }).first().click()
await a.getByTestId('pay-button').click()
r.check('6F.6: a part can\'t be split again (no "Split the amount")', await a.getByTestId('pay-split').count() === 0)
await a.getByRole('button', { name: /Paid/ }).last().click()
const paidOne = await waitFor(async () => { const o = await get(); return o.items.find(i => i.id === part1.id)?.status === 'paid' && o }, 10_000, 500)
r.check('6F.6: one part paid like any line; Undo is gone', !!paidOne && paidOne.split_bills[0].can_undo === false
&& await a.getByTestId('split-undo').count() === 0)
const refused = await fetch(`${backend.url}/api/orders/${os.id}/split-bills/${split2.split_bills[0].id}/undo`, { method: 'POST', headers: { Authorization: `Bearer ${boss}` } })
r.check('6F.6: undo refused once a part is paid', refused.status === 409)
await api('POST', `/api/orders/${os.id}/pay`, { token: boss, body: { item_ids: [split2.split_bills[0].part_ids[1]], payment_method: 'card' } })
await api('POST', `/api/orders/${os.id}/close`, { token: boss }).catch(() => {})
await setting(boss, 'payments.split_amount', 'off')
}
// ── 4.8: the owner's choices: combine lines, close with unpaid items, seats ───────── // ── 4.8: the owner's choices: combine lines, close with unpaid items, seats ─────────
const t6 = free.find(t => t.id !== t4.id && t.id !== t5.id) const t6 = free.find(t => t.id !== t4.id && t.id !== t5.id)
const o6 = await api('POST', '/api/orders/', { token: tokenA, body: { table_id: t6.id } }) const o6 = await api('POST', '/api/orders/', { token: tokenA, body: { table_id: t6.id } })
+10 -2
View File
@@ -5,6 +5,7 @@ import { useTranslation } from '@xenia/i18n'
import { fade } from '../logic/colour' import { fade } from '../logic/colour'
import OneMore from './OneMore' import OneMore from './OneMore'
import { canOneMore } from '../logic/lines' import { canOneMore } from '../logic/lines'
import { countsInTotal, isPart, isSettled } from '../logic/split'
const fmtPrice = money const fmtPrice = money
@@ -403,7 +404,14 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
].filter(Boolean).join(' ')} ].filter(Boolean).join(' ')}
style={nameColor ? { color: nameColor } : undefined} style={nameColor ? { color: nameColor } : undefined}
> >
{item.product?.name || `#${item.product_id}`} {(isPart(item) ? item.product_name : item.product?.name) || `#${item.product_id}`}
{isSettled(item) && (
<span data-testid="item-settled" title={t('split.settledHint')}
style={{ marginLeft: 6, fontSize: 10, fontWeight: 800, padding: '1px 5px', borderRadius: 4, verticalAlign: 'middle',
background: 'rgb(var(--x-info-rgb) / 0.15)', color: 'var(--x-info)', border: '1px solid rgb(var(--x-info-rgb) / 0.35)' }}>
➗ {t('split.settled')}
</span>
)}
{courseBadge} {courseBadge}
{sourceBadge} {sourceBadge}
{moved && ( {moved && (
@@ -696,7 +704,7 @@ export default function OrderSummary({ order, selectable = false, selectedIds =
const orderItemLayout = useTableViewStore(s => s.orderItemLayout || 'compact') const orderItemLayout = useTableViewStore(s => s.orderItemLayout || 'compact')
const activeItems = order.items?.filter(i => i.status !== 'cancelled') || [] const activeItems = order.items?.filter(i => i.status !== 'cancelled') || []
const total = activeItems const total = activeItems
.filter(i => i.status !== 'cancelled') .filter(countsInTotal) // 6F.6: a split bill's settled lines are counted through its parts
.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0) .reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
const paidTotal = activeItems const paidTotal = activeItems
.filter(i => i.status === 'paid') .filter(i => i.status === 'paid')
@@ -0,0 +1,113 @@
// Split the bill by amount (plan 6F.6): the chosen lines become one amount, cut into equal parts
// (pre-filled with the table's customers) or, for two parts, any ratio (a slider or part 1 typed).
// The server settles the lines and adds the parts; each part is then paid like any line.
import { useState } from 'react'
import { parseNumber, useTranslation } from '@xenia/i18n'
import { money } from '../i18n'
import { defaultParts, splitAmounts } from '../logic/split'
export default function SplitAmountModal({ total, count, choices, customerCount, busy, error, onSplit, onClose }) {
const { t } = useTranslation('waiter')
const [parts, setParts] = useState(() => defaultParts(customerCount, choices.maxParts))
const [mode, setMode] = useState('equal')
const [pct, setPct] = useState(50)
const [typed, setTyped] = useState('')
const custom = mode === 'custom' && parts === 2
const typedAmount = typed.trim() ? parseNumber(typed, { decimals: 2, allowNegative: false }) : null
const first = custom ? (typedAmount ?? Math.round(total * pct) / 100) : null
const amounts = splitAmounts(total, custom ? 'custom' : 'equal', parts, first)
const step = d => { setParts(p => Math.max(2, Math.min(choices.maxParts, p + d))); setMode('equal') }
const round = { width: 48, height: 48, borderRadius: '50%', border: '1.5px solid var(--border)', background: 'var(--bg3)', fontSize: 24, fontWeight: 700, color: 'var(--text)', cursor: 'pointer' }
const tab = on => ({
flex: 1, padding: '9px 0', borderRadius: 10, fontSize: 13, fontWeight: 700, cursor: 'pointer',
border: `2px solid ${on ? 'var(--x-info)' : 'rgb(var(--x-ink-rgb) / 0.1)'}`,
background: on ? 'rgb(var(--x-info-rgb) / 0.18)' : 'rgb(var(--x-ink-rgb) / 0.04)',
color: on ? 'var(--x-info-ink)' : 'var(--x-ink-2)',
})
return (
<div className="modal-overlay" onClick={busy ? undefined : onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="split-sheet">
<div className="modal-handle" />
<h2 className="modal-title">{t('split.title')}</h2>
<p style={{ textAlign: 'center', color: 'var(--x-ink-2)', margin: '0 0 2px' }}>{t('split.items', { count })}</p>
<p style={{ textAlign: 'center', color: 'var(--x-warning)', fontSize: 26, fontWeight: 800, margin: '0 0 14px' }}>{money(total)}</p>
{choices.maxParts > 2 && (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, marginBottom: 12 }}>
<button type="button" style={round} onClick={() => step(-1)} disabled={parts <= 2} aria-label={t('split.fewer')} data-testid="split-fewer">−</button>
<div style={{ textAlign: 'center', minWidth: 90 }}>
<div style={{ fontSize: 34, fontWeight: 800 }} data-testid="split-parts">{parts}</div>
<div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 700 }}>{t('split.partsLabel')}</div>
</div>
<button type="button" style={round} onClick={() => step(1)} disabled={parts >= choices.maxParts} aria-label={t('split.more')} data-testid="split-more">+</button>
</div>
)}
{choices.custom && parts === 2 && (
<div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
<button type="button" style={tab(mode === 'equal')} onClick={() => setMode('equal')} data-testid="split-equal">{t('split.equal')}</button>
<button type="button" style={tab(mode === 'custom')} onClick={() => setMode('custom')} data-testid="split-custom">{t('split.custom')}</button>
</div>
)}
{custom && (
<div style={{ marginBottom: 12 }}>
<input type="range" min={1} max={99} value={pct} aria-label={t('split.ratio')} data-testid="split-ratio"
onChange={e => { setPct(Number(e.target.value)); setTyped('') }} style={{ width: '100%' }} />
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--muted)', fontWeight: 700 }}>
<span>{typedAmount == null ? `${pct}%` : ''}</span><span>{typedAmount == null ? `${100 - pct}%` : ''}</span>
</div>
<label style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8, fontSize: 14 }}>
<span style={{ flex: 1 }}>{t('split.firstAmount')}</span>
<input type="text" inputMode="decimal" value={typed} onChange={e => setTyped(e.target.value)} placeholder="0,00"
data-testid="split-first" style={{ width: 110, padding: '8px 10px', borderRadius: 10, border: '1px solid var(--border)', background: 'var(--bg3)', color: 'var(--text)', fontSize: 16, textAlign: 'right' }} />
</label>
</div>
)}
<div style={{ background: 'var(--bg3)', border: '1px solid var(--border)', borderRadius: 12, padding: '8px 12px', marginBottom: 12 }} data-testid="split-preview">
{amounts ? amounts.map((a, n) => (
<div key={n} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, padding: '3px 0' }}>
<span>{t('split.part', { n: n + 1, of: amounts.length })}</span><strong>{money(a)}</strong>
</div>
)) : <p style={{ margin: 0, fontSize: 13, color: 'var(--x-danger)' }}>{t('split.invalid')}</p>}
</div>
<p style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center', margin: '0 0 12px' }}>{t('split.howItWorks')}</p>
{error && <p role="alert" style={{ color: 'var(--x-danger)', fontSize: 13, textAlign: 'center', margin: '0 0 10px' }}>{error}</p>}
<div style={{ display: 'flex', gap: 10 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose} disabled={busy}>{t('common.cancel')}</button>
<button className="btn btn--primary" style={{ flex: 1 }} disabled={busy || !amounts} data-testid="split-confirm"
onClick={() => onSplit(custom ? { mode: 'custom', parts: 2, first_amount: amounts[0] } : { mode: 'equal', parts })}>
{t('split.confirm', { count: amounts?.length ?? parts })}
</button>
</div>
</div>
</div>
)
}
/** The order's split bills above its lines: the parts, how much is paid, and Undo while nothing is. */
export function SplitBills({ bills, canUndo, onUndo }) {
const { t } = useTranslation('waiter')
if (!bills?.length) return null
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, margin: '8px 12px' }}>
{bills.map(b => (
<div key={b.id} data-testid="split-bill" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 12,
background: 'rgb(var(--x-info-rgb) / 0.1)', border: '1px solid rgb(var(--x-info-rgb) / 0.3)' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 700, fontSize: 14 }}>{t('split.bill', { count: b.parts, total: money(b.total) })}</div>
<div style={{ fontSize: 12, color: 'var(--x-ink-2)' }}>
{t('split.billPaid', { paid: money(b.paid), due: money(Math.max(0, b.total - b.paid)) })}
</div>
</div>
{canUndo && b.can_undo && (
<button type="button" className="btn btn--secondary" style={{ padding: '6px 12px', fontSize: 13 }} onClick={() => onUndo(b)} data-testid="split-undo">
{t('split.undo')}
</button>
)}
</div>
))}
</div>
)
}
+14
View File
@@ -0,0 +1,14 @@
// The venue's payments.split_amount / split_max_parts (6F.6, logic/split.js), from the shared settings request.
import { useEffect, useState } from 'react'
import { getVenueSettings } from '../api/venueSettings'
import { splitChoices, splitLevel, splitMax } from '../logic/split'
export function useSplitChoices() {
const [choices, setChoices] = useState(() => splitChoices('off', 10))
useEffect(() => {
let alive = true
getVenueSettings().then(r => { if (alive) setChoices(splitChoices(splitLevel(r.data), splitMax(r.data))) }).catch(() => {})
return () => { alive = false }
}, [])
return choices
}
+2
View File
@@ -0,0 +1,2 @@
// Split the bill by amount (plan 6F.6): the shared rules, @xenia/ordering/split.
export * from '@xenia/ordering/split'
+52 -2
View File
@@ -23,6 +23,9 @@ import MoveHistory, { MovedOrderBanner } from '../components/MoveHistory'
import QuantityModal from '../components/QuantityModal' import QuantityModal from '../components/QuantityModal'
import { useQuantityMode } from '../hooks/useQuantityMode' import { useQuantityMode } from '../hooks/useQuantityMode'
import { canChangeQuantity } from '../logic/lines' import { canChangeQuantity } from '../logic/lines'
import SplitAmountModal, { SplitBills } from '../components/SplitAmountModal'
import { useSplitChoices } from '../hooks/useSplitChoices'
import { isPart, isSettled } from '../logic/split'
import { usePriceRules } from '../hooks/usePriceRules' import { usePriceRules } from '../hooks/usePriceRules'
import { fade } from '../logic/colour' import { fade } from '../logic/colour'
import SeatsHint from '../components/SeatsHint' import SeatsHint from '../components/SeatsHint'
@@ -42,6 +45,7 @@ function combineIds(items) {
// Returns a stable string key for grouping under MERGE_IDENTICAL // Returns a stable string key for grouping under MERGE_IDENTICAL
function identicalKey(item) { function identicalKey(item) {
if (isPart(item)) return `part|${item.id}` // 6F.6: each part is paid on its own
const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4) const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4)
const opts = (() => { try { return item.selected_options ?? '[]' } catch { return '[]' } })() const opts = (() => { try { return item.selected_options ?? '[]' } catch { return '[]' } })()
const removed = (() => { try { return item.removed_ingredients ?? '[]' } catch { return '[]' } })() const removed = (() => { try { return item.removed_ingredients ?? '[]' } catch { return '[]' } })()
@@ -51,6 +55,7 @@ function identicalKey(item) {
// Returns a grouping key for MERGE_SAME_ITEM (ignores options/removed/notes, only product + price) // Returns a grouping key for MERGE_SAME_ITEM (ignores options/removed/notes, only product + price)
function sameItemKey(item) { function sameItemKey(item) {
if (isPart(item)) return `part|${item.id}`
const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4) const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4)
return `${item.product_id}|${effPrice}` return `${item.product_id}|${effPrice}`
} }
@@ -964,7 +969,7 @@ function CancelConfirmModal({ itemCount, onConfirm, onClose }) {
) )
} }
function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, onConfirm, onClose }) { function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, onConfirm, onSplit, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const { paymentSafety } = usePaymentSettingsStore() const { paymentSafety } = usePaymentSettingsStore()
const [method, setMethod] = useState('cash') const [method, setMethod] = useState('cash')
@@ -1033,6 +1038,14 @@ function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, o
</div> </div>
)} )}
{/* 6F.6: split the amount instead of paying it all now */}
{onSplit && (
<button type="button" className="btn btn--secondary" data-testid="pay-split"
style={{ width: '100%', marginBottom: 12 }} onClick={() => onSplit(payTotal)}>
➗ {t('split.button')}
</button>
)}
<div style={{ display: 'flex', gap: 12 }}> <div style={{ display: 'flex', gap: 12 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}> <button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>
{t('common.cancel')} {t('common.cancel')}
@@ -1209,6 +1222,12 @@ export default function TableDetailPage() {
const [qtyItem, setQtyItem] = useState(null) const [qtyItem, setQtyItem] = useState(null)
const [qtyError, setQtyError] = useState('') const [qtyError, setQtyError] = useState('')
const [qtyBusy, setQtyBusy] = useState(false) const [qtyBusy, setQtyBusy] = useState(false)
// 6F.6: split the bill by amount
const splitChoices = useSplitChoices()
const splitAccess = useAllowed('ordering.payments.split_amount')
const [splitTarget, setSplitTarget] = useState(null) // { ids, total }
const [splitBusy, setSplitBusy] = useState(false)
const [splitError, setSplitError] = useState('')
const [cancelConfirm, setCancelConfirm] = useState(null) // null | { mode: 'items', ids: [...] } | { mode: 'order' } const [cancelConfirm, setCancelConfirm] = useState(null) // null | { mode: 'items', ids: [...] } | { mode: 'order' }
const [paidSelectedIds, setPaidSelectedIds] = useState([]) const [paidSelectedIds, setPaidSelectedIds] = useState([])
@@ -1415,7 +1434,7 @@ export default function TableDetailPage() {
} }
const activeItems = order?.items?.filter(i => i.status === 'active') || [] const activeItems = order?.items?.filter(i => i.status === 'active') || []
const paidItems = order?.items?.filter(i => i.status === 'paid') || [] const paidItems = order?.items?.filter(i => i.status === 'paid' || isSettled(i)) || [] // 6F.6: settled by a split bill
const allPaid = order && activeItems.length === 0 const allPaid = order && activeItems.length === 0
const canInteract = !!order const canInteract = !!order
@@ -1955,6 +1974,13 @@ export default function TableDetailPage() {
{activeTab === 'active' && ( {activeTab === 'active' && (
<> <>
<MovedOrderBanner moves={moves.order} onOpen={() => setMoveSheet({ title: t('moves.orderTitle'), moves: moves.order })} /> <MovedOrderBanner moves={moves.order} onOpen={() => setMoveSheet({ title: t('moves.orderTitle'), moves: moves.order })} />
<SplitBills bills={order.split_bills} canUndo={splitAccess !== 'no' && !isOffline} onUndo={async bill => {
try {
await client.post(`/api/orders/${order.id}/split-bills/${bill.id}/undo`)
setSelectedIds([])
await load()
} catch (err) { setError(apiError(err, t('split.err.undo'))) }
}} />
<OrderSummary <OrderSummary
order={{ ...order, items: displayActiveItems }} order={{ ...order, items: displayActiveItems }}
selectable={canInteract && !paying} selectable={canInteract && !paying}
@@ -2423,10 +2449,34 @@ export default function TableDetailPage() {
activeItems={displayActiveItems} activeItems={displayActiveItems}
cardEnabled={cardEnabled} cardEnabled={cardEnabled}
onConfirm={(method) => paySelected(method, false)} onConfirm={(method) => paySelected(method, false)}
onSplit={splitChoices.on && splitAccess !== 'no' && !isOffline
&& !expandIds(selectedIds.length === 0 ? displayActiveItems.map(i => i.id) : selectedIds).some(id => isPart(activeItems.find(i => i.id === id)))
? total => {
setConfirmPay(false)
setSplitError('')
setSplitTarget({ ids: expandIds(selectedIds.length === 0 ? displayActiveItems.map(i => i.id) : selectedIds), total })
} : undefined}
onClose={() => setConfirmPay(false)} onClose={() => setConfirmPay(false)}
/> />
)} )}
{/* 6F.6: split the amount into parts */}
{splitTarget && (
<SplitAmountModal total={splitTarget.total} count={splitTarget.ids.length} choices={splitChoices}
customerCount={customerCount} busy={splitBusy} error={splitError}
onClose={() => setSplitTarget(null)}
onSplit={async body => {
setSplitBusy(true); setSplitError('')
try {
await client.post(`/api/orders/${order.id}/split-bills`, { item_ids: splitTarget.ids, ...body })
setSplitTarget(null)
setSelectedIds([])
setVirtualItems(null)
await load()
} catch (err) { setSplitError(apiError(err, t('split.err.split'))) } finally { setSplitBusy(false) }
}} />
)}
{/* Pay-and-close confirmation */} {/* Pay-and-close confirmation */}
{confirmPayAndClose && ( {confirmPayAndClose && (
<PayConfirmModal <PayConfirmModal