"""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 _tr(x) -> dict: """A choice's names per language {lang: text} (6R.L: the counter shows them in the cashier's language; display only, lines keep ids and the venue's names). A row or a sub-choice's dict.""" from core.menu_languages import _load, names_of if isinstance(x, dict): return {k: v for k, v in _load(x.get("translations")).items() if isinstance(v, str)} return names_of(x) 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")), "translations": _tr(s)} 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 allergens, sales_points from core.menu_languages import of as product_tr return { "id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url, "translations": product_tr(p), # 6R.L: {lang: {name, description}}; every choice below has its own "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", "one_more": bool(p.one_more_enabled), # 6F.5 "tags": _tags(p.tags), "allergens": allergens.of(p), "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), "translations": _tr(q)} 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), "translations": _tr(o)} for o in p.options], "prefs": [{"id": ps.id, "name": ps.name, "translations": _tr(ps), "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select), "shared": ({"name": shared(ps)["name"], "translations": _tr(shared(ps)), "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), "translations": _tr(c)} for c in ps.choices]} for ps in p.preference_sets], "ingredients": [{"id": i.id, "name": i.name, "translations": _tr(i)} 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() from services import price_changes, split_bills from core.menu_languages import of as product_tr return { # + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount "settings": {**settings, "price_change": price_changes.mode(db), # 6F.6: splitting a bill by amount (the level and the most equal parts) "split_amount": split_bills.level(db), "split_max_parts": split_bills.max_parts(db)}, "categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order, "translations": product_tr(c)} 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) @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) return pos_cart.quote(db, lines, order_type, existing) # ── quick sale (3.3b) ───────────────────────────────────────────────────────── class Payment(BaseModel): method: Literal["cash", "card"] lines: Optional[List[int]] = None # indexes into `lines`; None = all of them class SaleSplit(BaseModel): """A quick sale split by amount (6F.6, Q-4): the parts and how each is paid, all now.""" mode: Literal["equal", "custom"] = "equal" parts: int = Field(default=2, ge=2, le=50) first_amount: Optional[float] = Field(default=None, gt=0, le=1000000) methods: List[Literal["cash", "card"]] = Field(min_length=2, max_length=50) # one per part class SaleBody(BaseModel): order_type: Literal["takeaway", "here"] = "takeaway" lines: List[dict] = Field(min_length=1, max_length=200) payments: List[Payment] = Field(default_factory=list, max_length=2) # without `split`: at least one split: Optional[SaleSplit] = None cash_given: Optional[float] = Field(default=None, ge=0, le=100000) def _payment_groups(body: SaleBody, n: int) -> list: if not body.payments: raise XeniaError("pos.payment_invalid", reason="lines") 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)) if body.split is None else [] approved_by = _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)] if body.split is not None: return _split_sale(body, request, db, user, lines, adjs, approved_by, totals) 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_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), 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", []), } def _split_sale(body, request, db, user, lines, adjs, approved_by, totals): """A quick sale split by amount (6F.6, Q-4): the order and its lines as any quick sale, then the lines settled into a split bill and each part paid now by its own method (one payment per method). The fiscal receipt is the lines themselves, issued with the last part (Q-3).""" from models.order import OrderItem from routers import orders as orders_api from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest from services import split_bills sp = body.split orders_api._need(request, db, user, "ordering.payments.split_amount", target="pos sale") if len(sp.methods) != sp.parts: raise XeniaError("pos.payment_invalid", reason="lines") if not split_bills.allowed(split_bills.level(db), sp.mode, sp.parts, split_bills.max_parts(db)): raise XeniaError("split.not_allowed") total = round(sum(totals), 2) if total < 0.01 * sp.parts: raise XeniaError("split.amount_invalid", total=f"{total:.2f}") amounts = split_bills.amounts(total, sp.mode, sp.parts, sp.first_amount) cash_due = round(sum(a for a, m in zip(amounts, sp.methods) if m == "cash"), 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_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user) items = db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all() bill = split_bills.create(db, order, items, mode=sp.mode, parts=sp.parts, first=sp.first_amount, user=user) orders_api._audit(db, order.id, "SPLIT_CREATED", waiter_id=user.id, item_ids=[i.id for i in items], amount=bill.total, note=f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts)) db.commit() parts = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id, OrderItem.status == "active").order_by(OrderItem.id).all() paid, fiscal = [], None for method in ("cash", "card"): ids = [p.id for p, m in zip(parts, sp.methods) if m == method] if not ids: continue res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=ids, payment_method=method), request, db, user) paid.append({"method": method, "amount": round(sum(a for a, m in zip(amounts, sp.methods) if m == method), 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": total, "payments": paid, "split": {"id": bill.id, "amounts": amounts, "methods": sp.methods}, "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): """A % discount at the counter is a price change in the cart (6F.3): the venue's switch, then the key (or a manager's PIN). Returns the approving manager's id, else None. The reason isn't asked: the discount itself says what it is.""" from core.access.context import authorize from services import price_changes if any(line.discount_pct for line in lines): price_changes.check(db, sent=False, by_hand=False) approval = authorize(request, db, user, "ordering.prices.modify", target="pos sale discount") return approval.approved_by if approval is not None else None return None 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, approved_by=None): """Resolved lines as orders.add_priced_items takes them (selected_options entries with the database's prices; a discount as the item's price_adjustment, recorded as a manual_price event with "−N %" as its reason, 6F.3).""" 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, source="counter", price_reason=f"−{line.discount_pct:g} %" if adj and line.discount_pct else None, price_approved_by=approved_by if adj else 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)] approved_by = _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_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), 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") from services.split_bills import is_part _check_fiscal(db, {i.product for i in items.values() if not is_part(i)}) # 6F.6: the settled lines were checked 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}