Files
xenia-pos-local/local_backend/routers/pos.py
T
bonaminandClaude Opus 5.5 8abe4d92d3 feat(waiter): what a waiter may do comes from permission keys (platform-v2 step 4.3)
- Payments: ordering.orders.close checked on pay/close and the counter POS
  (waiters have it by default, owner decision); pay-offline always recorded.
- The venue switches waiter_cancellations / price_adjust / revert are gone:
  ordering.orders.cancel, ordering.prices.modify and the new
  ordering.payments.revert (overridable) decide; moves/split/transfer/merge
  need ordering.orders.open; discounts pricing.discounts.apply; chat chat.use.
- Venue role defaults: role_permissions (Alembic 0024), role_template(role, db),
  GET/PUT /api/waiters/roles/{role}/permissions applying the change to everyone
  with the role; manager Settings -> Operation -> "What each role may do".
  0024 also grants the new key to existing owners and store managers.
- Bootstrap `approvable`; @xenia/access useAllowed(key) -> yes/approve/no.
  The waiter shows each action by key, "with a manager's approval (PIN)" where
  allowed; GET /api/orders/cancel-permissions removed.
- Tests: test_waiter_keys.py (11), access allowed(), waiter.mjs +5, manager.mjs +3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:54:08 +02:00

644 lines
35 KiB
Python

