"""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