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:
@@ -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))
|
||||
@@ -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": "ΧΩΡΙΣ:"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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:"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user