feat: one way to count sales in every report; exports for Excel; the report kit and Today on v2 (platform-v2 step 6.12a)
- services/sales.py: sold = active + paid lines; a line's value net of what
was refunded of it; system lines (the delivery fee) counted apart as fees;
cost/profit with has_gap. Products, categories, tables, traffic, revenue
trends, business days (list and current), per-waiter sales, order history
totals and the printed products/categories/tables reports all use it (they
used to differ: closed-only vs all orders, fee as a product, refunds never
subtracted)
- the overview's day summary values lines with their price change (discounts
were valued at full price)
- services/csv_export.py: UTF-8 BOM, times in venue time with the zone in the
header, ';' and decimal commas for a Greek venue (',' and '.' otherwise);
every report export uses it; orders export has products / fees / refunded
- fix: /api/reports/shift/orders with business_day_id crashed (no window)
- manager: src/pages/reports/kit (page with tabs, period picker, panels,
figures, sortable table, export button, order dialog reusing the order
page's parts, hour chart on tokens) and reports/today on it; v1 Today removed
- tests: test_sales_accounting.py (a day with a fee and a partial refund adds
up the same in every report), test_reports_export.py (Excel format),
reports.test.mjs, e2e manager.mjs (Today, order dialog, export, Greek)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
"""CSV exports that open right in the venue's Excel (plan step 6.12a, from 2.99e).
|
||||
|
||||
- Times in **venue time** ("2026-11-19 21:30"), the zone named in the column header
|
||||
("Opened (Europe/Athens)"), instead of UTC ISO.
|
||||
- A UTF-8 byte-order mark, so Excel shows Greek names instead of mojibake.
|
||||
- The venue's language picks the separators Excel expects: Greek → columns split by `;`
|
||||
and decimal commas (12,50); otherwise `,` and decimal points.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
from datetime import date, datetime
|
||||
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
BOM = chr(0xFEFF) # tells Excel the file is UTF-8
|
||||
|
||||
|
||||
def _language(db) -> str:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == "venue.language").first() if db is not None else None
|
||||
return (row.value if row and row.value else "en").lower()
|
||||
|
||||
|
||||
def dialect(db) -> tuple[str, str]:
|
||||
"""(column separator, decimal mark) for the venue's Excel."""
|
||||
return (";", ",") if _language(db) == "el" else (",", ".")
|
||||
|
||||
|
||||
def venue_time(value) -> str:
|
||||
"""An ISO string or a datetime (UTC) → "YYYY-MM-DD HH:MM" in venue time; "" for nothing."""
|
||||
from core.timeutil import parse_api_datetime, to_venue
|
||||
if value in (None, ""):
|
||||
return ""
|
||||
dt = value if isinstance(value, datetime) else parse_api_datetime(str(value))
|
||||
if dt is None:
|
||||
return str(value)
|
||||
return to_venue(dt).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
|
||||
def response(db, rows: list[dict], fields: list[str], filename: str, *, times=(), labels: dict | None = None) -> StreamingResponse:
|
||||
"""`fields` in order (the header even with no rows); `times` are converted to venue time and
|
||||
their header names the zone; `labels` renames headers."""
|
||||
from core.timeutil import venue_tz
|
||||
sep, dec = dialect(db)
|
||||
zone = venue_tz().key
|
||||
labels = labels or {}
|
||||
header = [f"{labels.get(f, f)} ({zone})" if f in times else labels.get(f, f) for f in fields]
|
||||
|
||||
def cell(field, v):
|
||||
if field in times:
|
||||
return venue_time(v)
|
||||
if isinstance(v, bool):
|
||||
return "1" if v else "0"
|
||||
if isinstance(v, float):
|
||||
text = f"{v:.2f}" if abs(v - round(v, 2)) < 1e-9 else repr(v)
|
||||
return text.replace(".", dec) if dec != "." else text
|
||||
if isinstance(v, (date, datetime)):
|
||||
return v.isoformat()
|
||||
return "" if v is None else v
|
||||
|
||||
out = io.StringIO()
|
||||
w = csv.writer(out, delimiter=sep, lineterminator="\r\n")
|
||||
w.writerow(header)
|
||||
for r in rows:
|
||||
w.writerow([cell(f, r.get(f)) for f in fields])
|
||||
body = BOM + out.getvalue()
|
||||
return StreamingResponse(iter([body.encode("utf-8")]), media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'})
|
||||
@@ -0,0 +1,183 @@
|
||||
"""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.
|
||||
- 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")
|
||||
|
||||
|
||||
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
|
||||
|
||||
@property
|
||||
def takings(self) -> float:
|
||||
return self.revenue + self.fees
|
||||
|
||||
def add(self, line: Line) -> "Totals":
|
||||
self.refunded += line.refunded
|
||||
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}
|
||||
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user