feat(backend): error codes, backend i18n (en/el) and language fields

Platform v2 step 1.2 (APPS_PLATFORM D-12, §3.2, §8).
- core/errors.py: XeniaError + CODES registry; handlers give every error the
  {"error": {code, params, message}, "detail"} shape: XeniaError, wrapped
  HTTPException (http.<status>, detail untouched), validation.invalid (FastAPI
  detail list kept), and internal.error 500 with the request id (body, header
  and log line)
- orders: the 18 "Order not found" raises -> XeniaError("order.not_found")
- core/i18n: t(key, lang, **params) with en/el JSON (en fallback), venue/zone/
  user language resolution, normalize_language; 56 print keys
- printer_service: every printed label goes through keys. Kitchen,
  cancellation and service-item tickets print in the prep zone's language
  (-> venue.language); reports/receipts/synopsis in venue.language. Greek
  output is unchanged. Print retries now pass the job's zone (language and
  item grouping were lost on retries)
- users.language, prep_zones.language (revision 0003), setting venue.language
  (default en); editable via PATCH /auth/me, staff update, prep zones API;
  "" = inherit
- tests: error shapes, key/placeholder parity, fallback, kitchen ticket per
  zone/venue language, language APIs; pack rule CS-12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 17:29:31 +02:00
co-authored by Claude Opus 5.5
parent ab1e61a10f
commit 968b6c78fb
21 changed files with 901 additions and 115 deletions
+128
View File
@@ -0,0 +1,128 @@
"""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})."),
"module.disabled": (403, "The {module} module is turned off."),
"module.not_licensed": (402, "This site's license doesn't include {module}."),
"license.limit_reached": (402, "License limit reached for {limit} ({max})."),
"license.expired": (402, "The license has expired."),
# identity
"auth.invalid_credentials": (401, "Wrong username or password."),
"auth.session_ended": (401, "Your session has ended. Please log in again."),
"device.revoked": (401, "This device was removed. Pair it again."),
"device.not_paired": (401, "This device isn't paired with the venue."),
# validation
"validation.invalid": (422, "Some fields are invalid."),
"validation.unknown_language": (422, "Unsupported language: {language}."),
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
# server
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
# domain
"order.not_found": (404, "Order {order_id} not found."),
}
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)
+139
View File
@@ -0,0 +1,139 @@
"""Backend translations for text the backend itself renders (APPS_PLATFORM D-12, §8).
What uses it: printed tickets and reports, and later server-rendered notification text.
What does NOT: API errors (they return codes + English, core/errors.py) and UI text
(frontends translate with i18next).
Files: core/i18n/<lang>.json, nested objects; keys are dotted paths ("print.ticket.order").
English (en.json) is the source and the fallback: a key missing in another language
falls back to English; a key missing in English returns the key itself and logs a warning.
Placeholders use str.format syntax: "Table {table}", "TOTAL: {total:.2f}e".
Language resolution (§8): user.language -> device language (step 1.8) -> venue.language -> "en".
Printing: prep_zone.language -> venue.language.
Agent notes:
- Add a key to en.json first, then el.json. tests/test_i18n.py checks both files have
the same keys and the same placeholders.
- Greek print text is written WITHOUT accents on purpose: the thermal printers use
code page CP737, and the venue's tickets have always looked like that.
- The venue language is cached; the settings router calls invalidate() when it changes.
"""
from __future__ import annotations
import json
import logging
import threading
from pathlib import Path
logger = logging.getLogger("xenia.i18n")
_DIR = Path(__file__).resolve().parent
DEFAULT_LANGUAGE = "en"
def _flatten(obj: dict, prefix: str = "") -> dict[str, str]:
out = {}
for k, v in obj.items():
key = f"{prefix}{k}"
if isinstance(v, dict):
out.update(_flatten(v, key + "."))
else:
out[key] = str(v)
return out
def _load() -> dict[str, dict[str, str]]:
return {f.stem: _flatten(json.loads(f.read_text(encoding="utf-8"))) for f in sorted(_DIR.glob("*.json"))}
CATALOG: dict[str, dict[str, str]] = _load()
SUPPORTED_LANGUAGES: tuple[str, ...] = tuple(sorted(CATALOG))
def is_supported(lang: str | None) -> bool:
return lang in CATALOG
def t(key: str, lang: str | None = None, **params) -> str:
"""Translate key into lang (fallback: English, then the key itself)."""
template = CATALOG.get(lang or DEFAULT_LANGUAGE, {}).get(key)
if template is None:
template = CATALOG[DEFAULT_LANGUAGE].get(key)
if template is None:
logger.warning("i18n.missing_key key=%s lang=%s", key, lang)
return key
try:
return template.format(**params) if params else template
except (KeyError, IndexError, ValueError):
logger.warning("i18n.bad_params key=%s lang=%s params=%s", key, lang, sorted(params))
return template
# ── language resolution ──────────────────────────────────────────────────────
_lock = threading.Lock()
_cache: dict = {}
def configure(venue_language: str | None = None) -> None:
with _lock:
if venue_language is not None:
_cache["venue"] = venue_language
def invalidate() -> None:
with _lock:
_cache.clear()
def venue_language() -> str:
"""The `venue.language` setting (default "en"), cached."""
with _lock:
lang = _cache.get("venue")
if lang is None:
lang = DEFAULT_LANGUAGE
try:
from database import SessionLocal
from models.settings import PosSettings
db = SessionLocal()
try:
row = db.query(PosSettings).filter(PosSettings.key == "venue.language").first()
if row and is_supported(row.value):
lang = row.value
finally:
db.close()
except Exception:
pass
with _lock:
_cache["venue"] = lang
return lang
def normalize_language(value):
"""API input for a language field: "" or None -> None (inherit); a supported code -> itself.
Anything else raises XeniaError("validation.unknown_language")."""
if value is None or value == "":
return None
if not is_supported(value):
from core.errors import XeniaError
raise XeniaError("validation.unknown_language", language=value)
return value
def resolve_language(*candidates: str | None) -> str:
"""First supported language among candidates (most specific first), else the venue's."""
for c in candidates:
if is_supported(c):
return c
return venue_language()
def user_language(user) -> str:
"""§8 order for a user: user.language -> (device, step 1.8) -> venue -> en."""
return resolve_language(getattr(user, "language", None))
def zone_language(zone) -> str:
"""Language of tickets printed for a prep zone: zone.language -> venue."""
return resolve_language(getattr(zone, "language", None))
+72
View File
@@ -0,0 +1,72 @@
{
"print": {
"aligned": {
"order": "Παραγγελια: #{value}",
"table": "Τραπεζι: {value}",
"time": "Ωρα: {value}"
},
"cancel": {
"banner": "*** AKYPΩΣH ***"
},
"receipt": {
"closed": "Εκλεισε: {value}",
"opened": "Ανοιχτηκε: {value}",
"order_title": "ΠΑΡΑΓΓΕΛΙΑ #{value}"
},
"report": {
"avg_duration": "Μ. διαρκεια: {minutes:.0f} λεπτα",
"categories_title": "ΑΝΑΦΟΡΑ ΚΑΤΗΓΟΡΙΩΝ",
"details": "ΑΝΑΛΥΤΙΚΑ",
"from": "Απο: {value}",
"grand_total": "ΣΥΝΟΛΟ ΟΛΩΝ",
"items": "Αντικειμενα: {value}",
"orders": "Παραγγελιες: {value}",
"pct_revenue": "% Εσοδων",
"pct_units": "% Τεμαχιων",
"period": "Περιοδος: {value}",
"prep_zone_title": "ΖΩΝΗ ΠΡΟΕΤΟΙΜΑΣΙΑΣ",
"print_jobs": "Εκτυπωσεις: {value}",
"printer": "Εκτυπωτης: {value}",
"printer_title": "ΑΝΑΦΟΡΑ ΕΚΤΥΠΩΤΗ",
"product_breakdown": "ΑΝΑΛΥΣΗ ΠΡΟΙΟΝΤΩΝ",
"product_shares": "{revenue:.2f}e | {rev}% εσ. {qty}% τεμ.",
"products_full_title": "ΠΛΗΡΗΣ ΑΝΑΛΥΣΗ ΠΡΟΙΟΝΤΩΝ",
"products_title": "ΑΝΑΦΟΡΑ ΠΡΟΙΟΝΤΩΝ",
"qty_units": "{value} τεμ.",
"revenue": "Εσοδα",
"table": "Τραπεζι: {value}",
"table_orders_avg": "{count} παρ. / μ.ο. {avg:.2f}e",
"tables_title": "ΑΝΑΦΟΡΑ ΤΡΑΠΕΖΙΩΝ",
"to": "Εως: {value}",
"total": "ΣΥΝΟΛΟ: {value:.2f}e",
"total_items": "Συνολο ειδων: {value}",
"total_qty": "Συνολο τεμ.: {value}",
"units": "Τεμαχια",
"value": "Αξια: {value:.2f}e",
"value_caps": "ΑΞΙΑ: {value:.2f}e",
"waiter": "Σερβιτορος: {value}",
"waiter_title": "ΑΝΑΦΟΡΑ ΣΕΡΒΙΤΟΡΟΥ",
"workday": "Εργασιμη: {value}"
},
"synopsis": {
"paid": "ΠΛΗΡΩΜΕΝΑ:",
"paid_total": "Πληρωμενο: {value:.2f}e",
"pending": "ΕΚΚΡΕΜΗ:",
"remaining": "Εκκρεμει: {value:.2f}e",
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ"
},
"ticket": {
"compact_guests": " | {count}ατ.",
"compact_header": "Παρ. #{order} | Τρ. {table} | {time} | {waiter}",
"date_label": "Ημερομηνια:",
"end": "Τελος Παραγγελιας",
"guests_label": "Ατομα:",
"note": "Σημ: {note}",
"order_title": "Παραγγελια #{order}",
"table_label": "Τραπεζι:",
"table_value": "Τραπεζι {table}",
"waiter_label": "Σερβιτορος:",
"without": "ΧΩΡΙΣ:"
}
}
}
+72
View File
@@ -0,0 +1,72 @@
{
"print": {
"aligned": {
"order": "Order: #{value}",
"table": "Table: {value}",
"time": "Time: {value}"
},
"cancel": {
"banner": "*** CANCELLED ***"
},
"receipt": {
"closed": "Closed: {value}",
"opened": "Opened: {value}",
"order_title": "ORDER #{value}"
},
"report": {
"avg_duration": "Avg. duration: {minutes:.0f} min",
"categories_title": "CATEGORY REPORT",
"details": "DETAILS",
"from": "From: {value}",
"grand_total": "ALL PRINTERS",
"items": "Items: {value}",
"orders": "Orders: {value}",
"pct_revenue": "% revenue",
"pct_units": "% units",
"period": "Period: {value}",
"prep_zone_title": "PREP ZONE",
"print_jobs": "Print jobs: {value}",
"printer": "Printer: {value}",
"printer_title": "PRINTER REPORT",
"product_breakdown": "PRODUCT BREAKDOWN",
"product_shares": "{revenue:.2f}e | {rev}% rev. {qty}% qty",
"products_full_title": "FULL PRODUCT BREAKDOWN",
"products_title": "PRODUCT REPORT",
"qty_units": "{value} pcs",
"revenue": "Revenue",
"table": "Table: {value}",
"table_orders_avg": "{count} ord. / avg {avg:.2f}e",
"tables_title": "TABLE REPORT",
"to": "To: {value}",
"total": "TOTAL: {value:.2f}e",
"total_items": "Total items: {value}",
"total_qty": "Total qty: {value}",
"units": "Units",
"value": "Value: {value:.2f}e",
"value_caps": "VALUE: {value:.2f}e",
"waiter": "Waiter: {value}",
"waiter_title": "WAITER REPORT",
"workday": "Workday: {value}"
},
"synopsis": {
"paid": "PAID:",
"paid_total": "Paid: {value:.2f}e",
"pending": "PENDING:",
"remaining": "Remaining: {value:.2f}e",
"title": "ORDER SUMMARY"
},
"ticket": {
"compact_guests": " | {count}pax",
"compact_header": "Ord. #{order} | Tbl {table} | {time} | {waiter}",
"date_label": "Date:",
"end": "End of order",
"guests_label": "Guests:",
"note": "Note: {note}",
"order_title": "Order #{order}",
"table_label": "Table:",
"table_value": "Table {table}",
"waiter_label": "Waiter:",
"without": "NO:"
}
}
}
+2
View File
@@ -249,6 +249,8 @@ class RequestContextMiddleware:
req_id = new_request_id()
token = _ctx.set({"req": req_id, "user": None, "device": None})
# Also on request.state: the last-resort error handler runs outside this middleware
scope.setdefault("state", {})["request_id"] = req_id
start = time.perf_counter()
status_holder = {"code": None}