Files
xenia-pos-local/local_backend/tests/test_sales_accounting.py
T
bonaminandClaude Opus 5.5 07c9a0aecf feat: tabs in the books (platform-v2 step 6.13c, KI-018; owner 2026-11-19: every movement recorded)
- a line on a customer's tab is sold, not paid: services/sales.py counts tabbed lines as sold (on_tab apart)
- TabEntry / TabPayment record the business day and the shift of whoever did it (Alembic 0037, rows backfilled with their day);
  services/tab_books.py: per shift and per day, on tabs and tab money received (cash / card / other, who, in a shift or not)
- shift: tab cash goes in the drawer (net_to_deliver, the counted difference, total_collected), tab card in the card total;
  items paid other ways (transfer, on the house) are recorded apart and no longer counted as drawer cash;
  'activity': orders, items made / paid / put on a tab with values
- day summary: per person put on tabs and tab money received, every tab payment with who took it, the part taken outside shifts (in no drawer);
  the day's money: paid, on tabs, sold, paid on tabs, money taken (it used to subtract tabs from paid sales)
- Today: on tabs, paid on tabs; Staff -> Cash handover: paid on tabs; the shift dialog: made / paid / on a tab / paid on tabs
- fix: a line put on a tab was charged without its price change (a discount)
- tests: test_tab_books.py (the done-when), overview unit, e2e manager.mjs (the day records the tab payments; Today shows them)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:32:25 +02:00

110 lines
6.3 KiB
Python

"""One way to count sales in every report (plan step 6.12a, services/sales.py): a day with
products, a delivery fee and a partial refund adds up the same everywhere — products net of
what was refunded, the delivery fee apart, cancelled lines out."""
from datetime import timedelta
import pytest
@pytest.fixture
def the_day(db, make_user):
"""Table 4: a burger (10, cost 4), two coffees (3 each, no cost), the delivery fee (2.50),
a cancelled coffee; one coffee refunded (3)."""
from core.timeutil import business_date_of, utcnow
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.product import Category, Product
from models.refund import Refund, RefundItem
from models.table import Table
owner = make_user(role="owner")
waiter = make_user(role="waiter", full_name="Maria W")
now = utcnow() - timedelta(minutes=30)
day = BusinessDay(status="open", opened_by_id=owner.id, opened_at=now - timedelta(hours=2), business_date=business_date_of(now))
food, drinks = Category(name="Food"), Category(name="Drinks")
table = Table(number=4)
db.add_all([day, food, drinks, table])
db.flush()
burger = Product(name="Burger", base_price=10.0, primary_category_id=food.id)
coffee = Product(name="Freddo", base_price=3.0, primary_category_id=drinks.id)
fee = Product(name="Delivery", base_price=2.5, primary_category_id=food.id, system_key="delivery_fee")
db.add_all([burger, coffee, fee])
db.flush()
order = Order(opened_by=waiter.id, table_id=table.id, business_day_id=day.id, opened_at=now, closed_at=now + timedelta(minutes=40), status="closed")
db.add(order)
db.flush()
item = lambda p, qty, price, **kw: OrderItem(order_id=order.id, product_id=p.id, added_by=waiter.id, quantity=qty, unit_price=price, # noqa: E731
status=kw.pop("status", "paid"), paid_by=waiter.id, paid_at=now, payment_method="cash", **kw)
b = item(burger, 1, 10.0, unit_cost=4.0)
c = item(coffee, 2, 3.0)
f = item(fee, 1, 2.5) # its system_key comes from the product
x = item(coffee, 1, 3.0, status="cancelled")
db.add_all([b, c, f, x])
db.flush()
refund = Refund(order_id=order.id, business_day_id=day.id, refunded_by=owner.id, method="cash", amount=3.0)
db.add(refund)
db.flush()
db.add(RefundItem(refund_id=refund.id, order_item_id=c.id, quantity=1, amount=3.0))
db.commit()
return {"day": day, "order": order, "owner": owner, "waiter": waiter, "food": food, "drinks": drinks}
def test_the_day_adds_up_the_same_in_every_report(client, the_day, login):
h = login(the_day["owner"])
day_id = the_day["day"].id
get = lambda url, **p: client.get(url, headers=h, params=p).json() # noqa: E731
# the business day (list and "now"): products 10 + 3 (one coffee refunded), the fee apart
day = next(d for d in get("/api/reports/business-days")["business_days"] if d["id"] == day_id)
now = get("/api/reports/business-days/current")["business_day"]
for d in (day, now):
assert (d["revenue"], d["fees"], d["takings"], d["refunded"]) == (13.0, 2.5, 15.5, 3.0), d
assert d["total_cost"] == 4.0 and d["trackable_profit"] == 6.0 and d["has_gap"] is True
assert d["refunds"]["amount"] == 3.0
assert now["top_product"]["name"] == "Burger" or now["top_product"]["qty"] == 1
# products and categories: no "Delivery" product, the coffee net of its refund
products = {p["product_name"]: p for p in get("/api/reports/products/performance", business_day_id=day_id)["products"]}
assert set(products) == {"Burger", "Freddo"}
assert (products["Freddo"]["qty_sold"], products["Freddo"]["revenue"], products["Freddo"]["refunded"]) == (1, 3.0, 3.0)
cats = {c["category_name"]: c["revenue"] for c in get("/api/reports/categories/performance", business_day_id=day_id)["categories"]}
assert cats == {"Food": 10.0, "Drinks": 3.0}
# by table, by hour, by day: the same 13, the fee beside it
tables = get("/api/reports/tables/performance", business_day_id=day_id)["tables"]
assert [(t["table_name"], t["revenue"], t["fees"]) for t in tables] == [("T4", 13.0, 2.5)]
traffic = get("/api/reports/traffic", business_day_id=day_id)
assert round(sum(h["revenue"] for h in traffic["by_hour"]), 2) == 13.0
trend = get("/api/reports/revenue/trends")["trends"]
assert [(t["revenue"], t["fees"]) for t in trend] == [(13.0, 2.5)]
# per waiter, and the order history's totals
staff = get("/api/reports/shift/orders", business_day_id=day_id)["waiters"]
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, "on_tab": 0.0}
# the products export says the same
import csv
import io
text = client.get("/api/reports/products/export", headers=h, params={"business_day_id": day_id}).content.decode("utf-8")[1:]
rows = {r["product_name"]: r for r in csv.DictReader(io.StringIO(text))}
assert rows["Freddo"]["revenue"] == "3.00" and rows["Freddo"]["refunded"] == "3.00" and "Delivery" not in rows
def test_a_line_refunded_in_full_leaves_the_lists_but_its_refund_counts(db, the_day):
from models.order import OrderItem
from models.refund import Refund, RefundItem
from services import sales
burger = next(i for i in the_day["order"].items if i.product_name == "Burger")
r = Refund(order_id=the_day["order"].id, business_day_id=the_day["day"].id, refunded_by=the_day["owner"].id, method="card", amount=10.0)
db.add(r)
db.flush()
db.add(RefundItem(refund_id=r.id, order_item_id=burger.id, quantity=1, amount=10.0))
db.commit()
items = db.query(OrderItem).filter(OrderItem.order_id == the_day["order"].id).all()
t = sales.totals(sales.lines(db, items))
assert (round(t.revenue, 2), round(t.fees, 2), round(t.refunded, 2), t.cost) == (3.0, 2.5, 13.0, 0.0)
assert [line.kept for line in sales.lines(db, items) if line.item.product_name == "Burger"] == [False]
assert "Burger" not in {v["product_name"] for v in sales.products(db, items).values()} # not listed as sold