- signage_schedules (Alembic 0030): entries {playlist, days, hours (may pass
midnight), dates, priority} and a fallback playlist. A screen's `schedule`
(ref) wins over its single playlist.
- services/signage_schedule.pick (pure): highest priority, then the most
specific (dates > days > hours), then the later entry; no match → fallback.
- GET /api/signage/screen with a schedule: the schedule (with the venue's time
zone) and every playlist in it, `playlist` = the one playing now, so the
player can switch while the server is down.
- schedule_worker (signage module, 30 s) tells a screen when its pick changes.
- /api/signage/schedules CRUD (playing now, the screens on it); deleting a
playlist takes it out of schedules; changes reach screens through schedules.
- Devices page: a signage screen's Schedule.
- tests: test_signage_schedule.py (6); 526 passed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
217 lines
14 KiB
Python
217 lines
14 KiB
Python
"""API errors as stable codes (APPS_PLATFORM D-12, §3.2).
|
|
|
|
Every error response has this shape:
|
|
{"error": {"code": "order.not_found", "params": {"order_id": 7}, "message": "Order 7 not found."},
|
|
"detail": "Order 7 not found."}
|
|
- code: stable identifier; frontends translate it (i18n key `errors.<code>`).
|
|
- params: values the translated text can use.
|
|
- message: English, for logs, curl and un-migrated screens.
|
|
- detail: kept for frontends written before v2 (they read `detail`).
|
|
|
|
New and converted code raises XeniaError:
|
|
raise XeniaError("order.not_found", order_id=order_id)
|
|
The status comes from the registry below; pass status= only to override it.
|
|
Plain HTTPException (still in most v1 routers; converted gradually, plan step 6.x)
|
|
is wrapped as code "http.<status>" with its original `detail` untouched.
|
|
Request validation errors become "validation.invalid" with the field errors in params.
|
|
Unhandled exceptions become "internal.error" (500) with the request id in params.
|
|
|
|
Agent notes:
|
|
- Add every new code to CODES with its HTTP status and English message (str.format
|
|
placeholders from params). tests/test_errors.py fails on a raised code that
|
|
isn't registered (via XeniaError's constructor).
|
|
- Codes are part of the API contract: never rename one; add a new one instead.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from http import HTTPStatus
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.encoders import jsonable_encoder
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
logger = logging.getLogger("xenia.errors")
|
|
|
|
# code -> (HTTP status, English message)
|
|
CODES: dict[str, tuple[int, str]] = {
|
|
# access / licensing / modules (filled in by steps 1.3-1.9)
|
|
"access.denied": (403, "You don't have permission to do this ({key})."),
|
|
"access.override_possible": (403, "A manager can approve this ({key})."),
|
|
"access.override_invalid": (403, "This approval isn't valid any more. Ask a manager again."),
|
|
"access.not_overridable": (422, "{key} can't be approved by a manager."),
|
|
"access.approver_lacks_key": (403, "That account can't approve this ({key})."),
|
|
"access.override_rate_limited": (429, "Too many wrong PINs. Wait a few minutes and try again."),
|
|
"access.unknown_key": (422, "There is no permission {key}."),
|
|
"access.cannot_grant": (403, "You can only give permissions you have yourself ({key})."),
|
|
"module.disabled": (403, "The {module} module is turned off."),
|
|
"module.not_licensed": (402, "This site's license doesn't include {module}."),
|
|
"module.unknown": (404, "There is no module {module}."),
|
|
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
|
|
"license.limit_reached": (402, "License limit reached for {module} {limit} ({max})."),
|
|
"license.expired": (402, "The license has expired."),
|
|
"license.history_limited": (402, "This license shows only the last {days} days of history ({module})."),
|
|
# identity
|
|
"auth.invalid_credentials": (401, "Wrong username or password."),
|
|
"auth.session_ended": (401, "Your session has ended. Please log in again."),
|
|
"auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."),
|
|
"auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."),
|
|
"auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."),
|
|
"auth.username_required": (422, "Enter your username."),
|
|
"auth.client_not_allowed": (403, "This account can't use the {client} app."),
|
|
"auth.session_not_found": (404, "Session not found."),
|
|
"auth.wrong_pin": (401, "Wrong PIN. {attempts_left} tries left before you are signed out."),
|
|
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
|
|
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
|
|
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
|
|
"pos.shift_required": (409, "Start your shift before selling."),
|
|
"pos.payment_invalid": (422, "This payment doesn't add up ({reason})."),
|
|
"pos.fiscal_vat_missing": (422, "Fiscal receipts are on, but these products have no VAT group: {names}."),
|
|
"pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."),
|
|
"pos.table_not_found": (404, "Table {table_id} not found."),
|
|
"pos.table_not_yours": (403, "{table} isn't in your zones. A manager can add the zone to your account."),
|
|
"pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."),
|
|
"pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."),
|
|
"order.items_not_combinable": (422, "These lines can't be combined: only unpaid lines of the same item, with the same choices, note, price and kitchen state, and no discount, deal or tab."),
|
|
"order.not_sold_here": (422, "{name} isn't sold for this kind of order."),
|
|
"order.lines_required": (422, "This app sent the order in an old format. Update the app and send it again."),
|
|
"order.line.product_unavailable": (422, "{name} isn't available any more (line {line})."),
|
|
"order.line.option_gone": (422, "{name}: a chosen option doesn't exist any more (line {line}). Remove it and add it again."),
|
|
"order.line.choice_missing": (422, "{name}: a required choice is missing (line {line})."),
|
|
"order.line.quantity": (422, "{name}: that quantity isn't allowed (line {line})."),
|
|
"order.line.price": (422, "{name}: that price change isn't allowed (line {line})."),
|
|
"order.line.client_price": (422, "{name}: the app sent its own prices, but prices come from the server (line {line}). Update the app."),
|
|
"fees.area_not_found": (404, "Delivery area {area_id} not found."),
|
|
"fees.rule_not_found": (404, "Fee rule {rule_id} not found."),
|
|
"fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."),
|
|
"fees.order_invalid": (422, "The new order must list every rule once."),
|
|
"fees.vat_group_unknown": (422, "VAT group {vat_group_id} isn't one of the fiscal machine's groups."),
|
|
"refund.invalid": (422, "This refund doesn't add up ({reason})."),
|
|
"refund.too_old": (409, "Only payments from today's business day can be refunded at the counter."),
|
|
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
|
|
"online.not_found": (404, "Online order {order_id} not found."),
|
|
"online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."),
|
|
"caller_id.key_invalid": (403, "The phone system's key is missing or wrong."),
|
|
"display.qr_url_missing": (422, "Enter the link the QR code opens."),
|
|
"display.look_unknown": (404, "Look {look_id} not found."),
|
|
"display.look_default": (409, "The default look can't be deleted. Make another look the default first."),
|
|
"display.not_a_display": (404, "Device {device_id} isn't a customer display."),
|
|
"media.not_found": (404, "File {media_id} isn't in the media library."),
|
|
"media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4 or WebM)."),
|
|
"media.too_big": (413, "The file is too big (at most {max_mb} MB)."),
|
|
"media.too_many_pixels": (422, "The picture is too large (at most {max_mp} megapixels)."),
|
|
"media.unreadable": (422, "This picture can't be read. Save it again as JPG or PNG and upload it."),
|
|
"media.in_use": (409, "This file is used by {uses}. Remove it there first."),
|
|
"media.not_a_picture": (422, "Pick a picture here, not a video."),
|
|
"signage.playlist_unknown": (404, "Playlist {playlist_id} not found."),
|
|
"signage.slide_unknown": (404, "Slide {slide_id} not found."),
|
|
"signage.not_a_screen": (404, "Device {device_id} isn't a signage screen."),
|
|
"signage.schedule_unknown": (404, "Schedule {schedule_id} not found."),
|
|
"signage.not_a_video": (422, "Pick a video for this slide."),
|
|
"signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."),
|
|
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
|
|
"signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
|
|
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
|
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
|
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
|
"reservation.table_unknown": (404, "Table {table_id} not found."),
|
|
"reservation.table_busy": (409, "That table already has an open order. Pick another table, or close that order first."),
|
|
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
|
|
"kds.item_claimed": (409, "{name} is already on this item."),
|
|
"kds.claim_needs_staff": (403, "Only a staff member can claim an item."),
|
|
"device.revoked": (401, "This device was removed. Pair it again."),
|
|
"device.not_paired": (401, "This device isn't paired with the venue."),
|
|
"device.out_of_scope": (403, "A {app} device can't do this ({key})."),
|
|
"device.required": (401, "This login belongs to a paired device. Use it from that device."),
|
|
"device.not_found": (404, "Device {device_id} not found."),
|
|
"device.pair_code_invalid": (404, "That pairing code is wrong or has expired."),
|
|
"device.pair_rate_limited": (429, "Too many pairing requests. Wait a few minutes and try again."),
|
|
"device.not_an_app": (422, "{app} is not an app that runs on a device."),
|
|
"device.login_mode_invalid": (422, "A {app} device can't use the login mode {mode}."),
|
|
"device.link_invalid": (422, "Device {device_id} can't be linked to this device."),
|
|
# validation
|
|
"validation.invalid": (422, "Some fields are invalid."),
|
|
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
|
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
|
|
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
|
|
"validation.device_config": (422, "This device setting is not valid: {key}."),
|
|
# server
|
|
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
|
# domain
|
|
"order.not_found": (404, "Order {order_id} not found."),
|
|
"notification.not_found": (404, "Notification {notification_id} not found."),
|
|
"system.log_not_found": (404, "There is no log file for {date}."),
|
|
"catalog.unknown_category": (422, "There is no category {category_id}."),
|
|
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
|
|
}
|
|
|
|
|
|
class XeniaError(Exception):
|
|
"""An API error with a registered code. raise XeniaError("order.not_found", order_id=5)."""
|
|
|
|
def __init__(self, code: str, status: int | None = None, **params):
|
|
if code not in CODES:
|
|
raise KeyError(f"unregistered error code {code!r}: add it to core/errors.py CODES")
|
|
default_status, template = CODES[code]
|
|
self.code = code
|
|
self.status = status or default_status
|
|
self.params = params
|
|
try:
|
|
self.message = template.format(**params)
|
|
except (KeyError, IndexError):
|
|
self.message = template
|
|
super().__init__(self.message)
|
|
|
|
|
|
def error_body(code: str, message: str, params: dict | None = None, detail=None) -> dict:
|
|
return {"error": {"code": code, "params": params or {}, "message": message},
|
|
"detail": message if detail is None else detail}
|
|
|
|
|
|
async def _xenia_error_handler(request: Request, exc: XeniaError):
|
|
return JSONResponse(error_body(exc.code, exc.message, exc.params), status_code=exc.status)
|
|
|
|
|
|
async def _http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
detail = exc.detail
|
|
if isinstance(detail, str):
|
|
message = detail
|
|
elif isinstance(detail, dict) and isinstance(detail.get("message"), str):
|
|
message = detail["message"]
|
|
else:
|
|
try:
|
|
message = HTTPStatus(exc.status_code).phrase
|
|
except ValueError:
|
|
message = "Error"
|
|
return JSONResponse(error_body(f"http.{exc.status_code}", message, detail=detail),
|
|
status_code=exc.status_code, headers=getattr(exc, "headers", None))
|
|
|
|
|
|
async def _validation_handler(request: Request, exc: RequestValidationError):
|
|
errors = [{"field": ".".join(str(p) for p in e.get("loc", ())[1:]) or None,
|
|
"type": e.get("type"), "message": e.get("msg")} for e in exc.errors()]
|
|
# `detail` stays FastAPI's usual list, so existing frontends keep working
|
|
return JSONResponse(error_body("validation.invalid", CODES["validation.invalid"][1],
|
|
{"errors": jsonable_encoder(errors)}, detail=jsonable_encoder(exc.errors())),
|
|
status_code=422)
|
|
|
|
|
|
async def _unhandled_handler(request: Request, exc: Exception):
|
|
"""Last resort: a bug. Logged with the traceback; the client gets the request id
|
|
(also in the X-Request-ID header) so support can find the log lines."""
|
|
from core.logging import current_request_id
|
|
rid = getattr(request.state, "request_id", None) or current_request_id() or "-"
|
|
logger.exception("http.unhandled_error request_id=%s path=%s", rid, request.url.path)
|
|
err = XeniaError("internal.error", request_id=rid)
|
|
return JSONResponse(error_body(err.code, err.message, err.params), status_code=500,
|
|
headers={"X-Request-ID": rid})
|
|
|
|
|
|
def install_error_handlers(app: FastAPI) -> None:
|
|
app.add_exception_handler(Exception, _unhandled_handler)
|
|
app.add_exception_handler(XeniaError, _xenia_error_handler)
|
|
app.add_exception_handler(StarletteHTTPException, _http_exception_handler)
|
|
app.add_exception_handler(RequestValidationError, _validation_handler)
|