feat(backend): manager override with one-time PIN approval for cancel, price change, over-limit discount
Platform v2 step 1.9 (APPS_PLATFORM D-10).
- Perm(..., overridable=True). check() answers access.override_possible (not
access.denied) for such keys, and consumes an X-Xenia-Override token for them.
- POST /api/access/override {key, username, pin}: the approver must hold the key
(module effective); returns a token valid 60 s, once, for that key and the
requesting session only (sha256 stored). Wrong PINs throttled per session.
GET /api/access/overrides: audit list (core.staff.manage).
- access_overrides table (revision 0008): who asked, session, who approved, device,
key, created/expires/used, target. The revision also grants core.devices.manage and
the new pricing.discounts.over_limit to existing owners/store managers.
- Overridable: ordering.orders.cancel (the three cancel endpoints; the order audit log
notes "override #n approved by user m"), ordering.prices.modify (price adjust), and
new pricing.discounts.over_limit (waiter discounts beyond their limits; the reason
goes in params). The venue switch discounts.enabled is never overridable.
- /orders/cancel-permissions adds override_possible; permission catalogues expose
`overridable`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,7 +3,8 @@ from core.errors import XeniaError
|
||||
from core.timeutil import parse_api_datetime, venue_strftime, utcnow
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status, BackgroundTasks
|
||||
from core.access.override import require_override
|
||||
|
||||
|
||||
def _iso(dt) -> str | None:
|
||||
@@ -25,7 +26,7 @@ from schemas.order import OrderCreate, OrderOut, OrderItemOut, AddItemsRequest,
|
||||
from services.pricing import (
|
||||
OrderContext, resolve_price, evaluate_deals,
|
||||
build_active_price_group_ids, write_price_events,
|
||||
check_waiter_discount_limits, _system_round,
|
||||
check_waiter_discount_limits, discounts_enabled, _system_round,
|
||||
)
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -66,6 +67,11 @@ def _waiter_can_cancel(user: User, db: Session) -> bool:
|
||||
return global_on and holds(user, "ordering.orders.cancel")
|
||||
|
||||
|
||||
def _approval_note(approval) -> str | None:
|
||||
"""Audit-log note for an action a manager approved with their PIN (D-10)."""
|
||||
return f"override #{approval.id} approved by user {approval.approved_by}" if approval is not None else None
|
||||
|
||||
|
||||
def _can_access_order(order: Order, user: User, db: Session) -> bool:
|
||||
"""Zone-based access: any waiter whose zone covers the order's table group may act on it.
|
||||
Standalone orders (table_id=None) are accessible to all waiters with any zone assignment."""
|
||||
@@ -206,7 +212,7 @@ def cancel_permissions(db: Session = Depends(get_db), user: User = Depends(get_c
|
||||
"""Return whether the current user is allowed to cancel orders."""
|
||||
is_manager = holds(user, "core.dashboard.access")
|
||||
if is_manager:
|
||||
return {"can_cancel": True, "reason": None}
|
||||
return {"can_cancel": True, "reason": None, "override_possible": False}
|
||||
can = _waiter_can_cancel(user, db)
|
||||
reason = None
|
||||
if not can:
|
||||
@@ -216,7 +222,8 @@ def cancel_permissions(db: Session = Depends(get_db), user: User = Depends(get_c
|
||||
reason = "global_disabled"
|
||||
elif not holds(user, "ordering.orders.cancel"):
|
||||
reason = "user_disabled"
|
||||
return {"can_cancel": can, "reason": reason}
|
||||
# A manager can approve a single cancellation with their PIN (D-10)
|
||||
return {"can_cancel": can, "reason": reason, "override_possible": not can}
|
||||
|
||||
|
||||
@router.get("/", response_model=List[OrderOut])
|
||||
@@ -742,6 +749,7 @@ def cancel_item(
|
||||
order_id: int,
|
||||
item_id: int,
|
||||
background_tasks: BackgroundTasks,
|
||||
request: Request,
|
||||
print_cancellation: bool = True,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
@@ -751,10 +759,12 @@ def cancel_item(
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
is_manager = holds(user, "core.dashboard.access")
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
raise HTTPException(status_code=403, detail="Δεν επιτρέπεται η ακύρωση παραγγελίας")
|
||||
if not is_manager and not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
approval = None
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
# a manager may approve this one cancellation with their PIN (D-10)
|
||||
approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
|
||||
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||
if not item:
|
||||
@@ -780,7 +790,7 @@ def cancel_item(
|
||||
li.cancelled_at = now
|
||||
cancelled_ids.append(li.id)
|
||||
|
||||
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=cancelled_ids)
|
||||
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=cancelled_ids, note=_approval_note(approval))
|
||||
db.commit()
|
||||
|
||||
should_print = print_cancellation if is_manager else True
|
||||
@@ -1073,6 +1083,7 @@ def pay_items_offline(
|
||||
def cancel_order(
|
||||
order_id: int,
|
||||
background_tasks: BackgroundTasks,
|
||||
request: Request,
|
||||
print_cancellation: bool = True,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
@@ -1082,10 +1093,12 @@ def cancel_order(
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
is_manager = holds(user, "core.dashboard.access")
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
raise HTTPException(status_code=403, detail="Δεν επιτρέπεται η ακύρωση παραγγελίας")
|
||||
if not is_manager and not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
approval = None
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
# a manager may approve this one cancellation with their PIN (D-10)
|
||||
approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
|
||||
|
||||
now = utcnow()
|
||||
|
||||
@@ -1105,6 +1118,8 @@ def cancel_order(
|
||||
order.closed_by = user.id
|
||||
|
||||
note = f"Ακύρωση — {len(cancelled_item_ids)} αντικείμενα ακυρώθηκαν" if cancelled_item_ids else None
|
||||
if approval is not None:
|
||||
note = "; ".join(x for x in (note, _approval_note(approval)) if x)
|
||||
_audit(db, order_id, "ORDER_CANCELLED", waiter_id=user.id,
|
||||
item_ids=cancelled_item_ids if cancelled_item_ids else None, note=note)
|
||||
db.commit()
|
||||
@@ -1125,6 +1140,7 @@ def cancel_items_bulk(
|
||||
order_id: int,
|
||||
body: CancelItemsRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
@@ -1134,10 +1150,12 @@ def cancel_items_bulk(
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
is_manager = holds(user, "core.dashboard.access")
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
raise HTTPException(status_code=403, detail="Δεν επιτρέπεται η ακύρωση παραγγελίας")
|
||||
if not is_manager and not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
approval = None
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
# a manager may approve this one cancellation with their PIN (D-10)
|
||||
approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
|
||||
|
||||
items = db.query(OrderItem).filter(
|
||||
OrderItem.id.in_(body.item_ids),
|
||||
@@ -1169,7 +1187,7 @@ def cancel_items_bulk(
|
||||
cancelled_ids.append(li.id)
|
||||
|
||||
if cancelled_ids:
|
||||
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=cancelled_ids)
|
||||
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=cancelled_ids, note=_approval_note(approval))
|
||||
db.commit()
|
||||
|
||||
should_print = body.print_cancellation if is_manager else True
|
||||
@@ -1468,12 +1486,12 @@ def adjust_item_price(
|
||||
order_id: int,
|
||||
item_id: int,
|
||||
body: PriceAdjustRequest,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Apply an on-the-fly price adjustment to an active order item."""
|
||||
if not (holds(user, "core.dashboard.access") or holds(user, "ordering.prices.modify")):
|
||||
raise HTTPException(status_code=403, detail="Δεν έχετε δικαίωμα τροποποίησης τιμών")
|
||||
"""Apply an on-the-fly price adjustment to an active order item. Without
|
||||
ordering.prices.modify a manager can approve it once (X-Xenia-Override, D-10)."""
|
||||
setting = db.query(PosSettings).filter(PosSettings.key == "orders.waiter_price_adjust_allowed").first()
|
||||
if not setting or setting.value != "true":
|
||||
raise HTTPException(status_code=403, detail="Price adjustment is disabled")
|
||||
@@ -1489,6 +1507,8 @@ def adjust_item_price(
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
if not (holds(user, "core.dashboard.access") or holds(user, "ordering.prices.modify")):
|
||||
require_override(request, db, "ordering.prices.modify", target=f"order:{order_id} item:{item_id}")
|
||||
|
||||
item.price_adjustment = body.price_adjustment
|
||||
db.commit()
|
||||
@@ -1506,6 +1526,7 @@ from schemas.pricing import ApplyDiscountRequest, ApplyDiscountResponse
|
||||
def apply_waiter_discount(
|
||||
order_id: int,
|
||||
body: ApplyDiscountRequest,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
@@ -1537,7 +1558,11 @@ def apply_waiter_discount(
|
||||
|
||||
item_unit_prices = {i.id: i.unit_price + i.price_adjustment for i in items}
|
||||
|
||||
# Validate limits before touching anything
|
||||
if not discounts_enabled(db):
|
||||
raise HTTPException(status_code=403, detail="Discounts are globally disabled")
|
||||
|
||||
# Validate limits before touching anything. Beyond them: pricing.discounts.over_limit,
|
||||
# or a manager approves this one discount with their PIN (D-10).
|
||||
ok, error_msg = check_waiter_discount_limits(
|
||||
waiter_id=user.id,
|
||||
order_id=order_id,
|
||||
@@ -1546,8 +1571,8 @@ def apply_waiter_discount(
|
||||
item_unit_prices=item_unit_prices,
|
||||
db=db,
|
||||
)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=403, detail=error_msg)
|
||||
if not ok and not holds(user, "pricing.discounts.over_limit"):
|
||||
require_override(request, db, "pricing.discounts.over_limit", target=f"order:{order_id}", reason=error_msg)
|
||||
|
||||
from models.pricing import PriceEventLog
|
||||
|
||||
|
||||
Reference in New Issue
Block a user