diff --git a/local_backend/migrations/versions/0037_tab_books.py b/local_backend/migrations/versions/0037_tab_books.py new file mode 100644 index 0000000..f15e0f6 --- /dev/null +++ b/local_backend/migrations/versions/0037_tab_books.py @@ -0,0 +1,47 @@ +"""Tabs in the books (plan step 6.13c, KI-018): a line put on a tab and a payment on a tab +record the business day and the shift they happened in (the shift of whoever did it, if they +were on one), so a shift shows what it put on tabs and the tab money it received, and the +day shows both. Existing rows get their business day from when they happened. + +Revision ID: 0037_tab_books +Revises: 0036_print_job_resolution +Create Date: 2026-11-19 12:00:00 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0037_tab_books' +down_revision = '0036_print_job_resolution' +branch_labels = None +depends_on = None + +TABLES = ('tab_entries', 'tab_payments') + + +def upgrade() -> None: + for t in TABLES: + with op.batch_alter_table(t, schema=None) as batch_op: + batch_op.add_column(sa.Column('business_day_id', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('shift_id', sa.Integer(), nullable=True)) + batch_op.create_index(f'ix_{t}_business_day_id', ['business_day_id']) + batch_op.create_index(f'ix_{t}_shift_id', ['shift_id']) + batch_op.create_foreign_key(f'fk_{t}_business_day_id_business_days', 'business_days', ['business_day_id'], ['id']) + batch_op.create_foreign_key(f'fk_{t}_shift_id_waiter_shifts', 'waiter_shifts', ['shift_id'], ['id']) + # the day each existing row happened in (a closed day's window, or the open one) + op.execute(f""" + UPDATE {t} SET business_day_id = ( + SELECT d.id FROM business_days d + WHERE d.opened_at <= {t}.created_at AND (d.closed_at IS NULL OR d.closed_at >= {t}.created_at) + ORDER BY d.opened_at DESC LIMIT 1) + """) + + +def downgrade() -> None: + for t in TABLES: + with op.batch_alter_table(t, schema=None) as batch_op: + batch_op.drop_constraint(f'fk_{t}_shift_id_waiter_shifts', type_='foreignkey') + batch_op.drop_constraint(f'fk_{t}_business_day_id_business_days', type_='foreignkey') + batch_op.drop_index(f'ix_{t}_shift_id') + batch_op.drop_index(f'ix_{t}_business_day_id') + batch_op.drop_column('shift_id') + batch_op.drop_column('business_day_id') diff --git a/local_backend/models/tabs.py b/local_backend/models/tabs.py index ac8a9ff..9cdbbff 100644 --- a/local_backend/models/tabs.py +++ b/local_backend/models/tabs.py @@ -35,6 +35,9 @@ class TabEntry(Base): description = Column(Text, nullable=True) # auto-generated summary created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) created_at = Column(UTCDateTime, default=utcnow) + # 6.13c: the business day and the shift (of whoever did it, if on one) it happened in + business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True) + shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True) tab = relationship("Tab", back_populates="entries") created_by = relationship("User", foreign_keys=[created_by_id]) @@ -51,6 +54,9 @@ class TabPayment(Base): received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) notes = Column(Text, nullable=True) created_at = Column(UTCDateTime, default=utcnow) + # 6.13c: the business day and the shift (of whoever did it, if on one) it happened in + business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True) + shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True) tab = relationship("Tab", back_populates="payments") received_by = relationship("User", foreign_keys=[received_by_id]) diff --git a/local_backend/routers/business_day.py b/local_backend/routers/business_day.py index da50ee4..f9a3a26 100644 --- a/local_backend/routers/business_day.py +++ b/local_backend/routers/business_day.py @@ -292,6 +292,12 @@ def business_day_summary( "shift_pay": None, # distinct tables served (not order count) "tables_served": 0, + # 6.13c: lines this person put on customers' tabs, and tab money they received + "on_tab_items": 0.0, + "on_tab_value": 0.0, + "tab_cash": 0.0, + "tab_card": 0.0, + "tab_other": 0.0, } return waiter_stats[uid] @@ -331,6 +337,15 @@ def business_day_summary( else: e["other"] += val + # 6.13c: tabs: what went on them and the money received on them, per person and for the day + from services import tab_books + tabs_day = tab_books.for_day(db, day.id, {uid: (u.full_name or u.nickname or u.username) for uid, u in users_map.items()}) + for uid, x in tabs_day.pop("by_person").items(): + e = _waiter_entry(uid) + e["on_tab_items"] = x["on_tab_items"] + e["on_tab_value"] = x["on_tab_value"] + e["tab_cash"], e["tab_card"], e["tab_other"] = x["received"]["cash"], x["received"]["card"], x["received"]["other"] + from routers.shifts import compute_shift_pay for shift in shifts: e = _waiter_entry(shift.waiter_id) @@ -494,7 +509,7 @@ def business_day_summary( expenses_paid_today = round(sum(e.paid_amount for e in expenses_today), 2) expenses_due = round(expenses_total - expenses_paid_today, 2) - # TABBED REVENUE (items moved to tabs — not yet collected) + # Lines of today's orders on customers' tabs: sold, not paid (6.13c) tabbed_items = [i for i in all_items if i.status == "tabbed"] tabbed_revenue = round(sum(gross(i) for i in tabbed_items), 2) @@ -545,6 +560,9 @@ def business_day_summary( "expenses_paid_today": expenses_paid_today, "expenses_due": expenses_due, "tabbed_revenue": tabbed_revenue, + # 6.13c: put on tabs today (by anyone), tab money received today (by method; and the part + # received by people with no shift: in no drawer), every tab payment with who received it + "tabs": tabs_day, "net_estimate": net_estimate, "net_has_unknowns": net_has_unknowns, } diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index 7cec99c..1453fa4 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -2023,6 +2023,7 @@ def put_item_on_tab( user: User = Depends(require("tabs.manage")), # also needs the tabs module on (6.13a) ): from models.tabs import Tab, TabEntry + from services.sales import gross order = db.query(Order).filter(Order.id == order_id).first() if not order: @@ -2051,10 +2052,12 @@ def put_item_on_tab( tab_id=tab.id, order_id=order_id, order_item_id=item_id, - amount=round(item.unit_price * item.quantity, 2), + amount=round(gross(item), 2), # with its price change (a discount), as services/sales.py values it (6.13c) description=description, created_by_id=user.id, ) + from services import tab_books + tab_books.stamp(db, entry, user.id) # 6.13c: sold, not paid: the day and the shift it happened in db.add(entry) # Mark item as tabbed — distinct from active/paid/cancelled diff --git a/local_backend/routers/reports.py b/local_backend/routers/reports.py index 176ef66..8e9e3ec 100644 --- a/local_backend/routers/reports.py +++ b/local_backend/routers/reports.py @@ -2,6 +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 import csv import io import json @@ -1252,6 +1253,7 @@ def current_business_day( "opened_at": _dt(day.opened_at), **money, "refunds": day_refunds(db, day.id), + "tab_received": tab_books.for_day(db, day.id)["received"], # 6.13c: money paid on tabs today "orders_closed": len(closed_orders), "orders_open": len(open_orders), "active_waiters": len(active_shifts), diff --git a/local_backend/routers/shifts.py b/local_backend/routers/shifts.py index 43ed30d..0a777b9 100644 --- a/local_backend/routers/shifts.py +++ b/local_backend/routers/shifts.py @@ -32,33 +32,42 @@ def _get_setting(db: Session, key: str, default: str = "true") -> str: def compute_shift_total(shift_id: int, db: Session) -> float: - """What the shift took, net of its refunds (3.3e).""" + """The money the shift took (cash + card: items paid and tab payments), net of its refunds.""" split = compute_shift_payment_split(shift_id, db) - return round(split["cash_sales"] + split["card_sales"] - split["cash_refunds"] - split["card_refunds"], 2) + return round(split["cash_sales"] + split["card_sales"] + split["tab_cash"] + split["tab_card"] + - split["cash_refunds"] - split["card_refunds"], 2) def compute_shift_payment_split(shift_id: int, db: Session) -> dict: - """cash_sales / card_sales (items paid in this shift, with their price adjustments, i.e. - discounts) and cash_refunds / card_refunds (money this shift gave back, 3.3e).""" + """The shift's money by kind (6.13c: every movement apart). + + cash_sales / card_sales: items paid in this shift (with their price changes) in cash / by card; + other_sales: items paid any other way (transfer, on the house…): recorded, in no drawer + (until 6.13c they were counted as cash). tab_cash / tab_card / tab_other: payments on + customers' tabs this shift received. cash_refunds / card_refunds: money it gave back (3.3e). + """ + from services import tab_books from services.refunds import item_value, shift_refunds items = db.query(OrderItem).filter( OrderItem.paid_in_shift_id == shift_id, OrderItem.status == "paid", ).all() - cash = 0.0 - card = 0.0 + out = {"cash": 0.0, "card": 0.0, "other": 0.0} for i in items: - amount = item_value(i) method = (i.payment_method or "cash").lower() - if method == "card": - card += amount - else: - cash += amount + out[method if method in ("cash", "card") else "other"] += item_value(i) refunds = shift_refunds(db, shift_id) - return {"cash_sales": round(cash, 2), "card_sales": round(card, 2), + tab = tab_books.for_shift(db, shift_id)["received"] + return {"cash_sales": round(out["cash"], 2), "card_sales": round(out["card"], 2), "other_sales": round(out["other"], 2), + "tab_cash": tab["cash"], "tab_card": tab["card"], "tab_other": tab["other"], "cash_refunds": refunds["cash"], "card_refunds": refunds["card"]} +def expected_cash(split: dict, starting_cash: float | None) -> float: + """What should be in the drawer: starting cash + cash for items + cash on tabs − cash refunded.""" + return round((starting_cash or 0.0) + split["cash_sales"] + split["tab_cash"] - split["cash_refunds"], 2) + + def compute_shift_pay(shift: WaiterShift) -> dict: """Return duration_hours and shift_pay. shift_pay is None if no rate snapshot.""" now = utcnow() @@ -94,6 +103,26 @@ def compute_shift_pay(shift: WaiterShift) -> dict: return {"duration_hours": round(duration_hours, 2), "shift_pay": shift_pay} +def shift_activity(shift: WaiterShift, db: Session) -> dict: + """What happened in the shift (6.13c): orders opened and items made by this person in it, + items paid in it (by anyone's lines) and items it put on customers' tabs, with their values.""" + from models.order import Order + from services import tab_books + from services.sales import gross + end = shift.ended_at or utcnow() + made = db.query(OrderItem).filter(OrderItem.added_by == shift.waiter_id, OrderItem.added_at >= shift.started_at, + OrderItem.added_at <= end, OrderItem.status != "cancelled").all() + paid = db.query(OrderItem).filter(OrderItem.paid_in_shift_id == shift.id, OrderItem.status == "paid").all() + orders = db.query(Order).filter(Order.opened_by == shift.waiter_id, Order.opened_at >= shift.started_at, + Order.opened_at <= end, Order.status != "cancelled").count() + tab = tab_books.for_shift(db, shift.id)["on_tab"] + r = lambda v: round(v, 2) # noqa: E731 + return {"orders": orders, + "made_items": sum(i.quantity for i in made), "made_value": r(sum(gross(i) for i in made)), + "paid_items": sum(i.quantity for i in paid), "paid_value": r(sum(gross(i) for i in paid)), + "tab_items": tab["items"], "tab_value": tab["value"]} + + def _enrich_shift(shift: WaiterShift, db: Session) -> dict: w = shift.waiter wname = (w.full_name or w.username) if w else f"#{shift.waiter_id}" @@ -125,7 +154,12 @@ def _enrich_shift(shift: WaiterShift, db: Session) -> dict: "card_sales": split["card_sales"], "cash_refunds": split["cash_refunds"], "card_refunds": split["card_refunds"], - "net_to_deliver": round(split["cash_sales"] - split["cash_refunds"] + (shift.starting_cash or 0.0), 2), + "other_sales": split["other_sales"], + "tab_cash": split["tab_cash"], + "tab_card": split["tab_card"], + "tab_other": split["tab_other"], + "net_to_deliver": expected_cash(split, shift.starting_cash), + "activity": shift_activity(shift, db), "is_active": shift.ended_at is None, "notes": shift.notes, "hourly_rate_snapshot": shift.hourly_rate_snapshot, @@ -136,9 +170,8 @@ def _enrich_shift(shift: WaiterShift, db: Session) -> dict: "cancellation_value": cancellation_value, # Phase 2E — discrepancy computed live against cash-only expected (starting_cash + cash_sales) "counted_cash_end": shift.counted_cash_end, - "cash_discrepancy": round( - shift.counted_cash_end - (split["cash_sales"] - split["cash_refunds"] + (shift.starting_cash or 0.0)), 2 - ) if shift.counted_cash_end is not None else None, + "cash_discrepancy": round(shift.counted_cash_end - expected_cash(split, shift.starting_cash), 2) + if shift.counted_cash_end is not None else None, "breaks": [ {"id": b.id, "shift_id": b.shift_id, "started_at": _dt(b.started_at), "ended_at": _dt(b.ended_at)} for b in shift.breaks diff --git a/local_backend/routers/tabs.py b/local_backend/routers/tabs.py index bd5b01f..04dc058 100644 --- a/local_backend/routers/tabs.py +++ b/local_backend/routers/tabs.py @@ -20,12 +20,13 @@ from models.user import User from schemas.tabs import TabOut, TabEntryOut, TabPaymentOut, TabPayRequest, TabForgiveRequest, TabCloseRequest from core.access.deps import require, require_any from core.errors import XeniaError +from services import tab_books from services.ws_bus import broadcast_sync router = APIRouter() MANAGE = Depends(require("tabs.manage")) -METHODS = ("cash", "card", "other") +METHODS = tab_books.METHODS def changed(): @@ -150,6 +151,7 @@ def add_tab_entry( tab_id=tab_id, order_id=order_id, order_item_id=order_item_id, amount=amount, description=description, created_by_id=user.id, ) + tab_books.stamp(db, entry, user.id) db.add(entry) db.commit() db.refresh(tab) @@ -182,6 +184,7 @@ def pay_tab( payment_method=method, notes=body.notes, received_by_id=user.id, ) + tab_books.stamp(db, payment, user.id) # 6.13c: the day and the receiver's shift (their drawer) db.add(payment) db.commit() db.refresh(tab) diff --git a/local_backend/services/sales.py b/local_backend/services/sales.py index d9d3112..f404898 100644 --- a/local_backend/services/sales.py +++ b/local_backend/services/sales.py @@ -1,8 +1,9 @@ """How every report counts sales (plan step 6.12a). One set of rules, so a day adds up the same in every report, on screen, printed and exported. -- **Sold** = order lines that are `active` (ordered, not paid yet) or `paid`. Cancelled lines, - lines written off at closing (`closed`) and lines on a customer's tab (`tabbed`) are not sales. +- **Sold** = order lines that are `active` (ordered, not paid yet), `paid`, or on a customer's tab + (`tabbed`: sold, not paid; owner 2026-11-19, plan step 6.13c). Cancelled lines and lines written + off at closing (`closed`) are not sales. `on_tab` says how much of the sales is on tabs. - 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). @@ -16,7 +17,7 @@ from __future__ import annotations from dataclasses import dataclass -SOLD = ("active", "paid") +SOLD = ("active", "paid", "tabbed") def gross(item, quantity: float | None = None) -> float: @@ -70,6 +71,7 @@ class Totals: profit: float = 0.0 has_gap: bool = False units: float = 0.0 # products' quantity + on_tab: float = 0.0 # the part of revenue + fees on customers' tabs (sold, not paid) @property def takings(self) -> float: @@ -77,6 +79,8 @@ class Totals: def add(self, line: Line) -> "Totals": self.refunded += line.refunded + if line.item.status == "tabbed": + self.on_tab += line.value if line.fee: self.fees += line.value return self @@ -93,7 +97,8 @@ class Totals: def out(self) -> dict: r = lambda v: round(v + 0.0, 2) # noqa: E731 (-0.0 → 0.0) return {"revenue": r(self.revenue), "fees": r(self.fees), "takings": r(self.takings), "refunded": r(self.refunded), - "total_cost": r(self.cost), "trackable_profit": r(self.profit), "has_gap": self.has_gap} + "total_cost": r(self.cost), "trackable_profit": r(self.profit), "has_gap": self.has_gap, + "on_tab": r(self.on_tab)} def totals(ls) -> Totals: diff --git a/local_backend/services/tab_books.py b/local_backend/services/tab_books.py new file mode 100644 index 0000000..c816c13 --- /dev/null +++ b/local_backend/services/tab_books.py @@ -0,0 +1,103 @@ +"""Tabs in the books (plan step 6.13c, KI-018; owner 2026-11-19: every movement recorded). + +- A line put on a customer's tab **was sold but not paid**: the line is `tabbed` (services/sales.py + counts it as sold), and its TabEntry records who, when, the business day and the shift of whoever + did it. It is no money in anyone's hand: it isn't in any drawer. +- A payment on a tab is money received: its TabPayment records when, how (cash / card / other), + who received it, the business day and that person's shift if they are on one. Cash goes in that + shift's drawer, card in its card total. Received by someone with no shift (a manager): it is + theirs in the day's money and in no drawer. +""" +from __future__ import annotations + +from sqlalchemy.orm import Session + +METHODS = ("cash", "card", "other") + + +def stamp(db: Session, row, user_id: int) -> None: + """Set the open business day and the user's running shift on a TabEntry / TabPayment.""" + from models.business_day import BusinessDay + from models.shift import WaiterShift + day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() + shift = db.query(WaiterShift).filter(WaiterShift.waiter_id == user_id, WaiterShift.ended_at.is_(None)) \ + .order_by(WaiterShift.started_at.desc()).first() + row.business_day_id = day.id if day else (shift.business_day_id if shift else None) + row.shift_id = shift.id if shift else None + + +def _money(rows) -> dict: + out = {m: 0.0 for m in METHODS} + for p in rows: + m = p.payment_method if p.payment_method in METHODS else "other" + out[m] += p.amount + out = {k: round(v, 2) for k, v in out.items()} + out["total"] = round(sum(out.values()), 2) + out["count"] = len(rows) + return out + + +def _on_tab(entries) -> dict: + items = 0.0 + for e in entries: + it = getattr(e, "_item", None) + items += it.quantity if it is not None else 0 + return {"value": round(sum(e.amount for e in entries), 2), "lines": len(entries), "items": items} + + +def _with_items(db: Session, entries): + from models.order import OrderItem + ids = [e.order_item_id for e in entries if e.order_item_id] + by_id = {i.id: i for i in db.query(OrderItem).filter(OrderItem.id.in_(ids)).all()} if ids else {} + for e in entries: + e._item = by_id.get(e.order_item_id) + return entries + + +def for_shift(db: Session, shift_id: int) -> dict: + """{on_tab: {value, lines, items}, received: {cash, card, other, total, count}} of one shift.""" + from models.tabs import TabEntry, TabPayment + entries = _with_items(db, db.query(TabEntry).filter(TabEntry.shift_id == shift_id).all()) + pays = db.query(TabPayment).filter(TabPayment.shift_id == shift_id).all() + return {"on_tab": _on_tab(entries), "received": _money(pays)} + + +def for_day(db: Session, day_id: int, names: dict | None = None) -> dict: + """The day's tabs: what went on them, the money received on them (by method), and every payment + (who received it, in a shift or not).""" + from models.tabs import TabEntry, TabPayment + entries = _with_items(db, db.query(TabEntry).filter(TabEntry.business_day_id == day_id).all()) + pays = db.query(TabPayment).filter(TabPayment.business_day_id == day_id).order_by(TabPayment.created_at).all() + names = names or {} + + def who(uid): + return names.get(uid) or f"#{uid}" + from core.timeutil import iso_z + return { + "on_tab": _on_tab(entries), + "received": _money(pays), + "received_outside_shifts": _money([p for p in pays if p.shift_id is None]), + "payments": [{ + "id": p.id, "tab_id": p.tab_id, "customer_name": p.tab.customer.name if p.tab and p.tab.customer else None, + "amount": p.amount, "method": p.payment_method or "cash", "received_by_id": p.received_by_id, + "received_by_name": who(p.received_by_id), "shift_id": p.shift_id, "at": iso_z(p.created_at), + } for p in pays], + "by_person": _by_person(entries, pays), + } + + +def _by_person(entries, pays) -> dict: + """{user_id: {on_tab_value, on_tab_items, received: {cash, card, other}}}.""" + out: dict = {} + + def e(uid): + return out.setdefault(uid, {"on_tab_value": 0.0, "on_tab_items": 0.0, "received": {m: 0.0 for m in METHODS}}) + for t in entries: + x = e(t.created_by_id) + x["on_tab_value"] = round(x["on_tab_value"] + t.amount, 2) + x["on_tab_items"] += t._item.quantity if getattr(t, "_item", None) is not None else 0 + for p in pays: + m = p.payment_method if p.payment_method in METHODS else "other" + x = e(p.received_by_id) + x["received"][m] = round(x["received"][m] + p.amount, 2) + return out diff --git a/local_backend/tests/test_sales_accounting.py b/local_backend/tests/test_sales_accounting.py index 842a335..b0d2944 100644 --- a/local_backend/tests/test_sales_accounting.py +++ b/local_backend/tests/test_sales_accounting.py @@ -82,7 +82,7 @@ def test_the_day_adds_up_the_same_in_every_report(client, the_day, login): assert [(w["waiter_name"], w["total"], w["items"]) for w in staff] == [("Maria W", 13.0, 2)] history = get("/api/reports/orders/history", business_day_id=day_id) assert history[0]["totals"] == {"revenue": 13.0, "fees": 2.5, "takings": 15.5, "refunded": 3.0, - "total_cost": 4.0, "trackable_profit": 6.0, "has_gap": True} + "total_cost": 4.0, "trackable_profit": 6.0, "has_gap": True, "on_tab": 0.0} # the products export says the same import csv diff --git a/local_backend/tests/test_tab_books.py b/local_backend/tests/test_tab_books.py new file mode 100644 index 0000000..e697870 --- /dev/null +++ b/local_backend/tests/test_tab_books.py @@ -0,0 +1,93 @@ +"""Tabs in the books (plan step 6.13c, KI-018; owner 2026-11-19: every movement recorded). + +A shift: 3 items made, 2 paid in cash, 1 put on a customer's tab → the drawer expects the 2 (the tab +line is sold, not paid). The tab is paid later: part in cash by someone in another shift (their +drawer expects it), the rest by card by the owner with no shift (recorded as theirs, in the day, +in no drawer). Every report counts the tab line as sold and the tab money as received.""" +from datetime import timedelta + + +def _setup(db, make_user): + from core.timeutil import business_date_of, utcnow + from models.business_day import BusinessDay + from models.customers import Customer + from models.order import Order, OrderItem + from models.product import Category, Product + from models.shift import WaiterShift + now = utcnow() + owner = make_user(role="owner", full_name="Olga Owner") + maria = make_user(role="waiter", full_name="Maria W") + nikos = make_user(role="store_manager", full_name="Nikos M") + anna = make_user(role="store_manager", full_name="Anna M") + day = BusinessDay(status="open", opened_by_id=owner.id, opened_at=now - timedelta(hours=3), business_date=business_date_of(now)) + cat = Category(name="Drinks") + cust = Customer(name="Kostas", created_by_id=owner.id) + db.add_all([day, cat, cust]) + db.flush() + beer = Product(name="Beer", base_price=4.0, primary_category_id=cat.id) + db.add(beer) + db.flush() + shifts = {u.full_name: WaiterShift(waiter_id=u.id, business_day_id=day.id, started_at=now - timedelta(hours=2), starting_cash=10.0) + for u in (maria, nikos, anna)} + db.add_all(shifts.values()) + db.flush() + order = Order(opened_by=maria.id, order_type="takeaway", business_day_id=day.id, customer_id=cust.id, opened_at=now - timedelta(hours=1)) + db.add(order) + db.flush() + line = lambda **kw: OrderItem(order_id=order.id, product_id=beer.id, added_by=maria.id, quantity=1, unit_price=4.0, # noqa: E731 + added_at=now - timedelta(minutes=50), **kw) + paid = [line(status="paid", paid_by=maria.id, paid_at=now, payment_method="cash", paid_in_shift_id=shifts["Maria W"].id) for _ in range(2)] + tabbed = line() + tabbed.quantity = 2 # the third line: 2 beers, 8.00, on the tab + db.add_all(paid + [tabbed]) + db.commit() + return dict(owner=owner, maria=maria, nikos=nikos, anna=anna, day=day, shifts=shifts, order=order, tabbed=tabbed) + + +def test_a_shift_and_its_tab_in_the_books(client, db, make_user, login): + s = _setup(db, make_user) + nikos, anna, owner = login(s["nikos"]), login(s["anna"]), login(s["owner"]) + # Nikos (on his shift) puts the line on Kostas's tab + r = client.post(f"/api/orders/{s['order'].id}/items/{s['tabbed'].id}/tab", headers=nikos) + assert r.status_code == 200, r.text + tab_id = r.json()["tab_id"] + + shift = lambda name: client.get(f"/api/shifts/{s['shifts'][name].id}/summary", headers=owner).json() # noqa: E731 + m = shift("Maria W") + assert m["activity"] == {"orders": 1, "made_items": 4, "made_value": 16.0, "paid_items": 2, "paid_value": 8.0, "tab_items": 0, "tab_value": 0.0} + assert (m["cash_sales"], m["tab_cash"], m["net_to_deliver"]) == (8.0, 0.0, 18.0) # 10 starting + the 2 paid; not the tab line + n = shift("Nikos M") + assert (n["activity"]["tab_items"], n["activity"]["tab_value"], n["net_to_deliver"]) == (2, 8.0, 10.0) # put on a tab: no money + + # later: Anna (on her shift) takes 5 in cash; the owner, with no shift, takes the rest by card + assert client.post(f"/api/tabs/{tab_id}/pay", headers=anna, json={"amount": 5, "payment_method": "cash"}).status_code == 200 + assert client.post(f"/api/tabs/{tab_id}/pay", headers=owner, json={"amount": 3, "payment_method": "card"}).status_code == 200 + a = shift("Anna M") + assert (a["tab_cash"], a["tab_card"], a["net_to_deliver"], a["total_collected"]) == (5.0, 0.0, 15.0, 5.0) + + day = client.get("/api/business-day/summary", headers=owner).json() + t = day["tabs"] + assert t["on_tab"] == {"value": 8.0, "lines": 1, "items": 2} + assert (t["received"]["cash"], t["received"]["card"], t["received"]["total"]) == (5.0, 3.0, 8.0) + assert (t["received_outside_shifts"]["card"], t["received_outside_shifts"]["total"]) == (3.0, 3.0) + assert [(p["received_by_name"], p["method"], p["amount"], p["shift_id"] is None) for p in t["payments"]] == \ + [("Anna M", "cash", 5.0, False), ("Olga Owner", "card", 3.0, True)] + people = {w["waiter_name"]: w for w in day["waiters"]} + assert (people["Nikos M"]["on_tab_value"], people["Nikos M"]["on_tab_items"]) == (8.0, 2) + assert people["Anna M"]["tab_cash"] == 5.0 and people["Olga Owner"]["tab_card"] == 3.0 + assert day["tabbed_revenue"] == 8.0 + + # the reports: the tab line is sold (16 = 8 paid + 8 on the tab), 8 of it on a tab + cur = client.get("/api/reports/business-days/current", headers=owner).json()["business_day"] + assert cur["revenue"] == 16.0 and cur["on_tab"] == 8.0, cur + assert (cur["tab_received"]["cash"], cur["tab_received"]["card"]) == (5.0, 3.0) + + +def test_other_payment_methods_are_not_drawer_cash(client, db, make_user, login): + """Before 6.13c anything not paid by card counted as cash in the drawer (a line on the house too).""" + s = _setup(db, make_user) + db.query(type(s["tabbed"])).filter_by(id=s["tabbed"].id).update({"status": "paid", "payment_method": "treat", + "paid_in_shift_id": s["shifts"]["Maria W"].id}) + db.commit() + m = client.get(f"/api/shifts/{s['shifts']['Maria W'].id}/summary", headers=login(s["owner"])).json() + assert (m["cash_sales"], m["other_sales"], m["net_to_deliver"]) == (8.0, 8.0, 18.0) diff --git a/manager_dashboard/src/pages/overview/DaySummaryTabs.jsx b/manager_dashboard/src/pages/overview/DaySummaryTabs.jsx index bd3f3cd..c42a967 100644 --- a/manager_dashboard/src/pages/overview/DaySummaryTabs.jsx +++ b/manager_dashboard/src/pages/overview/DaySummaryTabs.jsx @@ -58,11 +58,24 @@ export function MoneyTab({ data }) {
- - {data.tabbed_revenue > 0 && + {data.tabbed_revenue > 0 && {t('overview.day.onTabsTip')}} />} - + + {data.tabs?.received?.total > 0 && {t('overview.day.tabReceivedTip')}} />} +
+ {data.tabs?.payments?.length > 0 && ( +
+ {data.tabs.payments.map(p => ( + + ))} +
+ )}
{t('overview.day.cogsTip')}} /> {data.cogs_has_gap && } @@ -137,6 +150,8 @@ export function StaffTab({ data }) {
{w.tables_served ?? 0}
{w.items_paid}
+ {w.on_tab_value > 0 &&
} + {w.tab_cash + w.tab_card + w.tab_other > 0 &&
}