feat(backend): UTC time model - venue zone, business date, aware-only datetimes

Platform v2 step 1.1 (APPS_PLATFORM D-11, §7, D-24).
- core/timeutil.py: utcnow, venue_tz (venue.timezone, cached, invalidated on
  change - no restart), to_venue/venue_date/venue_strftime, parse_api_datetime
  (offset -> UTC; naive = venue-local; date = venue midnight), business_date_of
  /business_date_window (rollover hour, default 06:00), LocalClock + is_within,
  UTCDateTime column type (naive writes raise, reads are aware UTC), iso_z
- every model column is UTCDateTime; Pydantic UTCDatetime emits "...Z"
- business_days.business_date set at open; revision 0002 adds it (backfilled)
  and makes sync_events.created_at a UTCDateTime (AUTOINCREMENT restated)
- tz.py deleted; system.timezone setting replaced by venue.timezone (validated)
  + business_day.rollover_hour; manager timezone picker writes venue.timezone
- fixes: price-group schedules/time_range used the container's zone (happy
  hour bug); traffic report bucketed by UTC hour; reports' "date" meant the UTC
  calendar day, now the business date; reservations stored venue-local naive
  times (no-show check 2-3 h off) and listed by func.date; schedule week used
  UTC midnights; fiscal file names used container-local time
