"""The time model (APPS_PLATFORM D-11, §7). The ONLY place backend code gets "now" or converts zones. Rules (a guard test enforces the mechanical ones, tests/guards/test_no_naive_time.py): - A moment is an aware UTC datetime. Get "now" with utcnow(). Never datetime.now(), datetime.utcnow(), date.today() or an argument-less .astimezone(). - Every datetime column is UTCDateTime: writing a naive datetime raises; reads come back aware UTC. Pydantic then serialises them with "Z". - The venue's zone is an IANA name in the `venue.timezone` setting (default Europe/Athens). DST comes from the tz database (`tzdata` package). - Clock rules (happy hour 17:00-19:00, schedules) are local wall-clock times, evaluated in the venue zone: is_within(LocalClock(...), at_utc). - A business day has a business_date, fixed when the day opens: business_date_of(opened_at). A day opened before `business_day.rollover_hour` (default 6) belongs to the previous date. Reports group by it. - Durations are computed in UTC (end - start), never in local time. - API input: parse_api_datetime(). A value WITH an offset is converted to UTC; a naive value means venue-local wall time (that's what the manager's date pickers send); a date-only value means venue midnight. Agent notes: - Settings are cached. The settings router calls invalidate() when venue.timezone or business_day.rollover_hour changes, so a change applies live. - Tests set the zone without a database: configure(tz="Europe/Athens", rollover_hour=6). """ from __future__ import annotations import threading from dataclasses import dataclass from datetime import date, datetime, time, timedelta, timezone from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from sqlalchemy.types import DateTime, TypeDecorator UTC = timezone.utc DEFAULT_TZ = "Europe/Athens" DEFAULT_ROLLOVER_HOUR = 6 DB_FORMAT = "%Y-%m-%d %H:%M:%S.%f" # how UTCDateTime values look in SQLite (and raw-SQL writers must match) # ── now ────────────────────────────────────────────────────────────────────── def utcnow() -> datetime: """The current moment, aware UTC. The only way to get "now".""" return datetime.now(UTC) def ensure_utc(dt: datetime | None) -> datetime | None: """Aware datetime -> same moment in UTC. Naive -> ValueError (we never guess).""" if dt is None: return None if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None: raise ValueError(f"naive datetime refused (D-11): {dt!r}") return dt.astimezone(UTC) def iso_z(dt: datetime | None) -> str | None: """ISO-8601 in UTC with a Z, for hand-built JSON payloads.""" if dt is None: return None return ensure_utc(dt).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" def to_db_str(dt: datetime) -> str: """The storage text of a moment, for code that writes datetime columns with raw SQL.""" return ensure_utc(dt).strftime(DB_FORMAT) # ── venue settings (cached) ────────────────────────────────────────────────── _lock = threading.Lock() _cache: dict = {} def configure(tz: str | None = None, rollover_hour: int | None = None) -> None: """Set the cached values directly (tests, or a caller that already read the settings).""" with _lock: if tz is not None: _cache["tz"] = ZoneInfo(tz) if rollover_hour is not None: _cache["rollover"] = int(rollover_hour) def invalidate() -> None: """Forget cached settings; the next call re-reads them. Called when the settings change.""" with _lock: _cache.clear() def _read_setting(key: str) -> str | None: try: from database import SessionLocal from models.settings import PosSettings db = SessionLocal() try: row = db.query(PosSettings).filter(PosSettings.key == key).first() return row.value if row and row.value else None finally: db.close() except Exception: return None def validate_tz(name: str) -> ZoneInfo: """ZoneInfo for an IANA name, or ValueError.""" try: return ZoneInfo(name) except (ZoneInfoNotFoundError, ValueError, TypeError) as e: raise ValueError(f"unknown time zone: {name!r}") from e def venue_tz() -> ZoneInfo: with _lock: tz = _cache.get("tz") if tz is None: name = _read_setting("venue.timezone") or DEFAULT_TZ try: tz = validate_tz(name) except ValueError: tz = ZoneInfo(DEFAULT_TZ) with _lock: _cache["tz"] = tz return tz def rollover_hour() -> int: with _lock: h = _cache.get("rollover") if h is None: raw = _read_setting("business_day.rollover_hour") try: h = int(raw) if raw is not None else DEFAULT_ROLLOVER_HOUR if not 0 <= h <= 23: h = DEFAULT_ROLLOVER_HOUR except ValueError: h = DEFAULT_ROLLOVER_HOUR with _lock: _cache["rollover"] = h return h # ── conversions ────────────────────────────────────────────────────────────── def to_venue(dt: datetime | None) -> datetime | None: """A moment in venue wall-clock time (aware, venue zone).""" if dt is None: return None return ensure_utc(dt).astimezone(venue_tz()) def venue_now() -> datetime: return utcnow().astimezone(venue_tz()) def venue_date(dt: datetime | None = None) -> date: """The venue's calendar date of a moment (default: now).""" return to_venue(dt or utcnow()).date() def venue_strftime(dt: datetime | None, fmt: str, empty: str = "—") -> str: """Format a moment in venue time (tickets, labels).""" if dt is None: return empty return to_venue(dt).strftime(fmt) def venue_local_to_utc(local: datetime) -> datetime: """Venue wall-clock time (naive) -> UTC. In the repeated autumn hour the first occurrence is chosen (fold=0); a time skipped in spring maps forward.""" if local.tzinfo is not None: return ensure_utc(local) return local.replace(tzinfo=venue_tz()).astimezone(UTC) def venue_day_window(d: date) -> tuple[datetime, datetime]: """[start, end) in UTC of venue calendar day d (23 h or 25 h on DST days).""" return (venue_local_to_utc(datetime.combine(d, time.min)), venue_local_to_utc(datetime.combine(d + timedelta(days=1), time.min))) def parse_api_datetime(value: str | datetime | date | None) -> datetime | None: """API input -> aware UTC. With offset/Z: converted. Naive: venue-local. Date only: venue midnight.""" if value is None or value == "": return None if isinstance(value, datetime): dt = value elif isinstance(value, date): dt = datetime.combine(value, time.min) else: s = str(value).strip().replace("Z", "+00:00").replace("z", "+00:00") dt = datetime.fromisoformat(s) if dt.tzinfo is None: return venue_local_to_utc(dt) return ensure_utc(dt) # ── business date ──────────────────────────────────────────────────────────── def business_date_of(dt: datetime | None = None, rollover: int | None = None) -> date: """The business date a moment belongs to: venue date, minus one day before the rollover hour.""" local = to_venue(dt or utcnow()) h = rollover_hour() if rollover is None else rollover d = local.date() return d - timedelta(days=1) if local.hour < h else d def business_date_window(d: date, rollover: int | None = None) -> tuple[datetime, datetime]: """[start, end) in UTC of business date d: venue d at rollover hour -> d+1 at rollover hour.""" h = rollover_hour() if rollover is None else rollover return (venue_local_to_utc(datetime.combine(d, time(h))), venue_local_to_utc(datetime.combine(d + timedelta(days=1), time(h)))) # ── clock rules ────────────────────────────────────────────────────────────── @dataclass(frozen=True) class LocalClock: """A wall-clock window in venue time, e.g. LocalClock("17:00", "19:00"). days: weekdays it applies to (Mon=0 ... Sun=6); None = every day. The day is the one the window STARTS on, so 22:00-02:00 on Friday covers Saturday 01:00. end <= start means the window crosses midnight. start == end means all day. """ start: str end: str days: frozenset[int] | None = None def _t(self, s: str) -> time: return time.fromisoformat(s) def is_within(rule: LocalClock, at: datetime | None = None) -> bool: """True if moment `at` (default now) falls inside the venue-time window.""" local = to_venue(at or utcnow()) t, start, end = local.time().replace(tzinfo=None), rule._t(rule.start), rule._t(rule.end) if start == end: return rule.days is None or local.weekday() in rule.days if start < end: return start <= t < end and (rule.days is None or local.weekday() in rule.days) # crosses midnight: evening part belongs to today, early part to yesterday's window if t >= start: return rule.days is None or local.weekday() in rule.days if t < end: return rule.days is None or (local.weekday() - 1) % 7 in rule.days return False # ── SQLAlchemy type ────────────────────────────────────────────────────────── class UTCDateTime(TypeDecorator): """Every datetime column. Write: aware only (naive raises), stored as UTC text 'YYYY-MM-DD HH:MM:SS.ffffff'. Read: aware UTC.""" impl = DateTime cache_ok = True def process_bind_param(self, value, dialect): if value is None: return None if not isinstance(value, datetime): raise TypeError(f"UTCDateTime needs a datetime, got {type(value).__name__}") return ensure_utc(value).replace(tzinfo=None) def process_result_value(self, value, dialect): if value is None: return None if value.tzinfo is None: return value.replace(tzinfo=UTC) return value.astimezone(UTC)