Files
xenia-pos-local/local_backend/routers/pos.py
T
bonaminandClaude Opus 5.5 bff82a332a feat(terminal): quick sale at the counter: cash/card/split, change, cash drawer, fiscal (platform-v2 3.3b)
- POST /api/pos/sales: all checks first (shift, lines, payment split, cash given,
  discount → ordering.prices.modify or manager approval, fiscal VAT groups), then the
  existing open_order / add_items / pay_items functions, so tickets, KDS, price events,
  shift totals and the fiscal receipt work as for any order.
- Cash drawer: printer_service.open_cash_drawer (ESC @ + ESC p 0 25 250) to the screen's
  receipt printer on cash, logged and audited (DRAWER_OPENED / DRAWER_FAILED).
- orders._can_access_order: the people assigned to an order may act on it (a cashier's
  own takeaway order); pos_cart prices a batch with the lines before it, as add_items does.
- Terminal: Charge → payment dialog (exact cash pre-selected, quick amounts, change,
  card, split by line), per-line discounts, sale summary and "Same again".
- Tests: backend +6 (socket printer receives the drawer kick, fiscal file in the bridge
  folder), terminal unit +1, terminal.mjs +9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:28:33 +02:00

259 lines
14 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
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) -> dict:
shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731
return {
"id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url,
"price": round(price, 2), "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), each with its price right now for one unit without options (pricing engine)."""
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())
lines = [pos_cart.Line(product=p, quantity=1) for p in products]
prices = pos_cart.price_lines(db, lines, settings["default_order_type"]) if lines else []
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, unit) for p, (unit, _) in zip(products, prices)],
}
# ── quote ───────────────────────────────────────────────────────────────────
class QuoteBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(default_factory=list, max_length=200)
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)]
priced = pos_cart.price_lines(db, lines, body.order_type) 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": body.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 core.access.context import authorize, current_device
from core.modules import device_config
from models.order import OrderItem
from models.printer import Printer
from models.shift import WaiterShift
from models.user import User
from routers import orders as orders_api
from schemas.order import AddItemsRequest, OrderCreate, OrderItemInput, PayItemsRequest, SelectedOptionInput
from services.fiscal_service import is_fiscal_enabled
from services.printer_service import open_cash_drawer
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")
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))
if any(line.discount_pct for line in lines):
authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
if is_fiscal_enabled(db):
missing = sorted({line.product.name for line in lines if not line.product.fiscal_vat_group_id})
if missing:
raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
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)
if body.cash_given is not None and cash_due and body.cash_given + 0.004 < cash_due:
raise XeniaError("pos.payment_invalid", reason="cash_short")
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
items_in = [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)]
added = orders_api.add_items(order.id, AddItemsRequest(items=items_in), 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), 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 = "none"
if cash_due > 0:
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 not None and printer.is_active:
ok, _ = open_cash_drawer(printer, db, reason=f"order {order.id}")
drawer = "opened" if ok else "failed"
orders_api._audit(db, order.id, "DRAWER_OPENED" if ok else "DRAWER_FAILED", waiter_id=user.id, note=printer.name)
db.commit()
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", []),
}