"""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), `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). - **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. - **Cost / profit**: a line with a cost snapshot adds its cost (for the quantity kept) and its profit; a line without one makes the total a lower bound (`has_gap`). """ from __future__ import annotations from dataclasses import dataclass SOLD = ("active", "paid", "tabbed") def gross(item, quantity: float | None = None) -> float: q = item.quantity if quantity is None else quantity return ((item.unit_price or 0.0) + (item.price_adjustment or 0.0)) * q def is_fee(item) -> bool: return getattr(item, "system_key", None) is not None @dataclass class Line: item: object quantity: float # sold minus refunded value: float # its value minus the refunded part refunded: float # the refunded value fee: bool @property def kept(self) -> bool: """Something of it was kept (not refunded in full).""" return self.quantity > 1e-9 @property def cost(self) -> float | None: uc = getattr(self.item, "unit_cost", None) return None if uc is None else uc * self.quantity 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] back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"]) out = [] for i in sold: 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=is_fee(i))) return out @dataclass class Totals: revenue: float = 0.0 # products, net of refunds fees: float = 0.0 # delivery fees (and other system lines), net of refunds refunded: float = 0.0 # what was refunded of these lines (already taken off) cost: float = 0.0 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: return self.revenue + self.fees 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 self.revenue += line.value self.units += line.quantity c = line.cost if c is None: self.has_gap = self.has_gap or line.kept else: self.cost += c self.profit += line.value - c return self 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, "on_tab": r(self.on_tab)} def totals(ls) -> Totals: t = Totals() for line in ls: t.add(line) return t def order_totals(db, orders) -> dict[int, Totals]: """{order_id: Totals} for orders (their items loaded through the relationship).""" all_items = [i for o in orders for i in o.items] by_order: dict[int, Totals] = {o.id: Totals() for o in orders} for line in lines(db, all_items): by_order[line.item.order_id].add(line) return by_order # ── summaries shared by the screens, the printed reports and the exports ───── def products(db, items, category_id: int | None = None) -> dict: """{product_id: {...}} for product lines (fees left out), names and categories as sold (D-18).""" pnames = _names(items) out: dict = {} for line in lines(db, items): if line.fee or not line.kept: continue it = line.item if category_id and it.category_id != category_id: continue e = out.setdefault(it.product_id, { "product_id": it.product_id, "product_name": pnames.get(it.product_id) or f"#{it.product_id}", "category_id": it.category_id, "qty_sold": 0.0, "revenue": 0.0, "refunded": 0.0, "total_cost": 0.0, "trackable_profit": 0.0, "uncosted_revenue": 0.0, "uncosted_items": 0.0, "order_ids": set(), }) e["qty_sold"] += line.quantity e["revenue"] += line.value e["refunded"] += line.refunded e["order_ids"].add(it.order_id) c = line.cost if c is None: e["uncosted_revenue"] += line.value e["uncosted_items"] += line.quantity else: e["total_cost"] += c e["trackable_profit"] += line.value - c return out def categories(db, items) -> dict: """{category_id: {...}} for product lines, with each category's products.""" pnames = _names(items) cnames = _names(items, "category") out: dict = {} for line in lines(db, items): if line.fee or not line.kept: continue it = line.item cid = it.category_id e = out.setdefault(cid, {"category_id": cid, "category_name": cnames.get(cid) or "—", "units_sold": 0.0, "revenue": 0.0, "refunded": 0.0, "total_cost": 0.0, "trackable_profit": 0.0, "uncosted_revenue": 0.0, "has_gap": False, "products": {}}) e["units_sold"] += line.quantity e["revenue"] += line.value e["refunded"] += line.refunded c = line.cost if c is None: e["uncosted_revenue"] += line.value e["has_gap"] = True else: e["total_cost"] += c e["trackable_profit"] += line.value - c p = e["products"].setdefault(it.product_id, {"name": pnames.get(it.product_id) or f"#{it.product_id}", "qty": 0.0, "revenue": 0.0}) p["qty"] += line.quantity p["revenue"] += line.value return out def _names(items, kind: str = "product") -> dict: """Names as sold; if renamed within the period, the newest wins (D-18, CS-4).""" out = {} for it in sorted(items, key=lambda i: (i.added_at is None, i.added_at, i.id)): if kind == "product": out[it.product_id] = it.product_name elif it.category_id is not None: out[it.category_id] = it.category_name return out