"""Per-device settings of an app (plan step 3.1a): what the manager may store in devices.config and what the device reads back. - validate(fields, config, db) -> dict | None: the cleaned config to store. Unknown keys, wrong types, values outside choices/min/max and refs to missing rows raise validation.device_config {key}. None/{} -> None (all defaults). - effective(fields, stored, db=None) -> dict: every field, its stored value when still valid, else its default. What GET /api/devices/me returns, so a screen never handles a missing or stale value (an old free-form config, a prep zone that was deleted). - for_app(app_key) -> the app's ConfigFields (from its manifest's DeviceApp.config). Agent notes: - Fields are declared in the app's manifest (core/modules/model.py ConfigField). A new field needs its label in packages/i18n/locales/{en,el}/modules.json (`.config..label`, plus `.choices.` per choice); test_module_texts fails otherwise. The manager renders the fields generically (DeviceConfigFields.jsx). - `ref` sources: "prep_zones" (PrepZone ids), "devices:" (live devices of that app). """ from __future__ import annotations from core.errors import XeniaError MAX_STR = 200 def for_app(app_key: str) -> tuple: from core.access.context import device_app da = device_app(app_key) return tuple(da.config) if da else () def _bad(key: str): return XeniaError("validation.device_config", key=key) def _ref_exists(source: str, value: int, db) -> bool: if source == "prep_zones": from models.prep_zone import PrepZone return db.get(PrepZone, value) is not None if source.startswith("devices:"): from models.device import Device d = db.get(Device, value) return d is not None and d.revoked_at is None and d.app_key == source.split(":", 1)[1] return False def _clean(f, value, db, *, strict: bool): """The value as stored, or raise (strict) / return the default (not strict).""" def bad(): if strict: raise _bad(f.key) return f.default if f.type == "bool": return value if isinstance(value, bool) else bad() if f.type == "int": if isinstance(value, bool) or not isinstance(value, int): return bad() if (f.choices and value not in f.choices) or (f.min is not None and value < f.min) \ or (f.max is not None and value > f.max): return bad() return value if f.type == "str": return value.strip() if isinstance(value, str) and len(value) <= MAX_STR else bad() if f.type == "enum": return value if value in f.choices else bad() if f.type == "ref": if value is None: return None if isinstance(value, bool) or not isinstance(value, int): return bad() if db is not None and not _ref_exists(f.choices_from or "", value, db): return bad() return value return bad() def validate(fields, config, db) -> dict | None: if config is None: return None if not isinstance(config, dict): raise _bad("config") by_key = {f.key: f for f in fields} out = {} for key, value in config.items(): f = by_key.get(key) if f is None: raise _bad(key) out[key] = _clean(f, value, db, strict=True) return out or None def effective(fields, stored, db=None) -> dict: stored = stored if isinstance(stored, dict) else {} return {f.key: (_clean(f, stored[f.key], db, strict=False) if f.key in stored else f.default) for f in fields} def describe(fields) -> list[dict]: """The fields for the manager (module catalogue).""" return [{"key": f.key, "type": f.type, "default": f.default, "choices": list(f.choices), "min": f.min, "max": f.max, "choices_from": f.choices_from} for f in fields]