- seed.py/demo_seed.py create store_manager with role permissions (regression
  from step 1.0: v1's startup ALTER list used to rename/grant role 'manager')
- tzdata dependency; guard tests/guards/test_no_naive_time.py (AST scan);
  tests/test_timeutil.py covers the §7.3 DST cases and the API checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 17:12:35 +02:00
co-authored by Claude Opus 5.5
parent d3d328804e
commit ab1e61a10f
66 changed files with 1122 additions and 437 deletions
+16 -2
View File
@@ -42,6 +42,8 @@ os.environ.setdefault("MASTER_PASSWORD", "")
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import models.all # noqa: E402,F401 every model registered before any test touches the ORM
import itertools # noqa: E402
import bcrypt # noqa: E402
@@ -64,6 +66,18 @@ def pytest_collection_modifyitems(config, items):
item.add_marker(pytest.mark.db)
# ── venue time ──────────────────────────────────────────────────────────────
@pytest.fixture(autouse=True)
def _venue_time():
"""Every test runs in Europe/Athens with rollover 06:00 (D-11), without reading
settings from a database. A test can call timeutil.configure(...) to change it."""
from core import timeutil
timeutil.configure(tz="Europe/Athens", rollover_hour=6)
yield
timeutil.invalidate()
# ── schema + per-test transaction ───────────────────────────────────────────
def _build_schema(engine):
@@ -139,7 +153,7 @@ _seq = itertools.count(1)
@pytest.fixture
def make_user(db):
"""make_user(role="manager", perms={"perm_view_reports": False}, **fields) -> User.
"""make_user(role="store_manager", perms={"perm_view_reports": False}, **fields) -> User.
Password is TEST_PASSWORD and PIN is TEST_PIN. Permissions start from the
role's defaults (roles.DEFAULT_PERMISSIONS).
@@ -151,7 +165,7 @@ def make_user(db):
pw_hash = bcrypt.hashpw(TEST_PASSWORD.encode(), _FAST_SALT).decode()
pin_hash = bcrypt.hashpw(TEST_PIN.encode(), _FAST_SALT).decode()
def _make(role="manager", perms=None, **fields):
def _make(role="store_manager", perms=None, **fields):
n = next(_seq)
values = dict(
username=f"{role}{n}", full_name=f"Test {role} {n}", role=role,
+2 -2
View File
@@ -5,6 +5,6 @@ Changing a guard's rule is a design decision: record it in APPS_PLATFORM §2 fir
| File | Rule | Filled in |
|---|---|---|
| `test_migrations.py` | Models and Alembic revisions don't drift; the schema is built only by Alembic; v1 databases are refused | step 1.0 |
| `test_no_naive_datetimes.py` | No `datetime.utcnow`, argument-less `now()` / `.astimezone()`, or `Column(DateTime` in backend code | step 1.1 (placeholder until then) |
| `test_migrations.py` | Models and Alembic revisions don't drift; AUTOINCREMENT survives batch rebuilds; the schema is built only by Alembic; v1 databases are refused; revision data backfills | steps 1.0, 1.1 |
| `test_no_naive_time.py` | No `datetime.utcnow`/`datetime.now`, `date.today()`, argument-less `.astimezone()`, tz-less `fromtimestamp`, or `Column(DateTime` outside `core/timeutil.py` | step 1.1 |
| `test_route_access.py` | Every route declares `require(...)`, `require_device(...)` or `public()` | step 1.5 (placeholder until then) |
@@ -37,6 +37,22 @@ def test_upgrade_empty_db_then_no_drift(tmp_path):
assert version == current_head()
def test_sqlite_autoincrement_survives(tmp_path):
"""compare_metadata doesn't check AUTOINCREMENT, and batch rebuilds drop it unless
a revision restates it (table_kwargs={"sqlite_autoincrement": True})."""
from database import Base
import models.all # noqa: F401
eng = _fresh_engine(tmp_path)
upgrade_to_head(eng)
with eng.connect() as conn:
for table in Base.metadata.tables.values():
if table.dialect_kwargs.get("sqlite_autoincrement"):
sql = conn.execute(text("select sql from sqlite_master where name = :n"), {"n": table.name}).scalar()
assert "AUTOINCREMENT" in sql, f"{table.name} lost AUTOINCREMENT"
eng.dispose()
def test_upgrade_is_idempotent(tmp_path):
eng = _fresh_engine(tmp_path)
upgrade_to_head(eng)
@@ -72,3 +88,22 @@ def test_nothing_calls_create_all():
if re.search(r"\.create_all\(", f.read_text(encoding="utf-8", errors="ignore")):
offenders.append(rel)
assert offenders == [], f"use core.schema.upgrade_to_head() instead of create_all: {offenders}"
def test_0002_backfills_business_date(tmp_path):
"""A day opened 23:30 UTC on 12 Nov = 01:30 Athens on 13 Nov -> business date 12 Nov."""
from alembic import command
from core.schema import alembic_config
eng = _fresh_engine(tmp_path)
with eng.begin() as conn:
command.upgrade(alembic_config(conn), "0001_v2_baseline")
conn.execute(text("insert into business_days (status, opened_at, opened_by_id) "
"values ('closed', '2026-11-12 23:30:00.000000', 1)"))
conn.execute(text("insert into business_days (status, opened_at, opened_by_id) "
"values ('closed', '2026-11-13 08:00:00.000000', 1)"))
upgrade_to_head(eng)
with eng.connect() as conn:
dates = [r[0] for r in conn.execute(text("select business_date from business_days order by id"))]
eng.dispose()
assert dates == ["2026-11-12", "2026-11-13"]
@@ -1,8 +0,0 @@
"""Time guard (D-11, D-17). Filled in by plan step 1.1 (time model)."""
import pytest
pytestmark = pytest.mark.skip(reason="placeholder: implemented in platform-v2 step 1.1")
def test_no_naive_datetimes():
raise NotImplementedError
@@ -0,0 +1,87 @@
"""Time guard (D-11, D-17): backend code gets "now" and zones only through core/timeutil.py.
Scans every .py file of local_backend (AST, so comments and strings don't count) except
tests/, migrations/ and the files in ALLOWED. It fails on:
- datetime.utcnow() -> use utcnow()
- datetime.now(...) with or without args -> use utcnow() / venue_now()
- date.today() -> use venue_date() or business_date_of()
- <x>.astimezone() without an argument -> converts to the CONTAINER's zone; use to_venue()
- datetime.fromtimestamp(ts) without tz -> pass tz=UTC
- Column(DateTime ...) -> use Column(UTCDateTime ...)
"""
import ast
from pathlib import Path
BACKEND = Path(__file__).resolve().parents[2]
# file -> why it may break the rules
ALLOWED = {
"core/timeutil.py": "the one module that implements the rules",
"services/netinfo_helper.py": "separate host-network sidecar process; doesn't import the app (aware UTC only)",
}
def _name(node) -> str:
"""Dotted name of a Name/Attribute chain, e.g. 'datetime.datetime.now'."""
parts = []
while isinstance(node, ast.Attribute):
parts.append(node.attr)
node = node.value
if isinstance(node, ast.Name):
parts.append(node.id)
return ".".join(reversed(parts))
def violations_in(source: str) -> list[tuple[int, str]]:
out = []
for node in ast.walk(ast.parse(source)):
if not isinstance(node, ast.Call):
continue
name = _name(node.func)
nargs = len(node.args) + len(node.keywords)
if name.endswith("datetime.utcnow"):
out.append((node.lineno, "datetime.utcnow() -> utcnow()"))
elif name in ("datetime.now", "datetime.datetime.now"):
out.append((node.lineno, "datetime.now() -> utcnow() / venue_now()"))
elif name in ("date.today", "datetime.date.today"):
out.append((node.lineno, "date.today() -> venue_date() / business_date_of()"))
elif name.endswith(".astimezone") and nargs == 0:
out.append((node.lineno, ".astimezone() without a zone -> to_venue()"))
elif name in ("datetime.fromtimestamp", "datetime.datetime.fromtimestamp") and nargs < 2 \
and not any(k.arg == "tz" for k in node.keywords):
out.append((node.lineno, "fromtimestamp() without tz"))
elif name == "Column" and node.args:
first = node.args[0]
target = _name(first.func) if isinstance(first, ast.Call) else _name(first)
if target.split(".")[-1] == "DateTime":
out.append((node.lineno, "Column(DateTime) -> Column(UTCDateTime)"))
return out
def test_backend_has_no_naive_time():
problems = []
for f in sorted(BACKEND.rglob("*.py")):
rel = f.relative_to(BACKEND).as_posix()
if rel.startswith(("tests/", "migrations/")) or "__pycache__" in rel or rel in ALLOWED:
continue
for line, msg in violations_in(f.read_text(encoding="utf-8")):
problems.append(f"{rel}:{line}: {msg}")
assert problems == [], "naive time handling (see core/timeutil.py):\n" + "\n".join(problems)
def test_guard_catches_each_pattern():
src = """
from datetime import datetime, date
a = datetime.utcnow()
b = datetime.now()
c = datetime.now(timezone.utc)
d = date.today()
e = x.astimezone()
f = datetime.fromtimestamp(1)
g = Column(DateTime(timezone=True))
ok1 = x.astimezone(tz)
ok2 = datetime.fromtimestamp(1, tz=UTC)
ok3 = Column(UTCDateTime)
"""
lines = sorted(line for line, _ in violations_in(src))
assert lines == [3, 4, 5, 6, 7, 8, 9]
+3 -3
View File
@@ -3,7 +3,7 @@ from conftest import TEST_PASSWORD
def test_manager_logs_in_and_reads_me(client, make_user):
m = make_user(role="manager")
m = make_user(role="store_manager")
r = client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD})
assert r.status_code == 200, r.text
token = r.json()["access_token"]
@@ -13,7 +13,7 @@ def test_manager_logs_in_and_reads_me(client, make_user):
def test_wrong_password_is_rejected(client, make_user):
m = make_user(role="manager")
m = make_user(role="store_manager")
r = client.post("/api/auth/login", json={"username": m.username, "password": "nope"})
assert r.status_code == 401
@@ -25,7 +25,7 @@ def test_login_fixture_gives_working_headers(client, make_user, login):
def test_commits_are_rolled_back_between_tests_part1(db, make_user):
from models.user import User
make_user(role="manager", username="rollback_probe")
make_user(role="store_manager", username="rollback_probe")
assert db.query(User).filter_by(username="rollback_probe").count() == 1
+244
View File
@@ -0,0 +1,244 @@
"""The time model (D-11). The §7.3 cases from APPS_PLATFORM are marked "§7.3".
All tests run in Europe/Athens with rollover 06:00 (autouse fixture in conftest).
DST in Athens, 2026: spring forward Sun 29 Mar 03:00 -> 04:00; fall back Sun 25 Oct 04:00 -> 03:00.
"""
import json
from datetime import date, datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
from sqlalchemy.exc import StatementError
from core import timeutil
from core.timeutil import (
LocalClock, UTCDateTime, business_date_of, business_date_window, is_within,
iso_z, parse_api_datetime, to_venue, utcnow, venue_day_window, venue_local_to_utc,
)
UTC = timezone.utc
def local(y, mo, d, h, mi=0):
"""Venue wall-clock -> aware UTC."""
return venue_local_to_utc(datetime(y, mo, d, h, mi))
# ── basics ───────────────────────────────────────────────────────────────────
def test_utcnow_is_aware_utc():
assert utcnow().tzinfo is UTC
def test_to_venue_follows_dst():
assert to_venue(datetime(2026, 1, 15, 12, tzinfo=UTC)).hour == 14 # UTC+2
assert to_venue(datetime(2026, 7, 15, 12, tzinfo=UTC)).hour == 15 # UTC+3
def test_naive_input_to_helpers_raises():
with pytest.raises(ValueError):
to_venue(datetime(2026, 1, 1, 12))
def test_iso_z():
assert iso_z(datetime(2026, 7, 1, 9, 5, 3, 123456, tzinfo=UTC)) == "2026-07-01T09:05:03.123Z"
def test_venue_tz_change_applies_live():
assert to_venue(datetime(2026, 1, 15, 12, tzinfo=UTC)).hour == 14
timeutil.configure(tz="Europe/London")
assert to_venue(datetime(2026, 1, 15, 12, tzinfo=UTC)).hour == 12
# ── API input ────────────────────────────────────────────────────────────────
@pytest.mark.parametrize("raw,expected", [
("2026-07-01T20:00:00Z", datetime(2026, 7, 1, 20, tzinfo=UTC)),
("2026-07-01T20:00:00+03:00", datetime(2026, 7, 1, 17, tzinfo=UTC)),
("2026-07-01T20:00:00", datetime(2026, 7, 1, 17, tzinfo=UTC)), # naive = venue local (summer)
("2026-01-10T20:00", datetime(2026, 1, 10, 18, tzinfo=UTC)), # naive = venue local (winter)
("2026-07-01", datetime(2026, 6, 30, 21, tzinfo=UTC)), # date = venue midnight
])
def test_parse_api_datetime(raw, expected):
assert parse_api_datetime(raw) == expected
def test_venue_day_window_is_25h_on_fall_back_day():
start, end = venue_day_window(date(2026, 10, 25))
assert end - start == timedelta(hours=25)
start, end = venue_day_window(date(2026, 3, 29))
assert end - start == timedelta(hours=23)
# ── business date ────────────────────────────────────────────────────────────
def test_order_at_0130_belongs_to_previous_business_date(): # §7.3
assert business_date_of(local(2026, 7, 11, 1, 30)) == date(2026, 7, 10)
assert business_date_of(local(2026, 7, 11, 6, 0)) == date(2026, 7, 11)
assert business_date_of(local(2026, 7, 10, 23, 0)) == date(2026, 7, 10)
def test_rollover_hour_setting():
timeutil.configure(rollover_hour=0)
assert business_date_of(local(2026, 7, 11, 1, 30)) == date(2026, 7, 11)
def test_business_date_window():
start, end = business_date_window(date(2026, 7, 10))
assert start == local(2026, 7, 10, 6) and end == local(2026, 7, 11, 6)
assert start <= local(2026, 7, 11, 1, 30) < end
# ── durations across DST (§7.3) ──────────────────────────────────────────────
def test_shift_across_fall_back_lasts_10h(): # §7.3
start = local(2026, 10, 24, 22, 0)
end = local(2026, 10, 25, 7, 0)
assert end - start == timedelta(hours=10)
def test_shift_across_spring_forward_lasts_8h(): # §7.3
start = local(2026, 3, 28, 22, 0)
end = local(2026, 3, 29, 7, 0)
assert end - start == timedelta(hours=8)
# ── clock rules ──────────────────────────────────────────────────────────────
@pytest.mark.parametrize("when", [local(2026, 1, 14, 17, 30), local(2026, 7, 15, 17, 30)])
def test_happy_hour_active_at_1730_in_winter_and_summer(when): # §7.3
assert is_within(LocalClock("17:00", "19:00"), when)
assert not is_within(LocalClock("17:00", "19:00"), when + timedelta(hours=2)) # 19:30
def test_window_end_is_exclusive():
assert not is_within(LocalClock("17:00", "19:00"), local(2026, 7, 15, 19, 0))
def test_window_crossing_midnight_belongs_to_start_day():
fri_only = LocalClock("22:00", "02:00", frozenset({4})) # Friday night
assert is_within(fri_only, local(2026, 7, 17, 23, 0)) # Fri 23:00
assert is_within(fri_only, local(2026, 7, 18, 1, 0)) # Sat 01:00, still Friday's window
assert not is_within(fri_only, local(2026, 7, 19, 1, 0)) # Sun 01:00 (Saturday's window)
@pytest.mark.parametrize("when", [local(2026, 1, 14, 17, 30), local(2026, 7, 15, 17, 30)])
def test_price_group_schedule_uses_venue_time(when): # §7.3, was the container-zone bug
from services.pricing import _price_group_is_active
pg = SimpleNamespace(is_active=False, auto_enable_time="17:00", auto_disable_time="19:00",
auto_days=json.dumps(list(range(7))))
assert _price_group_is_active(pg, when)
assert not _price_group_is_active(pg, when - timedelta(hours=1))
# ── hourly report across the repeated hour (§7.3) ────────────────────────────
def test_hourly_buckets_keep_both_repeated_0300_hours(): # §7.3
from routers.reports import traffic_buckets
first_0330 = datetime(2026, 10, 25, 0, 30, tzinfo=UTC) # 03:30 EEST
second_0330 = datetime(2026, 10, 25, 1, 30, tzinfo=UTC) # 03:30 EET, one hour later
assert to_venue(first_0330).hour == to_venue(second_0330).hour == 3
by_hour, by_weekday = traffic_buckets([(first_0330, 10.0), (second_0330, 5.0)])
assert by_hour[3]["orders"] == 2 and by_hour[3]["revenue"] == 15.0
assert sum(b["orders"] for b in by_hour.values()) == 2
assert by_weekday[5]["orders"] == 2 # business date Sat 24 Oct (before rollover)
# ── storage (UTCDateTime) ────────────────────────────────────────────────────
def test_utcdatetime_type_rules():
t = UTCDateTime()
with pytest.raises(ValueError):
t.process_bind_param(datetime(2026, 1, 1, 12), None)
athens = to_venue(datetime(2026, 1, 1, 12, tzinfo=UTC))
assert t.process_bind_param(athens, None) == datetime(2026, 1, 1, 12)
assert t.process_result_value(datetime(2026, 1, 1, 12), None) == datetime(2026, 1, 1, 12, tzinfo=UTC)
def test_writing_naive_datetime_raises(db, make_user): # §7.3
from models.notes import SiteNote
u = make_user()
db.add(SiteNote(body="x", created_by_id=u.id, created_at=datetime(2026, 1, 1, 12)))
with pytest.raises(StatementError):
db.flush()
db.rollback()
def test_columns_read_back_aware_utc(db, make_user):
from models.notes import SiteNote
u = make_user()
n = SiteNote(body="x", created_by_id=u.id, created_at=to_venue(datetime(2026, 7, 1, 9, tzinfo=UTC)))
db.add(n)
db.commit()
db.expire_all()
got = db.get(SiteNote, n.id).created_at
assert got == datetime(2026, 7, 1, 9, tzinfo=UTC) and got.tzinfo is not None
# ── API level ────────────────────────────────────────────────────────────────
def _day_with_late_order(db, manager):
"""Business day opened 23:00 venue time on 10 Jul; one closed order at 01:30 on 11 Jul."""
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.product import Category, Product
opened = local(2026, 7, 10, 23, 0)
bd = BusinessDay(opened_by_id=manager.id, opened_at=opened, business_date=business_date_of(opened),
status="closed", closed_at=local(2026, 7, 11, 3, 0))
cat = Category(name="Food")
db.add_all([bd, cat])
db.flush()
prod = Product(name="Pita", base_price=4.0, category_id=cat.id)
db.add(prod)
db.flush()
order = Order(opened_by=manager.id, business_day_id=bd.id, status="closed",
opened_at=local(2026, 7, 11, 1, 30), closed_at=local(2026, 7, 11, 2, 0))
db.add(order)
db.flush()
db.add(OrderItem(order_id=order.id, product_id=prod.id, added_by=manager.id, quantity=1,
unit_price=4.0, status="paid", paid_at=local(2026, 7, 11, 1, 45)))
db.commit()
return bd
def test_reports_use_business_date_for_late_order(client, db, make_user, login): # "done when" check
m = make_user(role="store_manager")
bd = _day_with_late_order(db, m)
assert bd.business_date == date(2026, 7, 10)
r = client.get("/api/reports/revenue/trends", params={"granularity": "daily"}, headers=login(m))
assert r.status_code == 200, r.text
rows = r.json() if isinstance(r.json(), list) else r.json().get("data") or r.json().get("trends")
assert [row["date"] for row in rows] == ["2026-07-10"]
# The plain-date report filter means the business date as well
r = client.get("/api/reports/shift", params={"date": "2026-07-10"}, headers=login(m))
assert r.status_code == 200, r.text
body = r.json()
assert parse_api_datetime(body["from"]) == local(2026, 7, 10, 6)
assert sum(w["total"] for w in body["waiters"]) == 4.0
def test_api_outputs_utc_with_z(client, db, make_user, login):
m = make_user(role="store_manager")
r = client.get("/api/auth/me", headers=login(m))
created = r.json()["created_at"]
assert created.endswith("Z") or created.endswith("+00:00")
def test_reservation_naive_input_is_venue_local(client, db, make_user, login):
m = make_user(role="store_manager")
r = client.post("/api/reservations/", headers=login(m), json={
"guest_name": "Maria", "party_size": 2, "reserved_for": "2026-07-10T21:00:00"})
assert r.status_code in (200, 201), r.text
assert parse_api_datetime(r.json()["reserved_for"]) == local(2026, 7, 10, 21, 0)
# listing by venue date finds it
r = client.get("/api/reservations/", params={"date": "2026-07-10"}, headers=login(m))
assert [x["guest_name"] for x in r.json()] == ["Maria"]
def test_venue_timezone_setting_is_validated_and_applies_live(client, db, make_user, login):
m = make_user(role="superadmin")
bad = client.put("/api/settings/venue.timezone", headers=login(m), json={"value": "Mars/Olympus"})
assert bad.status_code == 422
ok = client.put("/api/settings/venue.timezone", headers=login(m), json={"value": "Europe/London"})
assert ok.status_code == 200
assert timeutil._cache == {} # invalidated: the next call re-reads the setting