diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index afe91ca..6860fed 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -230,6 +230,13 @@ CODES: dict[str, tuple[int, str]] = { "order.quantity_line": (400, "This line's quantity can't be changed here."), "order.price_change_sent_off": (403, "Prices can only be changed before the items are sent."), "order.price_reason_required": (400, "Say why the price changes."), + "split.not_allowed": (403, "Splitting a bill this way isn't turned on for this venue."), + "split.lines_changed": (409, "Some of these items were paid or changed meanwhile. Look again."), + "split.amount_invalid": (400, "Each part must be more than 0 and less than the total ({total})."), + "split.part_locked": (400, "This is part of a split bill: undo the split to change it."), + "split.not_found": (404, "That split bill isn't there any more."), + "split.paid_already": (409, "A part is already paid or on a tab: the split can't be undone."), + "split.parts_unpaid": (400, "Parts of a split bill are still unpaid: take their payment first."), "order.nothing_paid": (404, "There are no paid items to undo."), "order.cannot_close": (400, "This order can't be closed now ({status})."), "order.no_active_items": (400, "None of these items are on the order any more."), diff --git a/local_backend/core/i18n/el.json b/local_backend/core/i18n/el.json index a0a7341..c2b46a8 100644 --- a/local_backend/core/i18n/el.json +++ b/local_backend/core/i18n/el.json @@ -53,7 +53,8 @@ "paid_total": "Πληρωμενο: {value:.2f}e", "pending": "ΕΚΚΡΕΜΗ:", "remaining": "Εκκρεμει: {value:.2f}e", - "title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ" + "title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ", + "split": "ΔΙΑΧΩΡΙΣΜΟΣ (ΕΞΟΦΛΕΙΤΑΙ ΑΠΟ ΤΑ ΜΕΡΗ):" }, "ticket": { "compact_guests": " | {count}ατ.", @@ -92,7 +93,8 @@ } }, "system_product": { - "delivery_fee": "Μεταφορικά" + "delivery_fee": "Μεταφορικά", + "split_part": "Διαχωρισμός λογαριασμού" }, "qr": { "order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.", @@ -104,5 +106,8 @@ "order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.", "order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.", "bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό." + }, + "split": { + "part_name": "Μέρος λογαριασμού {n}/{of}" } } diff --git a/local_backend/core/i18n/en.json b/local_backend/core/i18n/en.json index 227ecc3..df58448 100644 --- a/local_backend/core/i18n/en.json +++ b/local_backend/core/i18n/en.json @@ -53,7 +53,8 @@ "paid_total": "Paid: {value:.2f}e", "pending": "PENDING:", "remaining": "Remaining: {value:.2f}e", - "title": "ORDER SUMMARY" + "title": "ORDER SUMMARY", + "split": "SPLIT BILL (SETTLED BY THE PARTS):" }, "ticket": { "compact_guests": " | {count}pax", @@ -92,7 +93,8 @@ } }, "system_product": { - "delivery_fee": "Delivery fee" + "delivery_fee": "Delivery fee", + "split_part": "Split bill" }, "qr": { "order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.", @@ -104,5 +106,8 @@ "order_sent": "Table {table} ordered from the tablet ({count} items): sent to the kitchen.", "order_waiting": "Table {table} ordered from the tablet ({count} items): confirm it on the table.", "bill_message": "Table {table}: the guests ask for the bill." + }, + "split": { + "part_name": "Split bill {n}/{of}" } } diff --git a/local_backend/migrations/versions/0050_split_bills.py b/local_backend/migrations/versions/0050_split_bills.py new file mode 100644 index 0000000..2d89950 --- /dev/null +++ b/local_backend/migrations/versions/0050_split_bills.py @@ -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') diff --git a/local_backend/models/order.py b/local_backend/models/order.py index 9729618..48ea8ce 100644 --- a/local_backend/models/order.py +++ b/local_backend/models/order.py @@ -136,6 +136,9 @@ class OrderItem(Base): # the line this one was cut from (6F.4): a split, a lowered quantity, a split payment; its moves # before the cut are this line's too (services/moves.py) split_from_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True) + # a split bill (6F.6): on the lines it settled (status "split") and on its part lines (the + # system product split_part, paid like any line); services/split_bills.py + split_bill_id = Column(Integer, ForeignKey("split_bills.id"), nullable=True, index=True) order = relationship("Order", back_populates="items") product = relationship("Product", back_populates="order_items") @@ -295,3 +298,23 @@ class OrderMoveItem(Base): quantity = Column(Float, nullable=True) move = relationship("OrderMove", back_populates="items") + + +class SplitBill(Base): + """A bill split by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py): chosen lines + settled together (status "split") and cut into `parts` part lines that are paid on their own. + Undone (undone_at) only while no part was paid or put on a tab.""" + __tablename__ = "split_bills" + + id = Column(Integer, primary_key=True, index=True) + order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True) + total = Column(Float, nullable=False) + mode = Column(String, nullable=False) # equal | custom + parts = Column(Integer, nullable=False) + amounts = Column(Text, nullable=False) # JSON [4.5, 10.5]: each part, in order + created_by = Column(Integer, ForeignKey("users.id"), nullable=True) + created_at = Column(UTCDateTime, default=utcnow, nullable=False) + business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True) + undone_at = Column(UTCDateTime, nullable=True) + undone_by = Column(Integer, ForeignKey("users.id"), nullable=True) + receipt_issued_at = Column(UTCDateTime, nullable=True) # the fiscal receipt of the settled lines (last part paid) diff --git a/local_backend/modules/ordering/manifest.py b/local_backend/modules/ordering/manifest.py index ff0d724..b71ee92 100644 --- a/local_backend/modules/ordering/manifest.py +++ b/local_backend/modules/ordering/manifest.py @@ -17,6 +17,7 @@ MODULE = Module( Perm('ordering.prices.view_changes', 'See the prices changed by hand (who, when, why)', roles=('owner', 'store_manager')), Perm('ordering.refunds', 'Refund payments from other shifts', roles=('owner', 'store_manager'), overridable=True), Perm('ordering.payments.revert', 'Turn paid items back to unpaid', roles=('owner', 'store_manager'), overridable=True), + Perm('ordering.payments.split_amount', 'Split a bill by amount (equal parts or a ratio)', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter'), overridable=True), Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')), ), settings=( @@ -32,6 +33,8 @@ MODULE = Module( SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'), SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'), SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'), + SettingDef('payments.split_amount', 'off', "Splitting a bill by amount (6F.6), each level with the ones before: 'off' | 'two_equal' (half and half) | 'two_custom' (two parts in any ratio) | 'multiple_equal' (2 to payments.split_max_parts equal parts). Who may: ordering.payments.split_amount.", type='enum', choices=('off', 'two_equal', 'two_custom', 'multiple_equal')), + SettingDef('payments.split_max_parts', '10', 'The most equal parts a bill can be split into (6F.6, 2-50).', type='int'), SettingDef('payments.card_enabled', 'false', "Allow waiters to record card payments (in addition to cash): 'true' | 'false'", type='bool'), SettingDef('print.alert_after_failures', '2', 'Tell managers when a kitchen/bar ticket has failed to print this many times and is still retrying (0 = never; they are always told when a ticket is finally given up).', type='int'), SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'), diff --git a/local_backend/routers/business_day.py b/local_backend/routers/business_day.py index f9a3a26..e993eb5 100644 --- a/local_backend/routers/business_day.py +++ b/local_backend/routers/business_day.py @@ -312,8 +312,9 @@ def business_day_summary( if o.table_id: waiter_tables.setdefault(o.opened_by, set()).add(o.table_id) + from services.split_bills import is_part for item in all_items: - if item.status == "cancelled": + if item.status == "cancelled" or is_part(item): # 6F.6: a split bill's parts are money, not items ordered continue e = _waiter_entry(item.added_by) e["items_ordered"] += item.quantity @@ -407,7 +408,8 @@ def business_day_summary( for item in o.items: if item.status == "cancelled": continue - entry["items"] += item.quantity + if not is_part(item): + entry["items"] += item.quantity if item.status == "paid": entry["revenue"] += gross(item) diff --git a/local_backend/routers/menu_tablet.py b/local_backend/routers/menu_tablet.py index 54aaf65..fe835e0 100644 --- a/local_backend/routers/menu_tablet.py +++ b/local_backend/routers/menu_tablet.py @@ -299,7 +299,7 @@ def bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet" return {"lines": [], "total": 0, "paid": 0, "due": 0} lines = [] for i in order.items: - if i.status == "cancelled": + if i.status in ("cancelled", "split"): # 6F.6: a split bill's parts stand for the lines it settled continue unit = (i.unit_price or 0) + (i.price_adjustment or 0) texts = menu_languages.product_texts(i.product, customer=False) if i.product else {} diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index f246761..9265e63 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -61,6 +61,7 @@ from core.access.deps import require from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket from models.settings import PosSettings from services.ws_bus import broadcast_sync +from services import split_bills router = APIRouter() @@ -370,6 +371,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends "deal_id": i.deal_id, "linked_item_id": i.linked_item_id, "split_from_id": i.split_from_id, # 6F.4: the line it was cut from "cancel_reason": i.cancel_reason, + "split_bill_id": i.split_bill_id, # 6F.6: settled into a split bill (status split) or one of its parts } def fmt_log(l): @@ -422,6 +424,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends "requested_for": _iso(order.requested_for), "online_delivery_area": order.online_delivery_area, "items": [fmt_item(i) for i in order.items], + "split_bills": [split_bills.bill_out(b, order.items) for b in split_bills.live_bills(db, order.id)], # 6F.6 "waiters": [{"waiter_id": w.waiter_id} for w in order.waiters], "audit_logs": [fmt_log(l) for l in order.audit_logs], } @@ -923,6 +926,9 @@ def cancel_item( raise XeniaError("order.item_not_found") if item.status == "paid": raise XeniaError("order.item_paid") + if item.status not in ("active", "ready"): + raise XeniaError("order.item_not_active") + split_bills.refuse_parts([item]) # 6F.6: undo the split instead now = utcnow() item.status = "cancelled" @@ -973,10 +979,13 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio OrderItem.status.in_(["active", "ready"]), # ready items are also payable ).all() - # Fiscal validation: if enabled, all items must have VAT group assigned before payment + # Fiscal validation: if enabled, all items must have VAT group assigned before payment. + # A split bill's parts (6F.6) aren't on a receipt themselves: the settled lines are, once the + # last part is paid (checked when the bill was made). fiscal_on = is_fiscal_enabled(db) - if fiscal_on and items: - missing = validate_items_for_fiscal(items, db) + own = [i for i in items if not split_bills.is_part(i)] + if fiscal_on and own: + missing = validate_items_for_fiscal(own, db) if missing: names = ", ".join(missing) raise XeniaError("pos.fiscal_vat_missing", names=names) @@ -1020,7 +1029,12 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio order.closed_by = user.id auto_closed = True - if fiscal_on and items: + bills_due = split_bills.receipts_due(db, items) # 6F.6: the last part of a split bill + for due in bills_due: + _audit(db, order_id, "SPLIT_SETTLED", waiter_id=user.id, item_ids=[i.id for i in due["lines"]], + amount=due["bill"].total, note=" + ".join(f"{p['method']} {p['amount']:.2f}" for p in due["payments"])) + fiscal_sent = fiscal_on and (bool(own) or bool(bills_due)) + if fiscal_sent: order.fiscal_status = "pending" db.commit() @@ -1028,18 +1042,25 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio if auto_closed: broadcast_sync("order_closed", {"order_id": order_id, "table_id": order.table_id, "auto_closed": True}) - if fiscal_on and items: + if fiscal_on and own: from database import SessionLocal - fiscal_items = build_fiscal_items(items) - send_fiscal_receipt_background(fiscal_items, effective_method, total_paid, db, + fiscal_items = build_fiscal_items(own) + own_total = sum((i.unit_price + (i.price_adjustment or 0.0)) * i.quantity for i in own) + send_fiscal_receipt_background(fiscal_items, effective_method, own_total, db, order_id=order_id, db_factory=SessionLocal, timeout_seconds=60) + if fiscal_on: + from database import SessionLocal + for due in bills_due: # the settled lines as if paid normally, with each method's amount (Q-3) + send_fiscal_receipt_background(build_fiscal_items(due["lines"]), effective_method, due["bill"].total, db, + order_id=order_id, db_factory=SessionLocal, timeout_seconds=60, + payments=due["payments"]) return { "status": order.status, "paid_item_ids": paid_ids, "auto_closed": auto_closed, - "fiscal": "pending" if fiscal_on and items else None, + "fiscal": "pending" if fiscal_sent else None, } @@ -1100,6 +1121,8 @@ def close_order(order_id: int, request: Request, db: Session = Depends(get_db), raise XeniaError("order.not_yours") if order.status not in ("paid", "open", "partially_paid"): raise XeniaError("order.cannot_close", status=order.status) + if split_bills.has_unpaid_parts(db, order_id): # 6F.6: never written off: the settled lines were sold + raise XeniaError("split.parts_unpaid") now = utcnow() @@ -1256,6 +1279,8 @@ def cancel_order( if not is_manager and not _waiter_can_cancel(user, db): # a manager may approve this one cancellation with their PIN (D-10) approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}") + if split_bills.has_unpaid_parts(db, order_id): # 6F.6: undo the split first + raise XeniaError("split.parts_unpaid") now = utcnow() @@ -1319,11 +1344,12 @@ def cancel_items_bulk( OrderItem.order_id == order_id, ).all() + split_bills.refuse_parts(items) # 6F.6: undo the split instead now = utcnow() cancelled_ids = [] skipped_paid = [] for item in items: - if item.status == "paid": + if item.status not in ("active", "ready"): # paid, on a tab, settled by a split bill (6F.6) skipped_paid.append(item.id) continue item.status = "cancelled" @@ -1436,6 +1462,8 @@ def print_order( if item.status == "cancelled": continue product_name = item.product.name if item.product else f"#{item.product_id}" + if item.split_bill_id is not None and item.status != "split": + product_name = item.product_name # 6F.6: "Split bill 1/3" adj = getattr(item, 'price_adjustment', 0.0) or 0.0 effective_price = item.unit_price + adj items_data.append({ @@ -1447,7 +1475,7 @@ def print_order( "status": item.status, }) - grand_total = sum(i["total"] for i in items_data) + grand_total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them receipt = { "order_id": order.id, @@ -1552,6 +1580,8 @@ def merge_order( for item in source.items: item.order_id = target.id moved_item_ids.append(item.id) + from models.order import SplitBill # 6F.6: a split bill goes with its lines + db.query(SplitBill).filter(SplitBill.order_id == source.id).update({SplitBill.order_id: target.id}, synchronize_session=False) # Copy source waiters to target (no duplicates) existing_waiter_ids = {w.waiter_id for w in target.waiters} @@ -1589,6 +1619,68 @@ def merge_order( return target +# ─── Split the bill by amount (6F.6, services/split_bills.py) ───────────────── + +class SplitBillRequest(BaseModel): + item_ids: List[int] = Field(min_length=1, max_length=500) + mode: str = "equal" # equal | custom (two parts) + parts: int = Field(default=2, ge=2, le=50) + first_amount: Optional[float] = Field(default=None, gt=0, le=1000000) # custom: part 1, part 2 is the rest + + +@router.post("/{order_id}/split-bills") +def create_split_bill(order_id: int, body: SplitBillRequest, request: Request, db: Session = Depends(get_db), + user: User = Depends(get_current_user)): + """Settle the chosen unpaid lines into a split bill and cut it into parts paid on their own + (equal parts, the remainder on the last; or two parts, part 1 typed). The venue's + payments.split_amount decides which splits exist; the key ordering.payments.split_amount (a + manager may approve it once, D-10) who may. The parts are paid with POST /pay like any line.""" + order = db.get(Order, order_id) + if order is None: + raise XeniaError("order.not_found", order_id=order_id) + approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}") + if not _can_access_order(order, user, db): + raise XeniaError("order.not_yours") + if order.status not in ("open", "partially_paid"): + raise XeniaError("order.not_open") + ids = sorted(set(body.item_ids)) + items = db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.id.in_(ids)).order_by(OrderItem.id).all() + if len(items) != len(ids): + raise XeniaError("split.lines_changed") + bill = split_bills.create(db, order, items, mode=body.mode, parts=body.parts, first=body.first_amount, user=user) + amounts = json.loads(bill.amounts) + note = f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts) + approved = _approval_note(approval) + _audit(db, order_id, "SPLIT_CREATED", waiter_id=user.id, item_ids=ids, amount=bill.total, + note=f"{note}; {approved}" if approved else note) + db.commit() + broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_created"}) + db.refresh(order) + return split_bills.bill_out(bill, order.items) + + +@router.post("/{order_id}/split-bills/{bill_id}/undo") +def undo_split_bill(order_id: int, bill_id: int, request: Request, db: Session = Depends(get_db), + user: User = Depends(get_current_user)): + """Undo a split while none of its parts is paid or on a tab (Q-2): the parts are cancelled + ("split undone"), the lines are unpaid again. Same key as splitting.""" + from models.order import SplitBill + order = db.get(Order, order_id) + if order is None: + raise XeniaError("order.not_found", order_id=order_id) + approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}") + if not _can_access_order(order, user, db): + raise XeniaError("order.not_yours") + bill = db.get(SplitBill, bill_id) + if bill is None: + raise XeniaError("split.not_found") + back = split_bills.undo(db, order, bill, user) + _audit(db, order_id, "SPLIT_UNDONE", waiter_id=user.id, item_ids=back, amount=bill.total, note=_approval_note(approval)) + db.commit() + broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_undone"}) + return {"item_ids": back} + + # ─── Split a stacked item into two rows ────────────────────────────────────── @router.post("/{order_id}/items/{item_id}/split", response_model=List[OrderItemOut]) @@ -1787,6 +1879,7 @@ def adjust_item_price( raise XeniaError("order.item_not_found") if item.status != "active": raise XeniaError("order.item_not_active") + split_bills.refuse_parts([item]) # 6F.6 order = db.query(Order).filter(Order.id == order_id).first() if not _can_access_order(order, user, db): @@ -1873,6 +1966,7 @@ def apply_waiter_discount( ).all() if not items: raise XeniaError("order.no_active_items", status=404) + split_bills.refuse_parts(items) # 6F.6 item_unit_prices = {i.id: i.unit_price + i.price_adjustment for i in items} @@ -2100,6 +2194,7 @@ def move_items( ).all() if not items: raise XeniaError("order.no_active_items") + split_bills.refuse_parts(items) # 6F.6: a part stays with its bill from services import moves # 6F.4 moves.record(db, kind="items_moved", source=source, target=target, items=items, user_id=user.id) @@ -2166,6 +2261,8 @@ def print_synopsis( if item.status == "cancelled": continue product_name = item.product.name if item.product else f"#{item.product_id}" + if item.split_bill_id is not None and item.status != "split": + product_name = item.product_name # 6F.6: "Split bill 1/3" adj = getattr(item, 'price_adjustment', 0.0) or 0.0 effective_price = item.unit_price + adj items_data.append({ @@ -2177,7 +2274,7 @@ def print_synopsis( "status": item.status, }) - total = sum(i["total"] for i in items_data) + total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them paid_total = sum(i["total"] for i in items_data if i["status"] == "paid") synopsis = { @@ -2290,6 +2387,7 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db raise XeniaError("order.items_not_combinable", reason="not_found") if any(i.status != "active" for i in items): raise XeniaError("order.items_not_combinable", reason="not_unpaid") + split_bills.refuse_parts(items) # 6F.6 if any(i.deal_id or i.linked_item_id for i in items) or \ db.query(OrderItem).filter(OrderItem.linked_item_id.in_(ids)).first() is not None: raise XeniaError("order.items_not_combinable", reason="deal") diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index d32c71b..4aeb7ca 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -141,10 +141,12 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi by_point = {sp: pos_cart.unit_prices(db, products, sp) for sp in sales_points.IN_PERSON} default = pos_cart.point_for(settings["default_order_type"]) cats = db.query(Category).order_by(Category.sort_order, Category.name).all() - from services import price_changes + from services import price_changes, split_bills return { # + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount - "settings": {**settings, "price_change": price_changes.mode(db)}, + "settings": {**settings, "price_change": price_changes.mode(db), + # 6F.6: splitting a bill by amount (the level and the most equal parts) + "split_amount": split_bills.level(db), "split_max_parts": split_bills.max_parts(db)}, "categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order} for c in cats], "products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON}) @@ -180,14 +182,25 @@ class Payment(BaseModel): lines: Optional[List[int]] = None # indexes into `lines`; None = all of them +class SaleSplit(BaseModel): + """A quick sale split by amount (6F.6, Q-4): the parts and how each is paid, all now.""" + mode: Literal["equal", "custom"] = "equal" + parts: int = Field(default=2, ge=2, le=50) + first_amount: Optional[float] = Field(default=None, gt=0, le=1000000) + methods: List[Literal["cash", "card"]] = Field(min_length=2, max_length=50) # one per part + + class SaleBody(BaseModel): order_type: Literal["takeaway", "here"] = "takeaway" lines: List[dict] = Field(min_length=1, max_length=200) - payments: List[Payment] = Field(min_length=1, max_length=2) + payments: List[Payment] = Field(default_factory=list, max_length=2) # without `split`: at least one + split: Optional[SaleSplit] = None cash_given: Optional[float] = Field(default=None, ge=0, le=100000) def _payment_groups(body: SaleBody, n: int) -> list: + if not body.payments: + raise XeniaError("pos.payment_invalid", reason="lines") if len(body.payments) == 1 and body.payments[0].lines is None: return [(body.payments[0].method, list(range(n)))] seen = [i for pay in body.payments for i in (pay.lines or [])] @@ -211,12 +224,14 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us _require_shift(db, user) orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)] - groups = _payment_groups(body, len(lines)) + groups = _payment_groups(body, len(lines)) if body.split is None else [] approved_by = _check_discounts(request, db, user, lines) _check_fiscal(db, {line.product for line in lines}) priced = pos_cart.price_lines(db, lines, body.order_type) adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)] totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)] + if body.split is not None: + return _split_sale(body, request, db, user, lines, adjs, approved_by, totals) cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2) _check_cash(body.cash_given, cash_due) @@ -239,6 +254,53 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us } +def _split_sale(body, request, db, user, lines, adjs, approved_by, totals): + """A quick sale split by amount (6F.6, Q-4): the order and its lines as any quick sale, then + the lines settled into a split bill and each part paid now by its own method (one payment per + method). The fiscal receipt is the lines themselves, issued with the last part (Q-3).""" + from models.order import OrderItem + from routers import orders as orders_api + from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest + from services import split_bills + sp = body.split + orders_api._need(request, db, user, "ordering.payments.split_amount", target="pos sale") + if len(sp.methods) != sp.parts: + raise XeniaError("pos.payment_invalid", reason="lines") + if not split_bills.allowed(split_bills.level(db), sp.mode, sp.parts, split_bills.max_parts(db)): + raise XeniaError("split.not_allowed") + total = round(sum(totals), 2) + if total < 0.01 * sp.parts: + raise XeniaError("split.amount_invalid", total=f"{total:.2f}") + amounts = split_bills.amounts(total, sp.mode, sp.parts, sp.first_amount) + cash_due = round(sum(a for a, m in zip(amounts, sp.methods) if m == "cash"), 2) + _check_cash(body.cash_given, cash_due) + + order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user) + added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user) + items = db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all() + bill = split_bills.create(db, order, items, mode=sp.mode, parts=sp.parts, first=sp.first_amount, user=user) + orders_api._audit(db, order.id, "SPLIT_CREATED", waiter_id=user.id, item_ids=[i.id for i in items], amount=bill.total, + note=f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts)) + db.commit() + parts = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id, OrderItem.status == "active").order_by(OrderItem.id).all() + paid, fiscal = [], None + for method in ("cash", "card"): + ids = [p.id for p, m in zip(parts, sp.methods) if m == method] + if not ids: + continue + res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=ids, payment_method=method), request, db, user) + paid.append({"method": method, "amount": round(sum(a for a, m in zip(amounts, sp.methods) if m == method), 2), + "item_ids": res["paid_item_ids"]}) + fiscal = res.get("fiscal") or fiscal + drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none" + change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None + return { + "order_id": order.id, "total": total, "payments": paid, "split": {"id": bill.id, "amounts": amounts, "methods": sp.methods}, + "cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal, + "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []), + } + + # ── shared checks (3.3b, 3.3c) ───────────────────────────────────────────────── def _require_shift(db, user): @@ -458,7 +520,8 @@ def pos_order_pay(order_id: int, body: OrderPayBody, request: Request, db: Sessi items = {i.id: i for i in db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.id.in_(wanted)).all()} if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()): raise XeniaError("pos.items_changed") - _check_fiscal(db, {i.product for i in items.values()}) + from services.split_bills import is_part + _check_fiscal(db, {i.product for i in items.values() if not is_part(i)}) # 6F.6: the settled lines were checked amount = {pay.method: round(sum(_item_total(items[i]) for i in pay.item_ids), 2) for pay in body.payments} cash_due = amount.get("cash", 0.0) _check_cash(body.cash_given, cash_due) diff --git a/local_backend/routers/reports.py b/local_backend/routers/reports.py index fb4cece..8164bdf 100644 --- a/local_backend/routers/reports.py +++ b/local_backend/routers/reports.py @@ -2,7 +2,7 @@ from core.access.queries import holders_filter from core.errors import XeniaError from core.modules.entitlements import clamp_start, history_floor, history_since, limit from core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow -from services import tab_books +from services import split_bills, tab_books # split_bills: 6F.6, settled lines count, parts never import csv import io import json @@ -164,7 +164,7 @@ def shift_orders_summary( user: User = Depends(require_reports), ): """Items sent (added) per waiter — regardless of payment status.""" - q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) + q = db.query(OrderItem).filter(split_bills.sold_filter()) start = end = None # 6.12a: with a business day there is no window (was a crash) if business_day_id: q = q.join(Order).filter(Order.business_day_id == business_day_id) @@ -496,7 +496,7 @@ def printer_totals( item_ids = [] for item_id in item_ids: item = db.query(OrderItem).filter(OrderItem.id == item_id).first() - if item and item.status in ("active", "paid"): + if item and split_bills.counts_as_sale(item): summary[pid]["items"] += item.quantity val = _item_val(item) summary[pid]["total"] += val @@ -565,7 +565,7 @@ def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, m item_ids = [] for item_id in item_ids: item = db.query(OrderItem).filter(OrderItem.id == item_id).first() - if item and item.status in ("active", "paid"): + if item and split_bills.counts_as_sale(item): items_count += item.quantity val = _item_val(item) grand_total += val @@ -633,7 +633,7 @@ def print_waiter( tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} order_data = [] for o in orders: - active_items = [i for i in o.items if i.status in ("active", "paid")] + active_items = [i for i in o.items if split_bills.counts_as_sale(i)] total = sum(_item_val(i) for i in active_items) order_data.append({ "id": o.id, @@ -648,7 +648,7 @@ def print_waiter( }) items_count = sum( - i.quantity for o in orders for i in o.items if i.status in ("active", "paid") + i.quantity for o in orders for i in o.items if split_bills.counts_as_sale(i) ) grand_total = sum(d["total"] for d in order_data) @@ -778,7 +778,7 @@ def print_products( period_label, period_is_workday = _analytics_period(body, db) # Build sold-item summary - q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) + q = db.query(OrderItem).filter(split_bills.sold_filter()) if body.business_day_id: q = q.join(Order).filter(Order.business_day_id == body.business_day_id) elif body.from_dt and body.to_dt: @@ -837,7 +837,7 @@ def print_categories( period_label, period_is_workday = _analytics_period(body, db) - q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) + q = db.query(OrderItem).filter(split_bills.sold_filter()) if body.business_day_id: q = q.join(Order).filter(Order.business_day_id == body.business_day_id) elif body.from_dt and body.to_dt: @@ -974,7 +974,7 @@ def product_performance( from models.product import Product from models.waste import WasteLog - q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) + q = db.query(OrderItem).filter(split_bills.sold_filter()) _since = history_since(from_dt, 'reports') if _since: q = q.filter(OrderItem.added_at >= _since) @@ -1337,7 +1337,7 @@ def category_performance( ): from models.product import Product, Category - q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) + q = db.query(OrderItem).filter(split_bills.sold_filter()) _since = history_since(from_dt, 'reports') if _since: q = q.filter(OrderItem.added_at >= _since) @@ -1504,7 +1504,7 @@ def printer_history( order_total = sum( _item_val(i) for i in order.items - if i.status in ("active", "paid") + if split_bills.counts_as_sale(i) ) if log.success and log.order_id not in seen_order_totals: seen_order_totals[log.order_id] = order_total @@ -1713,7 +1713,7 @@ def prep_zones_report( q = q.filter(Order.opened_at <= parse_api_datetime(to_dt)) if business_day_id: q = q.filter(Order.business_day_id == business_day_id) - q = q.filter(OrderItem.status.in_(["active", "paid"])) + q = q.filter(split_bills.sold_filter()) items = q.all() # Aggregate per zone @@ -1839,7 +1839,7 @@ def print_prep_zone( q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt)) if body.business_day_id: q = q.filter(Order.business_day_id == body.business_day_id) - q = q.filter(OrderItem.status.in_(["active", "paid"])) + q = q.filter(split_bills.sold_filter()) items = q.all() product_counts: dict[str, dict] = {} diff --git a/local_backend/services/caller_id.py b/local_backend/services/caller_id.py index 7eb6951..8fb82f1 100644 --- a/local_backend/services/caller_id.py +++ b/local_backend/services/caller_id.py @@ -43,7 +43,8 @@ def card(db, customer) -> dict: from models.table import Table orders = db.query(Order).filter(Order.customer_id == customer.id).order_by(Order.opened_at.desc()).all() done = [o for o in orders if o.status in ("closed", "paid")] - live = lambda o: [i for i in o.items if i.status in ("active", "paid")] # noqa: E731 + from services.split_bills import counts_as_sale + live = lambda o: [i for i in o.items if counts_as_sale(i)] # noqa: E731 (6F.6: settled lines, not parts) tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} return { "id": customer.id, "name": customer.name, "nickname": customer.nickname, "phone": customer.phone, diff --git a/local_backend/services/fiscal/__init__.py b/local_backend/services/fiscal/__init__.py index e7033e1..528c2cd 100644 --- a/local_backend/services/fiscal/__init__.py +++ b/local_backend/services/fiscal/__init__.py @@ -125,13 +125,14 @@ def _in_background(db_factory, model, row_id: int, prepare, timeout_seconds: int def send_fiscal_receipt_background(items: list[dict], payment_method: str, total: float, db, order_id: int, - db_factory, timeout_seconds: int = 60) -> None: + db_factory, timeout_seconds: int = 60, payments: list[dict] | None = None) -> None: """Issue the receipt through the venue's driver in a background thread; order.fiscal_status - becomes success or failed when the device answers (or the wait times out).""" + becomes success or failed when the device answers (or the wait times out). `payments` + [{"method", "amount"}]: a receipt paid in several ways (a split bill's parts, 6F.6).""" from models.order import Order driver = driver_for(db) - _in_background(db_factory, Order, order_id, lambda: driver.prepare_receipt(db, items, payment_method, total), - timeout_seconds) + _in_background(db_factory, Order, order_id, + lambda: driver.prepare_receipt(db, items, payment_method, total, payments=payments), timeout_seconds) def send_credit_note_background(items: list[dict], method: str, total: float, db, refund_id: int, original: dict, diff --git a/local_backend/services/fiscal/base.py b/local_backend/services/fiscal/base.py index 071aa44..371c456 100644 --- a/local_backend/services/fiscal/base.py +++ b/local_backend/services/fiscal/base.py @@ -28,8 +28,9 @@ class FiscalDriver: # cashier is told to issue the credit note on the machine itself (owner decision 2026-11-15). credit_notes: bool = False - def prepare_receipt(self, db, items: list[dict], method: str, total: float) -> Send: - """A sales receipt, ready to send.""" + def prepare_receipt(self, db, items: list[dict], method: str, total: float, payments: list[dict] | None = None) -> Send: + """A sales receipt, ready to send. `payments` [{"method", "amount"}] when it was paid in + several ways (a split bill, 6F.6); else all of it by `method`.""" raise NotImplementedError def prepare_credit_note(self, db, items: list[dict], method: str, total: float, original: dict | None = None) -> Send: diff --git a/local_backend/services/fiscal/txt_file.py b/local_backend/services/fiscal/txt_file.py index 4215290..2eeedfe 100644 --- a/local_backend/services/fiscal/txt_file.py +++ b/local_backend/services/fiscal/txt_file.py @@ -62,7 +62,7 @@ def _get_folders(db) -> tuple[str, str]: return out_folder, in_folder -def _build_command_file(items: list[dict], payment_method: str, total: float, db) -> str: +def _build_command_file(items: list[dict], payment_method: str, total: float, db, payments: list[dict] | None = None) -> str: """ Build the fiscal command file content as a string. @@ -98,7 +98,15 @@ def _build_command_file(items: list[dict], payment_method: str, total: float, db if msg_line.strip(): lines.append(f"FM|{i}|{msg_line.upper()}") - if payment_method == "card": + if payments and len(payments) > 1: + # Paid in several ways (a split bill, 6F.6; the driver manual's "multiple ways to close"): + # each card amount through the EFT/POS first, then cash closes the rest. + card = [p for p in payments if p.get("method") == "card" and p.get("amount", 0) > 0] + for p in card: + lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{p['amount']:.2f}") + if round(sum(p.get("amount", 0) for p in payments if p not in card), 2) > 0: + lines.append(f"CR|{clerk_id}") + elif (payments[0].get("method") if payments else payment_method) == "card": total_str = f"{total:.2f}" lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{total_str}") else: @@ -177,11 +185,11 @@ class TxtFileDriver(FiscalDriver): name = "dTEC100extra (text-file bridge)" credit_notes = False - def prepare_receipt(self, db, items, method, total): + def prepare_receipt(self, db, items, method, total, payments=None): out_folder, in_folder = _get_folders(db) os.makedirs(out_folder, exist_ok=True) os.makedirs(in_folder, exist_ok=True) - content = _build_command_file(items, method, total, db) + content = _build_command_file(items, method, total, db, payments) filename = _unique_filename() return lambda timeout_seconds: _write_and_poll(out_folder, in_folder, content, filename, timeout_seconds) diff --git a/local_backend/services/sales.py b/local_backend/services/sales.py index 4895023..3dfb919 100644 --- a/local_backend/services/sales.py +++ b/local_backend/services/sales.py @@ -7,6 +7,10 @@ in every report, on screen, printed and exported. - A line's **value** = (unit price + its price change) × quantity, then **minus what was refunded** of it (services/refunds.py: refunds are per line and quantity, so they come off the line, the product, the category, the table, the hour and the day they belong to). +- **A split bill** (6F.6, services/split_bills.py): the lines it settled (`split`) are sold like + paid lines; its **part lines** are the money for them, never a sale (left out here; the shifts' + drawers, payment methods and tabs count them). A refund of a part comes off the settled lines + by their share of the bill. - **Fees** (lines the system adds, `system_key` set: the delivery fee) are counted apart: they are money taken, but not a product sold. `revenue` everywhere is products only; `fees` is beside it; `takings` = revenue + fees. @@ -17,7 +21,7 @@ from __future__ import annotations from dataclasses import dataclass -SOLD = ("active", "paid", "tabbed") +SOLD = ("active", "paid", "tabbed", "split") def gross(item, quantity: float | None = None) -> float: @@ -58,17 +62,40 @@ def lines(db, items) -> list[Line]: """Sold lines (see the module doc) with their refunds taken off. A line refunded in full stays (quantity 0, value 0) so its refund is counted; `sold()` leaves it out of lists.""" from services.refunds import refunded_quantities - sold = [i for i in items if i.status in SOLD] + from services.split_bills import is_part + sold = [i for i in items if i.status in SOLD and not is_part(i)] back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"]) + shares = _split_refunds(db, {i.split_bill_id for i in sold if i.status == "split"}) fees = _fee_products(db) if sold else set() out = [] for i in sold: - r = min(back.get(i.id, 0.0), i.quantity) + if i.status == "split": + r = i.quantity * shares.get(i.split_bill_id, 0.0) + else: + r = min(back.get(i.id, 0.0), i.quantity) q = max(i.quantity - r, 0.0) out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=i.product_id in fees)) return out +def _split_refunds(db, bill_ids) -> dict[int, float]: + """{split_bill_id: the share of the bill refunded} from its parts' refunds (6F.6).""" + from models.order import OrderItem, SplitBill + from services.refunds import refunded_quantities + ids = {b for b in bill_ids if b is not None} + if not ids: + return {} + parts = db.query(OrderItem).filter(OrderItem.split_bill_id.in_(ids), OrderItem.status == "paid").all() + back = refunded_quantities(db, [p.id for p in parts]) + if not back: + return {} + totals = {b.id: b.total for b in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all()} + value: dict[int, float] = {} + for p in parts: + value[p.split_bill_id] = value.get(p.split_bill_id, 0.0) + gross(p, min(back.get(p.id, 0.0), p.quantity)) + return {b: min(v / totals[b], 1.0) for b, v in value.items() if totals.get(b)} + + @dataclass class Totals: revenue: float = 0.0 # products, net of refunds diff --git a/local_backend/services/split_bills.py b/local_backend/services/split_bills.py new file mode 100644 index 0000000..e18c35f --- /dev/null +++ b/local_backend/services/split_bills.py @@ -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, + } diff --git a/local_backend/services/system_products.py b/local_backend/services/system_products.py index 5b3802e..5661ca3 100644 --- a/local_backend/services/system_products.py +++ b/local_backend/services/system_products.py @@ -21,7 +21,8 @@ from __future__ import annotations from collections import Counter DELIVERY_FEE = "delivery_fee" -KEYS = (DELIVERY_FEE,) +SPLIT_PART = "split_part" # a split bill's part line (6F.6, services/split_bills.py) +KEYS = (DELIVERY_FEE, SPLIT_PART) def _usual_vat_group(db): diff --git a/local_backend/tests/test_pos_refunds.py b/local_backend/tests/test_pos_refunds.py index 66aa7e8..ba237e8 100644 --- a/local_backend/tests/test_pos_refunds.py +++ b/local_backend/tests/test_pos_refunds.py @@ -189,7 +189,7 @@ def test_fiscal_driver_with_credit_notes_issues_one(client, db, till, menu, on_s class Machine(FiscalDriver): key, credit_notes = "test_machine", True - def prepare_receipt(self, db, items, method, total): + def prepare_receipt(self, db, items, method, total, payments=None): return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None} def prepare_credit_note(self, db, items, method, total, original=None): diff --git a/local_backend/tests/test_split_bills.py b/local_backend/tests/test_split_bills.py new file mode 100644 index 0000000..d237d6e --- /dev/null +++ b/local_backend/tests/test_split_bills.py @@ -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 diff --git a/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx b/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx index 16daa0a..c5e0de6 100644 --- a/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx +++ b/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx @@ -69,9 +69,36 @@ function OrderingSettings() { + ) } +/** 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 ( + + + 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) }))} /> + + )} + + ) +} + /** 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). */ function QuantitySettings({ s }) { diff --git a/manager_dashboard/src/pages/orders/OrderPage.jsx b/manager_dashboard/src/pages/orders/OrderPage.jsx index 445341c..972e262 100644 --- a/manager_dashboard/src/pages/orders/OrderPage.jsx +++ b/manager_dashboard/src/pages/orders/OrderPage.jsx @@ -22,7 +22,9 @@ import OrderPeople from './OrderPeople' import PayDialog from './PayDialog' import PrintProblemsCard from './PrintProblemsCard' 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 STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' } @@ -78,6 +80,7 @@ function OrderView({ orderId }) { const venue = useVenue() const [tab, setTab] = useState('order') 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 [printerId, setPrinterId] = useState('') @@ -156,6 +159,7 @@ function OrderView({ orderId }) { + {tab === 'order' && (
@@ -172,6 +176,9 @@ function OrderView({ orderId }) { {tab === 'history' &&
} {paying && 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)} onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />} diff --git a/manager_dashboard/src/pages/orders/PayDialog.jsx b/manager_dashboard/src/pages/orders/PayDialog.jsx index eac2ae0..d7c106c 100644 --- a/manager_dashboard/src/pages/orders/PayDialog.jsx +++ b/manager_dashboard/src/pages/orders/PayDialog.jsx @@ -3,17 +3,20 @@ // "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). import { useState } from 'react' -import { Banknote, CreditCard } from 'lucide-react' +import { Banknote, CreditCard, Divide } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useFormat, useTranslation } from '@xenia/i18n' import { Button, Dialog } from '@xenia/ui' 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 { formatMoney } = useFormat() const [busy, setBusy] = useState(null) const [error, setError] = useState(null) + const [splitting, setSplitting] = useState(false) async function pay(method) { setBusy(method) @@ -44,6 +47,13 @@ export default function PayDialog({ orderId, itemIds, amount, card = true, thenC
{error &&

{error}

} + {split && !splitting && ( + + )} + {split && splitting && ( + setSplitting(false)} onDone={onSplit} /> + )} ) diff --git a/manager_dashboard/src/pages/orders/SplitAmount.jsx b/manager_dashboard/src/pages/orders/SplitAmount.jsx new file mode 100644 index 0000000..7ad68fc --- /dev/null +++ b/manager_dashboard/src/pages/orders/SplitAmount.jsx @@ -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 ( +
+ {choices.maxParts > 2 && ( +
+ step(-1)}> + {parts} + = choices.maxParts} onClick={() => step(1)} data-testid="split-more"> +
+ )} + {choices.custom && parts === 2 && ( +
+ {['equal', 'custom'].map(m => ( + + ))} +
+ )} + {uneven && ( + + )} + {amounts ? ( +
    + {amounts.map((a, i) => ( +
  • {t('orders.split.part', { n: i + 1, of: amounts.length })}{formatMoney(a)}
  • + ))} +
+ ) :

{t('orders.split.invalid')}

} +

