Files
xenia-pos-local/local_backend/routers/settings.py
T
bonaminandClaude Opus 5.5 f6fcfb7736 feat(manager): every settings tab on v2 (platform-v2 step 6.14a)
- Settings: tabs in the address (?tab=), Fiscal only with the fiscal app, Appearance only with the waiter app
- General: version / update / license / state / uptime, the local network (address by hand or found, the pairing QR),
  what is set up, export / import of the catalogue and the tables (a wrong file refused, two confirmations), support lock
- Sign-in & security: idle lock / sign-out (seconds..hours, warning when sign-out comes first), recovery codes
- Operation: role permissions, waiters' own shifts and takings, card payments, tables and orders, courses (add, rename,
  colour, order), quick notes, table flags (emoji, colour, white/black text, on/off), quick messages, send the QR menu now
- Appearance: the waiter app's table-card colours per state, light and dark, flash, colour picker with opacity, reset
- Fiscal: on/off, driver, folders with a reachability check, clerk / card terminal numbers, receipt end lines, VAT groups
- Development: pretend printing
- dropped: the v1 'automatic store schedule' switches (kept in the browser only, nothing read them) and the second time-zone card
- backend: JSON settings must be JSON (validation.setting_value); fiscal folders are plain paths (were typed json)
- venue colour data in sections/venueColours.js (guard DATA); store/tableColourStore and Settings/tabs deleted
- tests: settings.test.mjs (5), test_settings_json.py, e2e manager.mjs 'settings v2' (12 checks)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:41:14 +02:00

93 lines
3.7 KiB
Python

from core import i18n, timeutil
from core.errors import XeniaError
from core.timeutil import utcnow
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from datetime import datetime, timezone
from database import get_db
from models.settings import PosSettings
from schemas.settings import UpdateSettingRequest
from routers.deps import get_current_user, require_settings_manager
from models.user import User
router = APIRouter()
# Settings are declared by the module manifests (SettingDef; APPS_PLATFORM §4.1).
# These two views are derived from the registry, so a module adds a setting by
# declaring it in its manifest. Readers that query PosSettings directly still need
# the install rows seeded by migration 0001 (see plan step 1.3 notes).
# Functions, not module constants: the registry imports this router while validating.
def valid_settings() -> dict[str, str]:
from core.modules.registry import setting_defs
return {k: sd.description for k, (sd, _m) in setting_defs().items()}
def defaults() -> dict[str, str]:
from core.modules.registry import setting_defs
return {k: sd.default for k, (sd, _m) in setting_defs().items()}
@router.get("/")
def get_all_settings(
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
stored = {s.key: s.value for s in db.query(PosSettings).all()}
result = {}
dflt = defaults()
for key, description in valid_settings().items():
result[key] = {
"value": stored.get(key, dflt.get(key, "true")),
"description": description,
}
return result
@router.put("/{key}")
def update_setting(
key: str,
body: UpdateSettingRequest,
db: Session = Depends(get_db),
user: User = Depends(require_settings_manager),
):
if key not in valid_settings():
raise XeniaError("settings.unknown_key", key=key)
from core.modules.registry import setting_defs
sd = setting_defs()[key][0]
if (sd.type == "enum" and body.value not in sd.choices) or (sd.type == "bool" and body.value not in ("true", "false")) or (sd.type == "int" and not body.value.lstrip("-").isdigit()):
raise XeniaError("validation.setting_value", key=key, value=body.value)
if sd.type == "json": # 6.14a: a broken JSON setting (courses, quick notes, table colours…) would break the apps reading it
import json
try:
json.loads(body.value)
except ValueError:
raise XeniaError("validation.setting_value", key=key, value=body.value[:40])
if key == "venue.timezone":
try:
timeutil.validate_tz(body.value)
except ValueError:
raise XeniaError("validation.unknown_timezone", timezone=body.value)
if key == "venue.language" and not i18n.is_supported(body.value):
raise XeniaError("validation.unknown_language", language=body.value)
if key == "business_day.rollover_hour":
if not (body.value.isdigit() and 0 <= int(body.value) <= 23):
raise XeniaError("validation.range", status=422, field='rollover_hour', min=0, max=23)
setting = db.query(PosSettings).filter(PosSettings.key == key).first()
if setting:
setting.value = body.value
setting.updated_at = utcnow()
setting.updated_by_id = user.id
else:
setting = PosSettings(key=key, value=body.value, updated_by_id=user.id)
db.add(setting)
db.commit()
db.refresh(setting)
if key in ("venue.timezone", "business_day.rollover_hour"):
timeutil.invalidate() # live: next call re-reads the setting
if key == "venue.language":
i18n.invalidate()
return {"key": setting.key, "value": setting.value}