"""Counter POS (plan step 3.3a, D-26): what a paired counter screen needs, in its own scope.
GET /api/pos/session the signed-in cashier's shift and the business day (shift gate)
GET /api/pos/menu categories and products to sell, with options and today's price
POST /api/pos/quote a cart priced by the backend (services/pos_cart.py)
POST /api/pos/sales a quick sale (3.3b): order + items + payment(s) in one call, the
cash drawer on cash, the fiscal receipt as for any payment
GET /api/pos/tables the tables the cashier may serve (their zones, as in the waiter app)
with each one's open order: totals, people, flags, ready items (3.3c)
POST /api/pos/tables/{id}/items send cart lines to a table (opens its order if it has none)
POST /api/pos/orders/{id}/pay pay chosen items of a table's order (cash/card/split, drawer)
POST /api/pos/orders/{id}/close close a fully paid order (never writes unpaid items off)
GET /api/pos/receipts today's paid orders, newest first (3.3e; scope=mine|all)
GET /api/pos/receipts/{id} one paid order: items with what's refundable, its refunds
POST /api/pos/orders/{id}/refund money back for paid items (services/refunds.py): cash opens
the drawer, the cashier's shift goes down, credit note via
the fiscal driver or by hand on the machine (D-27)
Tables use the waiter app's rules and functions (routers/orders.py): zone access, the person
assigned to an order, business day, kitchen tickets, shift totals. Cancelling items is the
waiter's own POST /api/orders/{id}/cancel-items (manager approval when the cashier can't).
Prices are never computed on the screen: the menu's `price` is the pricing engine's answer for
one unit with no options right now (happy hours, price groups), and the cart is priced with
POST /quote. The menu leaves out what a cashier doesn't need (costs, fiscal fields, digital
menu overrides). Starting a shift uses POST /api/shifts/start (ordering, in the POS scope).
"""
from __future__ import annotations
from typing import List, Literal, Optional
from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session, selectinload
from core.access.check import holds
from core.access.deps import require
from core.errors import XeniaError
from database import get_db
from services import pos_cart
router = APIRouter()
ACCESS = "pos_counter.access"
def _iso(dt):
return (dt.isoformat() + "Z") if dt is not None and dt.tzinfo is None else (dt.isoformat() if dt else None)
# ── session (shift gate) ─────────────────────────────────────────────────────
@router.get("/session")
def pos_session(db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""The open business day, the cashier's own open shift, whether they may start one
themselves, and who can open the day (shown when it's closed)."""
from core.access.queries import users_with_key
from models.business_day import BusinessDay
from models.settings import PosSettings
from models.shift import WaiterShift
from models.user import User
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
shift = db.query(WaiterShift).filter(WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() \
if isinstance(user, User) else None
row = db.get(PosSettings, "shifts.waiter_self_start")
self_start = holds(user, "core.dashboard.access") or (row is not None and row.value == "true")
openers = [u.nickname or u.full_name for u in users_with_key(db, "ordering.business_day.manage").order_by(User.full_name)
if u.role != "superadmin"]
return {
"business_day": {"id": day.id, "business_date": str(day.business_date) if day.business_date else None,
"opened_at": _iso(day.opened_at)} if day else None,
"shift": {"id": shift.id, "started_at": _iso(shift.started_at), "starting_cash": shift.starting_cash} if shift else None,
"self_start": bool(self_start),
"day_openers": openers,
}
# ── menu ────────────────────────────────────────────────────────────────────
def _subs_out(raw):
return [{"name": s["name"], "price": round(float(s.get("extra_cost") or 0.0), 2), "is_default": bool(s.get("is_default"))}
for s in pos_cart._subs(raw)]
def _product_out(p, price: float, prices: dict | None = None) -> dict:
shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731
from core import sales_points
return {
"id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url,
"price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()},
"sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON],
"base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
"tags": _tags(p.tags),
"primary_category_id": p.primary_category_id,
"categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships],
"sort_order": p.sort_order,
"quick": [{"id": q.id, "name": q.name, "price": round(q.price or 0.0, 2), "allow_multiple": bool(q.allow_multiple)}
for q in sorted(p.quick_options, key=lambda q: q.sort_order)],
"options": [{"id": o.id, "name": o.name, "price": round(o.extra_cost or 0.0, 2), "allow_multiple": bool(o.allow_multiple),
"multi_select": bool(o.multi_select), "subs": _subs_out(o.sub_choices)}
for o in p.options],
"prefs": [{"id": ps.id, "name": ps.name, "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select),
"shared": ({"name": shared(ps)["name"], "subs": _subs_out(shared(ps)["choices"])} if shared(ps) else None),
"choices": [{"id": c.id, "name": c.name, "price": round(c.extra_cost or 0.0, 2),
"disables_shared": bool(c.disables_subset), "subs": _subs_out(c.sub_choices)}
for c in ps.choices]}
for ps in p.preference_sets],
"ingredients": [{"id": i.id, "name": i.name} for i in p.ingredients],
}
def _tags(raw):
import json
try:
v = json.loads(raw) if isinstance(raw, str) else (raw or [])
except ValueError:
return []
return [t for t in v if isinstance(t, str)]
@router.get("/menu")
def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Categories and the products a cashier can sell (available, active, not service
items, sold at the counter: eating in or to take away, phase 3S), each with its price right
now for one unit without options (pricing engine): `price` for the screen's default order
type, `prices` per counter sales point, `sold_at` (which of the two)."""
from core import sales_points
from models.product import Category, Product, ProductPreferenceSet
from core.access.context import current_device
from core.modules import device_config
dev = current_device(request, db)
settings = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db)
products = (db.query(Product)
.filter(Product.is_available.is_(True), Product.lifecycle_status == "active", Product.is_service_item.is_(False))
.options(selectinload(Product.quick_options), selectinload(Product.options), selectinload(Product.ingredients),
selectinload(Product.preference_sets).selectinload(ProductPreferenceSet.choices),
selectinload(Product.memberships))
.order_by(Product.sort_order, Product.name).all())
products = [p for p in products if set(sales_points.sold_at(p)) & set(sales_points.IN_PERSON)]
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()
return {
"settings": settings,
"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})
for i, p in enumerate(products)],
}
# ── quote ───────────────────────────────────────────────────────────────────
class QuoteBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(default_factory=list, max_length=200)
order_id: Optional[int] = None # adding to a table's order: its items count for deals (3.3c)
def _adjustments(db, events) -> list[dict]:
from models.pricing import PriceModifier
out = []
for e in events:
if not e.delta_amount:
continue
m = db.get(PriceModifier, e.modifier_id) if e.modifier_id else None
out.append({"label": m.name if m is not None else e.event_type, "delta": round(e.delta_amount, 2)})
return out
@router.post("/quote")
def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""The cart priced exactly as the order will be: per line the unit price (base + options,
then price groups/modifiers), its total, what was chosen (names) and any adjustment."""
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
order_type, existing = body.order_type, None
if body.order_id is not None:
order = _order_for(db, user, body.order_id)
order_type, existing = order.order_type or "here", pos_cart.order_cart(order)
priced = pos_cart.price_lines(db, lines, order_type, existing) if lines else []
out = []
for line, (unit, events) in zip(lines, priced):
adj = pos_cart.discount_adjustment(unit, line.discount_pct)
out.append({
"product_id": line.product.id, "name": line.product.name, "quantity": line.quantity,
"base_price": round(line.product.base_price, 2), "extra": line.extra,
"discount_pct": line.discount_pct, "discount": adj,
"unit_price": round(unit + adj, 2), "total": round((unit + adj) * line.quantity, 2),
"entries": [{"name": e["name"], "price": e["price_delta"], "type": e["type"]} for e in line.entries],
"removed": line.removed, "notes": line.notes, "adjustments": _adjustments(db, events),
})
return {"order_type": order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)}
# ── quick sale (3.3b) ─────────────────────────────────────────────────────────
class Payment(BaseModel):
method: Literal["cash", "card"]
lines: Optional[List[int]] = None # indexes into `lines`; None = all of them
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)
cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
def _payment_groups(body: SaleBody, n: int) -> list:
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 [])]
if sorted(seen) != list(range(n)) or len({pay.method for pay in body.payments}) != len(body.payments):
raise XeniaError("pos.payment_invalid", reason="lines")
return [(pay.method, list(pay.lines)) for pay in body.payments if pay.lines]
@router.post("/sales", status_code=201)
def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Sell the cart on the spot: open a takeaway / counter order (no table), add the lines
exactly as POST /api/orders/{id}/items would (prices, price events, deals, kitchen
tickets, KDS), take the payment(s) through POST /api/orders/{id}/pay (the cashier's
shift, the fiscal receipt, auto-close), and open the cash drawer of the screen's receipt
printer when cash was taken. The checks run before anything is written. Discounted lines
need ordering.prices.modify or a manager's approval (D-10)."""
from models.order import OrderItem
from routers import orders as orders_api
from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest
_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))
_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)]
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)
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
paid, fiscal = [], None
for method, idx in groups:
res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=[item_ids[i] for i in idx], payment_method=method), request, db, user)
paid.append({"method": method, "amount": round(sum(totals[i] for i in idx), 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": round(sum(totals), 2), "payments": paid,
"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):
from models.shift import WaiterShift
from models.user import User
if not isinstance(user, User) or db.query(WaiterShift).filter(
WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() is None:
raise XeniaError("pos.shift_required")
def _check_discounts(request, db, user, lines):
from core.access.context import authorize
if any(line.discount_pct for line in lines):
authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
def _check_fiscal(db, products):
from services.fiscal import is_fiscal_enabled
if is_fiscal_enabled(db):
missing = sorted({p.name for p in products if p is not None and not p.fiscal_vat_group_id})
if missing:
raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
def _check_cash(cash_given, cash_due):
if cash_given is not None and cash_due and cash_given + 0.004 < cash_due:
raise XeniaError("pos.payment_invalid", reason="cash_short")
def _items_in(lines, adjs):
"""Cart lines as POST /api/orders/{id}/items takes them (the waiter's selected_options
entries with the database's prices; a discount as the item's price_adjustment)."""
from schemas.order import OrderItemInput, SelectedOptionInput
return [OrderItemInput(
product_id=line.product.id, quantity=line.quantity,
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
) for line, adj in zip(lines, adjs)]
def _open_drawer(request, db, user, order_id) -> str:
"""Kick the cash drawer of the screen's receipt printer: opened | failed | none (no printer)."""
from core.access.context import current_device
from core.modules import device_config
from models.printer import Printer
from routers import orders as orders_api
from services.printer_service import open_cash_drawer
dev = current_device(request, db)
cfg = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db)
printer = db.get(Printer, cfg["receipt_printer_id"]) if cfg.get("receipt_printer_id") else None
if printer is None or not printer.is_active:
return "none"
ok, _ = open_cash_drawer(printer, db, reason=f"order {order_id}")
orders_api._audit(db, order_id, "DRAWER_OPENED" if ok else "DRAWER_FAILED", waiter_id=user.id, note=printer.name)
db.commit()
return "opened" if ok else "failed"
# ── tables (3.3c) ───────────────────────────────────────────────────────────────
ACTIVE = ("open", "partially_paid", "paid")
UNPAID = ("active", "ready")
def _table_name(t) -> str:
return t.label or f"T{t.number}"
def _item_total(i) -> float:
return (i.unit_price + (i.price_adjustment or 0.0)) * i.quantity
def _in_zones(db, user, table) -> bool:
"""The waiter app's table rule (routers/tables.py list_tables): managers see every table,
staff the tables of their zones (a zone row without a group = every zone)."""
from models.user import WaiterZone
if holds(user, "core.dashboard.access"):
return True
zones = db.query(WaiterZone).filter(WaiterZone.waiter_id == user.id).all()
return any(z.group_id is None or z.group_id == table.group_id for z in zones)
def _order_for(db, user, order_id):
"""The order, if this cashier may act on it (the waiter app's rule, orders._can_access_order)."""
from models.order import Order
from routers import orders as orders_api
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
if not orders_api._can_access_order(order, user, db):
raise XeniaError("pos.table_not_yours", table=_table_name(order.table) if order.table else f"#{order_id}")
return order
@router.get("/tables")
def pos_tables(db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""The tables this cashier may serve and, for each, its open order: totals (all, unpaid),
item count, who is on it (and whether it's the cashier), when it opened, ready items
(KDS done), flags and a reservation due soon."""
from models.flag import TableFlagAssignment, TableFlagDef
from models.order import Order
from models.table import TableGroup
from models.user import User
from routers import tables as tables_api
visible = tables_api.list_tables(include_inactive=False, db=db, user=user)
ids = [t.id for t in visible]
orders = {}
if ids:
orders = {o.table_id: o for o in db.query(Order).filter(Order.table_id.in_(ids), Order.status.in_(ACTIVE))
.options(selectinload(Order.items), selectinload(Order.waiters)).all()}
people_ids = {w.waiter_id for o in orders.values() for w in o.waiters}
people = {u.id: u.nickname or u.full_name or u.username
for u in db.query(User).filter(User.id.in_(people_ids)).all()} if people_ids else {}
flags: dict[int, list] = {}
if ids:
rows = (db.query(TableFlagAssignment, TableFlagDef).join(TableFlagDef, TableFlagDef.id == TableFlagAssignment.flag_id)
.filter(TableFlagAssignment.table_id.in_(ids), TableFlagDef.is_active.is_(True))
.order_by(TableFlagDef.sort_order).all())
for a, d in rows:
flags.setdefault(a.table_id, []).append({"id": d.id, "name": d.name, "emoji": d.emoji, "color": d.color,
"text_color": d.text_color})
def order_out(o):
live = [i for i in o.items if i.status in UNPAID or i.status == "paid"]
return {
"id": o.id, "status": o.status, "opened_at": _iso(o.opened_at),
"total": round(sum(_item_total(i) for i in live), 2),
"unpaid": round(sum(_item_total(i) for i in live if i.status in UNPAID), 2),
"items": len(live),
"ready": sum(1 for i in live if (i.kds_status or "pending") == "done"),
"people": [people[w.waiter_id] for w in o.waiters if w.waiter_id in people],
"mine": any(w.waiter_id == user.id for w in o.waiters),
}
group_ids = [t.group_id for t in visible if t.group_id is not None]
groups = db.query(TableGroup).filter(TableGroup.id.in_(group_ids)).order_by(TableGroup.sort_order).all() if group_ids else []
return {
"groups": [{"id": g.id, "name": g.name, "color": g.color} for g in groups],
"tables": [{
"id": t.id, "name": _table_name(t), "number": t.number, "group_id": t.group_id, "seats": t.seat_count,
"flags": flags.get(t.id, []),
"reservation": ({"guest_name": t.upcoming_reservation.guest_name, "party_size": t.upcoming_reservation.party_size,
"reserved_for": _iso(t.upcoming_reservation.reserved_for)} if t.upcoming_reservation else None),
"order": order_out(orders[t.id]) if t.id in orders else None,
} for t in visible],
}
class TableItemsBody(BaseModel):
lines: List[dict] = Field(min_length=1, max_length=200)
@router.post("/tables/{table_id}/items", status_code=201)
def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: Session = Depends(get_db),
user=Depends(require(ACCESS))):
"""Send cart lines to a table, exactly as the waiter app does: into its open order, or a
new one (the cashier is assigned to it). Kitchen tickets, KDS, price events, deals."""
from models.order import Order
from models.table import Table
from routers import orders as orders_api
from schemas.order import AddItemsRequest, OrderCreate
_require_shift(db, user)
table = db.get(Table, table_id)
if table is None or not table.is_active:
raise XeniaError("pos.table_not_found", table_id=table_id)
order = db.query(Order).filter(Order.table_id == table_id, Order.status.in_(ACTIVE)).first()
if order is not None:
order = _order_for(db, user, order.id)
elif not _in_zones(db, user, table):
raise XeniaError("pos.table_not_yours", table=_table_name(table))
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
_check_discounts(request, db, user, lines)
existing = pos_cart.order_cart(order) if order is not None else None
priced = pos_cart.price_lines(db, lines, (order.order_type or "here") if order is not None else "here", existing)
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
if order is None:
order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user)
added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])}
class ItemsPayment(BaseModel):
method: Literal["cash", "card"]
item_ids: List[int] = Field(min_length=1, max_length=500)
class OrderPayBody(BaseModel):
payments: List[ItemsPayment] = Field(min_length=1, max_length=2)
cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
@router.post("/orders/{order_id}/pay")
def pos_order_pay(order_id: int, body: OrderPayBody, request: Request, db: Session = Depends(get_db),
user=Depends(require(ACCESS))):
"""Pay chosen items of an order (a table's) through POST /api/orders/{id}/pay, one call per
method: the cashier's shift, the fiscal receipt, auto-close. Cash opens the drawer. Items
someone else paid or cancelled meanwhile → pos.items_changed, nothing is paid."""
from models.order import OrderItem
from routers import orders as orders_api
from schemas.order import PayItemsRequest
_require_shift(db, user)
orders_api._need(request, db, user, "ordering.orders.close", target=f"order:{order_id}")
order = _order_for(db, user, order_id)
wanted = [i for pay in body.payments for i in pay.item_ids]
if len(set(wanted)) != len(wanted) or len({pay.method for pay in body.payments}) != len(body.payments):
raise XeniaError("pos.payment_invalid", reason="lines")
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()})
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)
paid, fiscal, res = [], None, {}
for pay in body.payments:
res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=pay.item_ids, payment_method=pay.method), request, db, user)
paid.append({"method": pay.method, "amount": amount[pay.method], "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, "status": res.get("status"), "auto_closed": bool(res.get("auto_closed")),
"total": round(sum(amount.values()), 2), "payments": paid, "cash_given": body.cash_given, "change": change,
"drawer": drawer, "fiscal": fiscal,
}
@router.post("/orders/{order_id}/close")
def pos_order_close(order_id: int, request: Request, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Close an order once everything on it is paid (or cancelled). Unlike the manager's close,
the counter never writes unpaid items off: pos.order_unpaid {count}."""
from models.order import OrderItem
from routers import orders as orders_api
order = _order_for(db, user, order_id)
unpaid = db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.status.in_(UNPAID)).count()
if unpaid:
raise XeniaError("pos.order_unpaid", count=unpaid)
return orders_api.close_order(order.id, request, db, user)
# ── receipts and refunds (3.3e) ────────────────────────────────────────────────
def _order_label(o) -> str:
if o.table is not None:
return _table_name(o.table)
if o.source == "online" and o.online_order_ref:
return o.online_order_ref
return f"#{o.id}"
def _names(db, ids) -> dict:
from models.user import User
ids = {i for i in ids if i}
return {u.id: u.full_name or u.username for u in db.query(User).filter(User.id.in_(ids)).all()} if ids else {}
def _option_names(raw) -> list:
import json
try:
return [o.get("name") for o in (json.loads(raw) if raw else []) if isinstance(o, dict) and o.get("name")]
except (ValueError, TypeError):
return []
@router.get("/receipts")
def pos_receipts(scope: Literal["mine", "all"] = "all", db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Today's paid orders (the open business day), newest payment first: what the counter can
refund. `mine` = with items paid in the cashier's open shift. → {orders: [{id, label, type,
source, paid_at, paid, refunded, methods, mine, cashier}]} (at most 200)"""
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.refund import Refund
from services.refunds import item_value, open_shift
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if day is None:
return {"orders": []}
shift = open_shift(db, user)
paid = db.query(OrderItem).join(Order, Order.id == OrderItem.order_id).filter(
Order.business_day_id == day.id, OrderItem.status == "paid").all()
by_order: dict[int, list] = {}
for i in paid:
by_order.setdefault(i.order_id, []).append(i)
if not by_order:
return {"orders": []}
orders = {o.id: o for o in db.query(Order).options(selectinload(Order.table)).filter(Order.id.in_(by_order)).all()}
refunded: dict[int, float] = {}
for oid, amount in db.query(Refund.order_id, Refund.amount).filter(Refund.order_id.in_(by_order)).all():
refunded[oid] = refunded.get(oid, 0.0) + amount
last = {oid: max(items, key=lambda i: (i.paid_at.isoformat() if i.paid_at else "", i.id))
for oid, items in by_order.items()}
names = _names(db, [i.paid_by for i in last.values()])
out = []
for oid, items in by_order.items():
o = orders[oid]
mine = shift is not None and any(i.paid_in_shift_id == shift.id for i in items)
if scope == "mine" and not mine:
continue
out.append({
"id": oid, "label": _order_label(o), "type": o.order_type, "source": o.source, "paid_at": _iso(last[oid].paid_at),
"paid": round(sum(item_value(i) for i in items), 2), "refunded": round(refunded.get(oid, 0.0), 2),
"methods": sorted({i.payment_method or "cash" for i in items}), "mine": mine,
"cashier": names.get(last[oid].paid_by),
})
out.sort(key=lambda r: (r["paid_at"] or "", r["id"]), reverse=True)
return {"orders": out[:200]}
@router.get("/receipts/{order_id}")
def pos_receipt(order_id: int, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""One paid order for a refund: its paid items (with what's already refunded and what's
left), its refunds, whether it's from today, and what fiscal will do with a refund."""
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.refund import Refund
from services import fiscal
from services.refunds import item_value, open_shift, refunded_quantities
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
shift = open_shift(db, user)
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
items = db.query(OrderItem).options(selectinload(OrderItem.product)).filter(
OrderItem.order_id == order.id, OrderItem.status == "paid").order_by(OrderItem.id).all()
done = refunded_quantities(db, [i.id for i in items])
refunds = db.query(Refund).filter(Refund.order_id == order.id).order_by(Refund.created_at).all()
names = _names(db, [i.paid_by for i in items] + [r.refunded_by for r in refunds] + [r.approved_by for r in refunds])
st = fiscal.status(db)
return {
"id": order.id, "label": _order_label(order), "type": order.order_type, "source": order.source,
"today": day is not None and order.business_day_id == day.id,
"fiscal": {"enabled": st["enabled"], "credit_notes": st["credit_notes"]},
"items": [{
"id": i.id, "name": i.product_name, "options": _option_names(i.selected_options), "notes": i.notes,
"quantity": i.quantity, "unit_type": i.product.unit_type if i.product else "piece",
"unit_total": round(item_value(i, 1), 2), "total": round(item_value(i), 2),
"method": i.payment_method or "cash", "paid_at": _iso(i.paid_at), "paid_by": names.get(i.paid_by),
"mine": shift is not None and i.paid_in_shift_id == shift.id,
"refunded": round(done.get(i.id, 0.0), 3), "refundable": round(max(0.0, i.quantity - done.get(i.id, 0.0)), 3),
} for i in items],
"refunds": [{
"id": r.id, "created_at": _iso(r.created_at), "method": r.method, "amount": r.amount, "reason": r.reason,
"by": names.get(r.refunded_by), "approved_by": names.get(r.approved_by), "fiscal": r.fiscal_status,
} for r in refunds],
}
class RefundLine(BaseModel):
item_id: int
quantity: float = Field(gt=0, le=100000)
class RefundBody(BaseModel):
items: List[RefundLine] = Field(min_length=1, max_length=500)
method: Literal["cash", "card"]
reason: Optional[str] = Field(default=None, max_length=300)
@router.post("/orders/{order_id}/refund", status_code=201)
def pos_refund(order_id: int, body: RefundBody, request: Request, db: Session = Depends(get_db),
user=Depends(require(ACCESS))):
"""Give money back for paid items of today's order (services/refunds.py): from the cashier's
shift, cash opens the drawer. Items paid in another shift need ordering.refunds or a
manager's approval. With fiscal on, the credit note goes through the venue's driver, or
`fiscal: "manual"` tells the cashier to issue it on the machine.
→ {refund_id, order_id, amount, method, drawer, fiscal}"""
from models.order import Order, OrderItem
from services import fiscal, refunds
from services.ws_bus import broadcast_sync
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
row = refunds.refund(request, db, user, order, [(x.item_id, x.quantity) for x in body.items], body.method, body.reason)
if row.fiscal_status == "pending":
from database import SessionLocal
qty = {ri.order_item_id: ri.quantity for ri in row.items}
items = db.query(OrderItem).filter(OrderItem.id.in_(qty)).all()
fiscal.send_credit_note_background(fiscal.build_fiscal_items(items, qty), row.method, row.amount, db, row.id,
{"order_id": order.id, "reference": None}, SessionLocal)
drawer = _open_drawer(request, db, user, order.id) if row.method == "cash" else "none"
broadcast_sync("order_refunded", {"order_id": order.id, "refund_id": row.id, "amount": row.amount, "method": row.method})
return {"refund_id": row.id, "order_id": order.id, "amount": row.amount, "method": row.method,
"drawer": drawer, "fiscal": row.fiscal_status}