"""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) 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): 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, "unit_price": round(unit, 2), "total": round(unit * 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)}