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>
This commit is contained in:
@@ -77,6 +77,9 @@ def _can_access_order(order: Order, user: User, db: Session) -> bool:
|
||||
Standalone orders (table_id=None) are accessible to all waiters with any zone assignment."""
|
||||
if holds(user, "core.dashboard.access"):
|
||||
return True
|
||||
# Whoever the order is assigned to may act on it (e.g. a cashier's own counter sale, 3.3b)
|
||||
if any(ow.waiter_id == user.id for ow in order.waiters):
|
||||
return True
|
||||
zones = db.query(WaiterZone).filter(WaiterZone.waiter_id == user.id).all()
|
||||
if not zones:
|
||||
return False
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
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
|
||||
@@ -150,11 +152,107 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi
|
||||
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,
|
||||
"unit_price": round(unit, 2), "total": round(unit * line.quantity, 2),
|
||||
"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", []),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user