"""The badges a menu board can put on a product (owner review 5, 2026-11-21): the venue's own list, kept in the setting `signage.badges` (JSON), edited under Signage → Message & settings. Each badge has a key (what boards store), its name in Greek and English, its colours (background, text: None = white or black, whichever reads) and an icon (a name from ICONS, drawn by @xenia/signage). Its colours are the defaults: a board may give all its badges one colour of its own. Until the venue changes it, the list is DEFAULTS (the seven badges boards had before).""" from __future__ import annotations import json import re from typing import Dict, List, Optional from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator SETTING = "signage.badges" HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$" KEY = r"^[a-z0-9][a-z0-9_-]{0,23}$" # the icons a badge can have (lucide names; @xenia/signage BADGE_ICONS draws the same list) ICONS = ( "sparkles", "chef-hat", "tag", "star", "flame", "sprout", "leaf", "vegan", "wheat", "wheat-off", "fish", "shrimp", "beef", "drumstick", "egg", "milk", "nut", "carrot", "salad", "pizza", "hamburger", "sandwich", "soup", "croissant", "ice-cream-cone", "cake-slice", "coffee", "cup-soda", "wine", "beer", "martini", "glass-water", "citrus", "cherry", "apple", "heart", "award", "thumbs-up", "clock", "percent", "gift", "crown", "zap", "snowflake", ) DEFAULTS = [ {"key": "new", "names": {"el": "Νέο", "en": "New"}, "colour": "#22c55e", "text_colour": None, "icon": "sparkles"}, {"key": "chef", "names": {"el": "Πρόταση σεφ", "en": "Chef's pick"}, "colour": "#f59e0b", "text_colour": None, "icon": "chef-hat"}, {"key": "offer", "names": {"el": "Προσφορά", "en": "Offer"}, "colour": "#ef4444", "text_colour": None, "icon": "tag"}, {"key": "popular", "names": {"el": "Δημοφιλές", "en": "Popular"}, "colour": "#f472b6", "text_colour": None, "icon": "star"}, {"key": "spicy", "names": {"el": "Καυτερό", "en": "Spicy"}, "colour": "#dc2626", "text_colour": None, "icon": "flame"}, {"key": "vegetarian", "names": {"el": "Χορτοφαγικό", "en": "Vegetarian"}, "colour": "#16a34a", "text_colour": None, "icon": "sprout"}, {"key": "vegan", "names": {"el": "Vegan", "en": "Vegan"}, "colour": "#15803d", "text_colour": None, "icon": "vegan"}, ] class BadgeDef(BaseModel): model_config = ConfigDict(extra="forbid") key: str = Field(pattern=KEY) names: Dict[str, str] = Field(default_factory=dict) colour: str = Field(default="#f59e0b", pattern=HEX) text_colour: Optional[str] = Field(default=None, pattern=HEX) icon: Optional[str] = None @field_validator("names") @classmethod def _names(cls, v): out = {k: " ".join(str(x).split())[:24] for k, x in v.items() if k in ("el", "en")} out = {k: x for k, x in out.items() if x} if not out: raise ValueError("a badge has a name") return out @field_validator("icon") @classmethod def _icon(cls, v): if v is not None and v not in ICONS: raise ValueError("an icon of the list") return v class BadgeList(BaseModel): model_config = ConfigDict(extra="forbid") badges: List[BadgeDef] = Field(default_factory=list, max_length=30) @model_validator(mode="after") def _unique(self): keys = [b.key for b in self.badges] if len(set(keys)) != len(keys): raise ValueError("each badge has its own key") return self def load(db) -> list[dict]: from models.settings import PosSettings row = db.query(PosSettings).filter(PosSettings.key == SETTING).first() if row is None or not row.value: return [dict(b) for b in DEFAULTS] try: return BadgeList(badges=json.loads(row.value)).model_dump()["badges"] except Exception: # noqa: BLE001 — a broken setting falls back to the defaults return [dict(b) for b in DEFAULTS] def save(db, badges: list[BadgeDef]) -> list[dict]: from models.settings import PosSettings value = json.dumps([b.model_dump() for b in badges], ensure_ascii=False) row = db.query(PosSettings).filter(PosSettings.key == SETTING).first() if row is None: db.add(PosSettings(key=SETTING, value=value)) else: row.value = value return [b.model_dump() for b in badges] def new_key(name: str, taken: set) -> str: """A key for a new badge from its name (the editor makes its own; kept for scripts).""" base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:20] or "badge" key, n = base, 2 while key in taken: key, n = f"{base}-{n}", n + 1 return key