{t('orders.split.hint')}

+ {error &&

{error}

} +
+ + +
+
+ ) +} + +/** 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 ( +
+ {bills.map(b => ( +
+ + {t('orders.split.bill', { count: b.parts, total: formatMoney(b.total) })} + {t('orders.split.paid', { paid: formatMoney(b.paid), due: formatMoney(Math.max(0, b.total - b.paid)) })} + + {canUndo && b.can_undo && ( + + )} +
+ ))} +
+ ) +} diff --git a/manager_dashboard/src/pages/orders/orderLogic.js b/manager_dashboard/src/pages/orders/orderLogic.js index ed13a13..6cafe87 100644 --- a/manager_dashboard/src/pages/orders/orderLogic.js +++ b/manager_dashboard/src/pages/orders/orderLogic.js @@ -3,6 +3,8 @@ // items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise // the rest is paid first. +import { splitChoices, splitLevel, splitMax } from '@xenia/ordering/split' + export const OPEN_STATUSES = ['open', 'partially_paid', 'paid'] 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. */ export function venueRules(settings) { 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). */ export function sendBody(cart, note) { return { lines: cart.map(c => c.line), order_note: note?.trim() || null } diff --git a/manager_dashboard/tests/orders.test.mjs b/manager_dashboard/tests/orders.test.mjs index c82ef5a..e680286 100644 --- a/manager_dashboard/tests/orders.test.mjs +++ b/manager_dashboard/tests/orders.test.mjs @@ -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, true), 'writeOff') assert.equal(closeStep({ items: [item(1, 'paid', 5)] }, false), 'close') - assert.deepEqual(venueRules({ 'orders.close_with_unpaid': { value: 'true' } }), { closeWithUnpaid: true, card: true }) - assert.deepEqual(venueRules({ 'payments.card_enabled': { value: 'false' } }), { closeWithUnpaid: false, card: false }) + const off = { on: false, maxParts: 2, custom: 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', () => { diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 02fbc80..669b768 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -375,5 +375,14 @@ "scene": { "not_found": "Η σκηνή δεν βρέθηκε.", "until_past": "Αυτή η ώρα έχει περάσει: διαλέξτε μια μεταγενέστερη." + }, + "split": { + "not_allowed": "Αυτός ο διαχωρισμός λογαριασμού δεν είναι ενεργός σε αυτό το κατάστημα.", + "lines_changed": "Κάποια από αυτά πληρώθηκαν ή άλλαξαν στο μεταξύ. Δείτε ξανά.", + "amount_invalid": "Κάθε μέρος πρέπει να είναι πάνω από 0 και κάτω από το σύνολο ({{total}}).", + "part_locked": "Αυτό είναι μέρος διαχωρισμένου λογαριασμού: αναιρέστε τον διαχωρισμό για να το αλλάξετε.", + "not_found": "Αυτός ο διαχωρισμός δεν υπάρχει πια.", + "paid_already": "Ένα μέρος έχει ήδη πληρωθεί ή μπει σε καρτέλα: ο διαχωρισμός δεν αναιρείται.", + "parts_unpaid": "Μέρη διαχωρισμένου λογαριασμού είναι ακόμα απλήρωτα: πληρώστε τα πρώτα." } } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index d465d41..ad7296d 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -771,6 +771,21 @@ "add_only": "Μόνο προσθήκη", "add_and_remove": "Προσθήκη και αφαίρεση" } + }, + "split": { + "title": "Διαχωρισμός λογαριασμού με ποσά", + "intro": "Το προσωπικό χωρίζει έναν λογαριασμό σε μέρη που πληρώνονται χωριστά: οι γραμμές εξοφλούνται μαζί και κάθε μέρος πληρώνεται μετρητά, με κάρτα ή σε καρτέλα.", + "when": "Το προσωπικό μπορεί να χωρίσει", + "whenHint": "Ποιος: «Τι επιτρέπεται σε κάθε ρόλο» και τα δικαιώματα κάθε ατόμου.", + "whenTip": "Κάθε επιλογή περιλαμβάνει τις προηγούμενες. Μισά μισά: δύο ίσα μέρη. Δύο μέρη, όποια ποσά: και αναλογία ή τι πληρώνει το μέρος 1. Σε ίσα μέρη: από 2 έως το μέγιστο παρακάτω, το υπόλοιπο λεπτό στο τελευταίο μέρος. Ο διαχωρισμός αναιρείται μέχρι να πληρωθεί ένα μέρος. Η απόδειξη είναι οι ίδιες οι γραμμές και τυπώνεται όταν πληρωθεί το τελευταίο μέρος.", + "levels": { + "off": "Καθόλου", + "two_equal": "Μισά μισά", + "two_custom": "Δύο μέρη, όποια ποσά", + "multiple_equal": "Σε ίσα μέρη (και δύο με όποια ποσά)" + }, + "max": "Μέγιστα ίσα μέρη", + "maxHint": "Τα μέρη ξεκινούν από τους πελάτες του τραπεζιού, όταν υπάρχουν." } }, "logs": { @@ -3348,7 +3363,8 @@ "paid": "Πληρώθηκε", "cancelled": "Ακυρώθηκε", "tabbed": "Στην καρτέλα", - "closed": "Απλήρωτο" + "closed": "Απλήρωτο", + "split": "Σε διαχωρισμό" }, "without": "Χωρίς {{list}}", "added": "{{time}} · {{name}}", @@ -3409,7 +3425,10 @@ "PRICE_CHANGED": "Αλλαγή τιμής", "PRICE_SET_BY_HAND": "Τιμή με το χέρι (εγκρίθηκε)", "QUANTITY_CHANGED": "Αλλαγή ποσότητας", - "ITEM_REORDERED": "Άλλο ένα" + "ITEM_REORDERED": "Άλλο ένα", + "SPLIT_CREATED": "Διαχωρισμός λογαριασμού", + "SPLIT_UNDONE": "Αναίρεση διαχωρισμού", + "SPLIT_SETTLED": "Εξόφληση διαχωρισμού" }, "price": { "modifier_applied": "Κανόνας τιμής", @@ -3485,6 +3504,25 @@ "items_moved": "Μεταφορά γραμμών", "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": { diff --git a/packages/i18n/locales/el/modules.json b/packages/i18n/locales/el/modules.json index c834e39..cfab25f 100644 --- a/packages/i18n/locales/el/modules.json +++ b/packages/i18n/locales/el/modules.json @@ -463,7 +463,8 @@ }, "refunds": "Επιστροφή χρημάτων για πληρωμές άλλων βαρδιών", "payments": { - "revert": "Αναίρεση πληρωμής (πληρωμένα → απλήρωτα)" + "revert": "Αναίρεση πληρωμής (πληρωμένα → απλήρωτα)", + "split_amount": "Διαχωρισμός λογαριασμού με ποσά (ίσα μέρη ή αναλογία)" }, "items": { "change_quantity": "Αλλαγή ποσότητας σταλμένης γραμμής (χωρίς νέο δελτίο)" diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index 87db9ca..f33b93d 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -215,7 +215,20 @@ "given": "Μετρητά που δόθηκαν", "exact": "Ακριβώς: {{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": { "paid": "Πληρώθηκαν {{total}}", @@ -281,7 +294,8 @@ "cash": "πληρώθηκε · μετρητά", "card": "πληρώθηκε · κάρτα" }, - "readyItem": "έτοιμο" + "readyItem": "έτοιμο", + "settled": "Στον διαχωρισμό" }, "online": { "arrived_one": "Νέα online παραγγελία", diff --git a/packages/i18n/locales/el/waiter.json b/packages/i18n/locales/el/waiter.json index 9e9e441..7e6253c 100644 --- a/packages/i18n/locales/el/waiter.json +++ b/packages/i18n/locales/el/waiter.json @@ -918,5 +918,33 @@ "noChange": "Αλλάξτε τη με − και +", "onlyUp": "Σε αυτό το κατάστημα οι ποσότητες μόνο αυξάνονται.", "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": "Ο διαχωρισμός δεν αναιρέθηκε." + } } } diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 78007fa..4bcb89a 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -375,5 +375,14 @@ "scene": { "not_found": "Scene not found.", "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." } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index b5d943c..5c93bbf 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -771,6 +771,21 @@ "add_only": "Only add", "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": { @@ -3348,7 +3363,8 @@ "paid": "Paid", "cancelled": "Cancelled", "tabbed": "On the tab", - "closed": "Written off" + "closed": "Written off", + "split": "In a split bill" }, "without": "Without {{list}}", "added": "{{time}} · {{name}}", @@ -3409,7 +3425,10 @@ "PRICE_CHANGED": "Price changed", "PRICE_SET_BY_HAND": "Price set by hand (approved)", "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": { "modifier_applied": "Price rule", @@ -3485,6 +3504,25 @@ "items_moved": "Lines moved", "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": { diff --git a/packages/i18n/locales/en/modules.json b/packages/i18n/locales/en/modules.json index c87dfce..2273e60 100644 --- a/packages/i18n/locales/en/modules.json +++ b/packages/i18n/locales/en/modules.json @@ -463,7 +463,8 @@ }, "refunds": "Refund payments from other shifts", "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": { "change_quantity": "Change a sent line's quantity (no new ticket)" diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index f27e754..e0b967b 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -215,7 +215,20 @@ "given": "Cash given", "exact": "Exact: {{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": { "paid": "Paid {{total}}", @@ -281,7 +294,8 @@ "cash": "paid · cash", "card": "paid · card" }, - "readyItem": "ready" + "readyItem": "ready", + "settled": "In the split bill" }, "online": { "arrived_one": "New online order", diff --git a/packages/i18n/locales/en/waiter.json b/packages/i18n/locales/en/waiter.json index c14bc68..396c9db 100644 --- a/packages/i18n/locales/en/waiter.json +++ b/packages/i18n/locales/en/waiter.json @@ -918,5 +918,33 @@ "noChange": "Use − and + to change it", "onlyUp": "At this venue quantities only go up.", "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." + } } } diff --git a/packages/ordering/package.json b/packages/ordering/package.json index abd23e0..87d6cc4 100644 --- a/packages/ordering/package.json +++ b/packages/ordering/package.json @@ -8,7 +8,8 @@ "exports": { ".": "./src/index.js", "./cart": "./src/cart.js", - "./printProblems": "./src/printProblems.js" + "./printProblems": "./src/printProblems.js", + "./split": "./src/split.js" }, "dependencies": { "@xenia/access": "^0.0.0", diff --git a/packages/ordering/src/index.js b/packages/ordering/src/index.js index 2eeb39d..f3f0232 100644 --- a/packages/ordering/src/index.js +++ b/packages/ordering/src/index.js @@ -6,4 +6,5 @@ export * from './cart.js' export { ProductDialog } from './ProductDialog.jsx' export { useQuote } from './useQuote.js' export * from './printProblems.js' +export * from './split.js' export { PrintProblemsPanel } from './PrintProblemsPanel.jsx' diff --git a/packages/ordering/src/split.js b/packages/ordering/src/split.js new file mode 100644 index 0000000..8e664f2 --- /dev/null +++ b/packages/ordering/src/split.js @@ -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' diff --git a/packages/ordering/tests/split.test.mjs b/packages/ordering/tests/split.test.mjs new file mode 100644 index 0000000..9a342ad --- /dev/null +++ b/packages/ordering/tests/split.test.mjs @@ -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) +}) diff --git a/terminal/src/apps/pos/PaymentDialog.jsx b/terminal/src/apps/pos/PaymentDialog.jsx index d5d5d9e..80ae22c 100644 --- a/terminal/src/apps/pos/PaymentDialog.jsx +++ b/terminal/src/apps/pos/PaymentDialog.jsx @@ -3,27 +3,41 @@ // 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, // 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 { Banknote, Check, CreditCard, Split } from 'lucide-react' +import { Banknote, Check, CreditCard, Divide, Minus, Plus, Split } from 'lucide-react' import { errorMessage } from '@xenia/api' 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 { 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 ${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 }) - * → the result passed to onPaid. `payments` are by row index (splitPayments). */ -export default function PaymentDialog({ total, rows, submit, onPaid, onClose }) { +/** rows: [{ label, total }]; submit({ method: 'cash'|'card'|'split'|'amount', rowMethods, payments, split, cashGiven }) + * → the result passed to onPaid. `payments` are by row index (splitPayments). `amountSplit` + * ({ 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 { formatMoney } = useFormat() const totals = rows.map(r => r.total) const [method, setMethod] = useState('cash') const [split, setSplit] = useState(() => rows.map(() => 'card')) 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 given = givenText.trim() === '' ? null : parseNumber(givenText, { decimals: 2, allowNegative: false }) const change = cashDue > 0 ? changeFor(given ?? cashDue, cashDue) : null @@ -43,8 +57,11 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose }) setBusy(true) setError('') 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 { - 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 display({ mode: 'paid', total, paid: result?.cash_given ?? total, change: result?.change ?? 0 }) onPaid(result) @@ -59,16 +76,18 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose }) - }>
- {[['cash', Banknote], ['card', CreditCard], ['split', Split]].map(([m, Icon]) => ( + {[['cash', Banknote], ['card', CreditCard], ['split', Split], ...(amountSplit ? [['amount', Divide]] : [])].map(([m, Icon]) => ( @@ -99,6 +118,57 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
)} + {method === 'amount' && ( +
+ {maxParts > 2 && ( +
+ { setNParts(n => Math.max(2, n - 1)); setShareMode('equal') }} data-testid="amount-fewer"> + {nParts} + = maxParts} + onClick={() => { setNParts(n => Math.min(maxParts, n + 1)); setShareMode('equal') }} data-testid="amount-more"> +
+ )} + {amountSplit.choices.custom && nParts === 2 && ( +
+ {['equal', 'custom'].map(m => ( + + ))} +
+ )} + {uneven && ( + + )} + {amounts ? ( +
+ {amounts.map((a, i) => ( +
+ {t('pos.pay.part', { n: i + 1, of: amounts.length })} + {formatMoney(a)} + + {['cash', 'card'].map(m => ( + + ))} + +
+ ))} +
+ ) :

{t('pos.pay.splitInvalid')}

} +

{t('pos.pay.amountHint')}

+
+ )} + {method === 'card' &&

{t('pos.pay.cardHint', { amount: formatMoney(total) })}

} {cashDue > 0 && ( diff --git a/terminal/src/apps/pos/PosScreen.jsx b/terminal/src/apps/pos/PosScreen.jsx index 85b7432..d507a44 100644 --- a/terminal/src/apps/pos/PosScreen.jsx +++ b/terminal/src/apps/pos/PosScreen.jsx @@ -14,7 +14,8 @@ import { useEffect, useMemo, useState } from 'react' import { Globe, Info, LayoutGrid, Receipt, Search, ShoppingBag, X } from 'lucide-react' 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 { useLiveEvent } from '../../device/context' 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 const mayDiscount = useCan('ordering.prices.modify') 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 onlineModule = useModule('connect_orders') const handlesOnline = useCan('connect_orders.manage') @@ -249,9 +254,9 @@ function Counter({ menu, t }) {
{atTable - ? - : } + : } )} diff --git a/terminal/src/apps/pos/SaleCart.jsx b/terminal/src/apps/pos/SaleCart.jsx index c6b60f6..ff95605 100644 --- a/terminal/src/apps/pos/SaleCart.jsx +++ b/terminal/src/apps/pos/SaleCart.jsx @@ -11,7 +11,7 @@ import { setLineQty } from './logic/cart' import PaymentDialog from './PaymentDialog' 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 { formatMoney } = useFormat() const toast = useToast() @@ -36,8 +36,10 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, }, [cart, ready, quote.quote, paying, byId, display]) useEffect(() => () => display({ mode: 'idle' }), [display]) - const submit = async ({ method, payments, cashGiven }) => (await client.post('/api/pos/sales', { - order_type: orderType, lines: cart, payments: method === 'split' ? payments : [{ method }], cash_given: cashGiven, + const submit = async ({ method, payments, split, cashGiven }) => (await client.post('/api/pos/sales', { + 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 return ( @@ -76,7 +78,7 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, {paying && quote.quote && ( - ({ label: `${l.quantity}× ${byId.get(l.product_id)?.name ?? ''}`, total: quote.quote.lines[i].total }))} onClose={() => setPaying(false)} onPaid={result => { diff --git a/terminal/src/apps/pos/TablePanel.jsx b/terminal/src/apps/pos/TablePanel.jsx index 38a6a3e..5a55911 100644 --- a/terminal/src/apps/pos/TablePanel.jsx +++ b/terminal/src/apps/pos/TablePanel.jsx @@ -11,13 +11,13 @@ import { Button, Dialog, EmptyState, IconButton, Spinner, useToast } from '@xeni import client from '../../api/client' import CartLine from './CartLine' 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 PaymentDialog from './PaymentDialog' import { PaidSummary } from './SaleCart' 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 { formatMoney, formatTime } = useFormat() const toast = useToast() @@ -75,11 +75,20 @@ export default function TablePanel({ table, cart, setCart, byId, canDiscount, on reload() }) - const payRows = chosen.map(l => ({ id: l.id, label: `${qtyLabel(l.quantity, l.unitType)} ${l.name}`, total: l.total })) - const submitPay = async ({ method, payments, cashGiven }) => (await client.post(`/api/pos/orders/${orderId}/pay`, { - payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }], - cash_given: cashGiven, - })).data + 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, split, cashGiven }) => { + let body + 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 + 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])) @@ -179,6 +188,7 @@ export default function TablePanel({ table, cart, setCart, byId, canDiscount, on {paying && ( r.part) ? { ...amountSplit, customerCount: order?.customer_count } : null} onClose={() => setPaying(null)} onPaid={result => { setPaying(null) @@ -231,7 +241,8 @@ function OrderLine({ line, selected, onToggle }) { {formatMoney(line.total)} - {line.paid && {t(`pos.table.paidBy.${line.method === 'card' ? 'card' : 'cash'}`)}} + {line.paid && !line.settled && {t(`pos.table.paidBy.${line.method === 'card' ? 'card' : 'cash'}`)}} + {line.settled && {t('pos.table.settled')}} {!line.paid && line.kds === 'done' && {t('pos.table.readyItem')}} diff --git a/terminal/src/apps/pos/logic/tables.js b/terminal/src/apps/pos/logic/tables.js index 8660641..ec8f39d 100644 --- a/terminal/src/apps/pos/logic/tables.js +++ b/terminal/src/apps/pos/logic/tables.js @@ -41,25 +41,28 @@ export function optionNames(selected) { } /** 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) { if (!order?.items) return [] 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 => ({ id: i.id, name: i.product_name ?? i.product?.name ?? '', quantity: i.quantity, unitType: i.unit_type, 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, options: optionNames(i.selected_options), notes: i.notes, kds: i.kds_status ?? 'pending', 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 - 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)] } @@ -67,8 +70,16 @@ export function orderLines(order) { /** { total, paid, unpaid, unpaidIds } of the lines. */ export function orderSums(lines) { const sum = ls => round2(ls.reduce((s, l) => s + l.total, 0)) - const open = lines.filter(l => !l.paid) - return { total: sum(lines), paid: sum(lines.filter(l => l.paid)), unpaid: sum(open), unpaidIds: open.map(l => l.id) } + const counted = lines.filter(l => !l.settled) // 6F.6: the parts pay for the settled lines + 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. */ diff --git a/terminal/tests/pos.test.mjs b/terminal/tests/pos.test.mjs index deeb1f4..acca9b7 100644 --- a/terminal/tests/pos.test.mjs +++ b/terminal/tests/pos.test.mjs @@ -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') }) +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 () => { const { findOnline, minutesSince, nextStep } = await import('../src/apps/pos/logic/online.js') assert.deepEqual(nextStep({ status: 'pending_acceptance' }), { kind: 'answer' }) diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 77f7153..63a9b83 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -755,8 +755,18 @@ try { 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') 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) + // 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-save').click() r.check(`${st6} a table flag needs a name`, (await page.getByTestId('flag-dialog').textContent()).includes('Enter a name')) diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index df7097a..37f5c74 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -75,6 +75,7 @@ async function pairFromManager(page, boss, body) { try { 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 } }) 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 @@ -434,6 +435,29 @@ try { await sleep(300) 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 ─ // the phone: Maria's live connection (as the waiter app opens it) and her API calls const phoneEvents = [] diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index 72dcc21..b2bf74e 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -429,6 +429,62 @@ try { 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 ───────── 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 } }) diff --git a/waiter_pwa/src/components/OrderSummary.jsx b/waiter_pwa/src/components/OrderSummary.jsx index 4e291b8..73d3fc7 100644 --- a/waiter_pwa/src/components/OrderSummary.jsx +++ b/waiter_pwa/src/components/OrderSummary.jsx @@ -5,6 +5,7 @@ import { useTranslation } from '@xenia/i18n' import { fade } from '../logic/colour' import OneMore from './OneMore' import { canOneMore } from '../logic/lines' +import { countsInTotal, isPart, isSettled } from '../logic/split' const fmtPrice = money @@ -403,7 +404,14 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd ].filter(Boolean).join(' ')} style={nameColor ? { color: nameColor } : undefined} > - {item.product?.name || `#${item.product_id}`} + {(isPart(item) ? item.product_name : item.product?.name) || `#${item.product_id}`} + {isSettled(item) && ( + + ➗ {t('split.settled')} + + )} {courseBadge} {sourceBadge} {moved && ( @@ -696,7 +704,7 @@ export default function OrderSummary({ order, selectable = false, selectedIds = const orderItemLayout = useTableViewStore(s => s.orderItemLayout || 'compact') const activeItems = order.items?.filter(i => i.status !== 'cancelled') || [] 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) const paidTotal = activeItems .filter(i => i.status === 'paid') diff --git a/waiter_pwa/src/components/SplitAmountModal.jsx b/waiter_pwa/src/components/SplitAmountModal.jsx new file mode 100644 index 0000000..b1230b5 --- /dev/null +++ b/waiter_pwa/src/components/SplitAmountModal.jsx @@ -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 ( +
+
e.stopPropagation()} data-testid="split-sheet"> +
+

{t('split.title')}

+

{t('split.items', { count })}

+

{money(total)}

+ + {choices.maxParts > 2 && ( +
+ +
+
{parts}
+
{t('split.partsLabel')}
+
+ +
+ )} + + {choices.custom && parts === 2 && ( +
+ + +
+ )} + + {custom && ( +
+ { setPct(Number(e.target.value)); setTyped('') }} style={{ width: '100%' }} /> +
+ {typedAmount == null ? `${pct}%` : ''}{typedAmount == null ? `${100 - pct}%` : ''} +
+ +
+ )} + +
+ {amounts ? amounts.map((a, n) => ( +
+ {t('split.part', { n: n + 1, of: amounts.length })}{money(a)} +
+ )) :

{t('split.invalid')}

} +
+

{t('split.howItWorks')}

+ {error &&

{error}

} +
+ + +
+
+
+ ) +} + +/** 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 ( +
+ {bills.map(b => ( +
+
+
{t('split.bill', { count: b.parts, total: money(b.total) })}
+
+ {t('split.billPaid', { paid: money(b.paid), due: money(Math.max(0, b.total - b.paid)) })} +
+
+ {canUndo && b.can_undo && ( + + )} +
+ ))} +
+ ) +} diff --git a/waiter_pwa/src/hooks/useSplitChoices.js b/waiter_pwa/src/hooks/useSplitChoices.js new file mode 100644 index 0000000..163e814 --- /dev/null +++ b/waiter_pwa/src/hooks/useSplitChoices.js @@ -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 +} diff --git a/waiter_pwa/src/logic/split.js b/waiter_pwa/src/logic/split.js new file mode 100644 index 0000000..55a3b33 --- /dev/null +++ b/waiter_pwa/src/logic/split.js @@ -0,0 +1,2 @@ +// Split the bill by amount (plan 6F.6): the shared rules, @xenia/ordering/split. +export * from '@xenia/ordering/split' diff --git a/waiter_pwa/src/pages/TableDetailPage.jsx b/waiter_pwa/src/pages/TableDetailPage.jsx index 6df077d..80b0868 100644 --- a/waiter_pwa/src/pages/TableDetailPage.jsx +++ b/waiter_pwa/src/pages/TableDetailPage.jsx @@ -23,6 +23,9 @@ import MoveHistory, { MovedOrderBanner } from '../components/MoveHistory' import QuantityModal from '../components/QuantityModal' import { useQuantityMode } from '../hooks/useQuantityMode' 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 { fade } from '../logic/colour' import SeatsHint from '../components/SeatsHint' @@ -42,6 +45,7 @@ function combineIds(items) { // Returns a stable string key for grouping under MERGE_IDENTICAL 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 opts = (() => { try { return item.selected_options ?? '[]' } 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) function sameItemKey(item) { + if (isPart(item)) return `part|${item.id}` const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4) 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 { paymentSafety } = usePaymentSettingsStore() const [method, setMethod] = useState('cash') @@ -1033,6 +1038,14 @@ function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, o
)} + {/* 6F.6: split the amount instead of paying it all now */} + {onSplit && ( + + )} +