| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168 |
- """Pure Prenot@Mi protocol parsing and precommit validation.
- This module is the functional core of the Italy plugin. It deliberately owns
- no browser, network, session, OTP, or form-submission behavior. Callers pass
- already-captured, sanitized data in and receive immutable value objects back.
- """
- from __future__ import annotations
- import json
- import html
- import re
- from dataclasses import dataclass, field
- from datetime import date, datetime, time
- from enum import Enum
- from typing import Any, Mapping, Sequence
- MAX_PROTOCOL_ITEMS = 512
- MAX_PROTOCOL_PAYLOAD_CHARS = 1_000_000
- MAX_LOOKAHEAD_MONTHS = 120
- _SITE_DATE_PATTERN = re.compile(r"^\d{2}/\d{2}/\d{4} 00:00:00$")
- PRENOTAMI_OTP_SENDER = "noreply-prenotami@esteri.it"
- _EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
- _OTP_CONTEXT_PATTERN = re.compile(
- r"(?<!\w)OTP\s+Code\s*:\s*([0-9]{6})(?!\w)",
- re.IGNORECASE,
- )
- class ItaProtocolError(ValueError):
- """Fail-closed protocol error with a stable, non-sensitive category."""
- def __init__(self, code: str, message: str, *, path: str = "") -> None:
- self.code = code
- self.path = path
- location = f" at {path}" if path else ""
- super().__init__(f"Italy protocol error [{code}]{location}: {message}")
- class ItaCapability(str, Enum):
- SERVICES_PROBE_ONLY = "services_probe_only"
- SINGLE_SCHENGEN_TOURISM = "single_schengen_tourism"
- class InventoryState(str, Enum):
- AVAILABLE = "available"
- UNAVAILABLE = "unavailable"
- @dataclass(frozen=True, slots=True)
- class CalendarScanConfig:
- lookahead_months: int
- @dataclass(frozen=True, slots=True)
- class FormControlConfig:
- control_id: str
- value: str
- labels: tuple[str, ...]
- @dataclass(frozen=True, slots=True)
- class OtpMailConfig:
- """Allowlisted cloud-mail query settings for one Italy route.
- The authorization mailbox is configured explicitly or derived per call
- from the current account, never cached on a shared route or included in
- diagnostic objects or log messages. The sender is
- fixed to Prenot@Mi's observed official address; a route may not widen the
- allowlist through configuration.
- """
- authorization_email: str | None = field(default=None, repr=False)
- subject_keywords: str = "OTP Code"
- body_keywords: str = "OTP Code:"
- expiry_seconds: int = 300
- authorization_source: str = "configured"
- def __post_init__(self) -> None:
- if self.authorization_source not in ("configured", "account"):
- raise ItaProtocolError(
- "otp_authorization_source_invalid",
- "authorization source must be configured or account",
- path="mail.authorization_source",
- )
- if self.authorization_source == "account":
- if self.authorization_email is not None:
- raise ItaProtocolError(
- "otp_authorization_source_conflict",
- "account source cannot also specify a fixed authorization mailbox",
- path="mail.authorization_email",
- )
- else:
- object.__setattr__(self, "authorization_email", self._require_mailbox(self.authorization_email))
- for field_name, expected in (("subject_keywords", "OTP Code"), ("body_keywords", "OTP Code:")):
- value = getattr(self, field_name)
- if not isinstance(value, str) or value.strip() != expected:
- raise ItaProtocolError(
- "otp_filter_invalid",
- "mail filters must match the observed Prenot@Mi OTP template",
- path=f"mail.{field_name}",
- )
- object.__setattr__(self, field_name, value.strip())
- if (
- not isinstance(self.expiry_seconds, int)
- or isinstance(self.expiry_seconds, bool)
- or not 1 <= self.expiry_seconds <= 300
- ):
- raise ItaProtocolError(
- "otp_expiry_invalid",
- "mail expiry must be an integer between 1 and 300 seconds",
- path="mail.expiry_seconds",
- )
- @staticmethod
- def _require_mailbox(value: Any) -> str:
- if not isinstance(value, str) or not _EMAIL_PATTERN.fullmatch(value.strip()):
- raise ItaProtocolError(
- "otp_authorization_email_invalid",
- "authorization mailbox must be a valid email address",
- path="mail.authorization_email",
- )
- return value.strip()
- def mailbox_for(self, account_email: str) -> str:
- """Bind per call; never mutate the route shared by pool instances.
- Account mode requires that each account's own inbox has an existing
- backend authorization. Configured mode preserves shared/forwarded
- inbox support; recipient filtering remains bound to the site account.
- """
- return self._require_mailbox(
- account_email if self.authorization_source == "account" else self.authorization_email
- )
- @dataclass(frozen=True, slots=True)
- class ItaRouteConfig:
- routing_key: str
- service_id: int
- capability: ItaCapability
- calendar_scan: CalendarScanConfig | None = None
- booking_type: FormControlConfig | None = None
- purpose: FormControlConfig | None = None
- mail: OtpMailConfig | None = None
- @dataclass(frozen=True, slots=True)
- class CalendarDay:
- day: date
- slots_free: int
- slots_remaining: int
- state: InventoryState
- def __post_init__(self) -> None:
- _require_date(self.day, "CalendarDay.day")
- slots_free = _require_int(self.slots_free, "CalendarDay.slots_free")
- slots_remaining = _require_int(
- self.slots_remaining,
- "CalendarDay.slots_remaining",
- )
- expected_state = _classify_inventory(
- slots_free,
- slots_remaining,
- path="CalendarDay",
- )
- if self.state is not expected_state:
- raise ItaProtocolError(
- "inventory_state_mismatch",
- "declared state differs from the slot counters",
- path="CalendarDay.state",
- )
- @property
- def is_available(self) -> bool:
- return self.state is InventoryState.AVAILABLE
- @dataclass(frozen=True, slots=True)
- class SlotCandidate:
- day: date
- start_time: time
- end_time: time
- slots_free: int
- slots_remaining: int
- state: InventoryState
- daily_calendar_id: str = field(repr=False)
- def __post_init__(self) -> None:
- _require_date(self.day, "SlotCandidate.day")
- start = _require_time(self.start_time, "SlotCandidate.start_time")
- end = _require_time(self.end_time, "SlotCandidate.end_time")
- if start >= end:
- raise ItaProtocolError(
- "time_range_invalid",
- "slot start time must be earlier than end time",
- path="SlotCandidate",
- )
- slots_free = _require_int(
- self.slots_free,
- "SlotCandidate.slots_free",
- )
- slots_remaining = _require_int(
- self.slots_remaining,
- "SlotCandidate.slots_remaining",
- )
- expected_state = _classify_inventory(
- slots_free,
- slots_remaining,
- path="SlotCandidate",
- )
- if self.state is not expected_state:
- raise ItaProtocolError(
- "inventory_state_mismatch",
- "declared state differs from the slot counters",
- path="SlotCandidate.state",
- )
- if (
- not isinstance(self.daily_calendar_id, str)
- or not self.daily_calendar_id.isdigit()
- or int(self.daily_calendar_id) <= 0
- ):
- raise ItaProtocolError(
- "daily_id_invalid",
- "runtime daily identifier must be a positive integer string",
- path="SlotCandidate.daily_calendar_id",
- )
- @property
- def is_available(self) -> bool:
- return self.state is InventoryState.AVAILABLE
- @property
- def time_label(self) -> str:
- return (
- f"{self.start_time.strftime('%H:%M')} - "
- f"{self.end_time.strftime('%H:%M')}"
- )
- @dataclass(frozen=True, slots=True)
- class DateSelectionState:
- planned_day: date
- matching_availability_count: int
- timeline_selected_days: tuple[date, ...]
- content_selected_days: tuple[date, ...]
- day_disabled: bool
- day_not_available: bool
- day_has_positive_state: bool
- def __post_init__(self) -> None:
- _require_date(self.planned_day, "DateSelectionState.planned_day")
- _require_nonnegative_int(
- self.matching_availability_count,
- "DateSelectionState.matching_availability_count",
- )
- _require_date_tuple(
- self.timeline_selected_days,
- "DateSelectionState.timeline_selected_days",
- )
- _require_date_tuple(
- self.content_selected_days,
- "DateSelectionState.content_selected_days",
- )
- for field_name in (
- "day_disabled",
- "day_not_available",
- "day_has_positive_state",
- ):
- _require_bool(
- getattr(self, field_name),
- f"DateSelectionState.{field_name}",
- )
- @dataclass(frozen=True, slots=True)
- class SlotSelectionState:
- active_slot_count: int
- active_is_candidate: bool
- active_has_unavailable_class: bool
- active_has_red_dot: bool
- active_hidden_input_count: int
- active_daily_id_matches_candidate: bool
- active_day_matches_candidate: bool
- active_time_matches_candidate: bool
- active_capacity_matches_candidate: bool
- def __post_init__(self) -> None:
- for field_name in (
- "active_slot_count",
- "active_hidden_input_count",
- ):
- _require_nonnegative_int(
- getattr(self, field_name),
- f"SlotSelectionState.{field_name}",
- )
- for field_name in (
- "active_is_candidate",
- "active_has_unavailable_class",
- "active_has_red_dot",
- "active_daily_id_matches_candidate",
- "active_day_matches_candidate",
- "active_time_matches_candidate",
- "active_capacity_matches_candidate",
- ):
- _require_bool(
- getattr(self, field_name),
- f"SlotSelectionState.{field_name}",
- )
- @dataclass(frozen=True, slots=True)
- class PrecommitApproval:
- """Immutable value returned by :func:`approve_precommit`."""
- calendar_day: CalendarDay
- candidate: SlotCandidate
- def resolve_route_config(
- apt_configs: Mapping[str, Any],
- routing_key: str,
- ) -> ItaRouteConfig:
- """Resolve one VFS/BLS-style ``apt_configs[routing_key]`` entry."""
- configs = _require_mapping(apt_configs, "apt_configs")
- key = _require_nonempty_string(routing_key, "routing_key")
- if key not in configs:
- raise ItaProtocolError(
- "route_missing",
- "no route is configured for the requested routing key",
- path="apt_configs",
- )
- raw_route = _require_mapping(configs[key], f"apt_configs.{key}")
- service_id = _require_positive_int(
- raw_route.get("service_id"),
- f"apt_configs.{key}.service_id",
- )
- raw_capability = _require_nonempty_string(
- raw_route.get("capability"),
- f"apt_configs.{key}.capability",
- )
- try:
- capability = ItaCapability(raw_capability)
- except ValueError as exc:
- raise ItaProtocolError(
- "capability_unsupported",
- "route capability is not supported",
- path=f"apt_configs.{key}.capability",
- ) from exc
- if capability is ItaCapability.SERVICES_PROBE_ONLY:
- return ItaRouteConfig(
- routing_key=key,
- service_id=service_id,
- capability=capability,
- )
- calendar_scan_raw = _require_mapping(
- raw_route.get("calendar_scan"),
- f"apt_configs.{key}.calendar_scan",
- )
- calendar_scan = CalendarScanConfig(
- lookahead_months=_require_lookahead_months(
- calendar_scan_raw.get("lookahead_months"),
- f"apt_configs.{key}.calendar_scan.lookahead_months",
- )
- )
- form_raw = _require_mapping(
- raw_route.get("form"),
- f"apt_configs.{key}.form",
- )
- booking_type = _parse_form_control(
- form_raw,
- prefix="booking_type",
- path=f"apt_configs.{key}.form",
- )
- purpose = _parse_form_control(
- form_raw,
- prefix="purpose",
- path=f"apt_configs.{key}.form",
- )
- mail = _parse_mail_config(
- raw_route.get("mail"),
- path=f"apt_configs.{key}.mail",
- )
- return ItaRouteConfig(
- routing_key=key,
- service_id=service_id,
- capability=capability,
- calendar_scan=calendar_scan,
- booking_type=booking_type,
- purpose=purpose,
- mail=mail,
- )
- def decode_double_json_array(
- payload: str,
- *,
- max_items: int = MAX_PROTOCOL_ITEMS,
- ) -> tuple[Mapping[str, Any], ...]:
- """Strictly decode the JSON-string-containing-a-JSON-array wire shape."""
- if not isinstance(payload, str) or not payload:
- raise ItaProtocolError(
- "payload_type",
- "payload must be a non-empty JSON string",
- )
- if len(payload) > MAX_PROTOCOL_PAYLOAD_CHARS:
- raise ItaProtocolError(
- "payload_too_large",
- "payload exceeds the local parsing limit",
- )
- if not _is_positive_int(max_items):
- raise ItaProtocolError(
- "max_items_invalid",
- "max_items must be a positive integer",
- )
- try:
- outer = json.loads(payload)
- except (TypeError, json.JSONDecodeError) as exc:
- raise ItaProtocolError(
- "outer_json_invalid",
- "outer JSON cannot be decoded",
- ) from exc
- if not isinstance(outer, str):
- raise ItaProtocolError(
- "payload_layer_count",
- "payload must contain exactly two JSON layers",
- )
- if len(outer) > MAX_PROTOCOL_PAYLOAD_CHARS:
- raise ItaProtocolError(
- "payload_too_large",
- "inner payload exceeds the local parsing limit",
- )
- try:
- items = json.loads(outer)
- except (TypeError, json.JSONDecodeError) as exc:
- raise ItaProtocolError(
- "inner_json_invalid",
- "inner JSON cannot be decoded",
- ) from exc
- if not isinstance(items, list):
- raise ItaProtocolError(
- "payload_layer_count",
- "inner JSON must be an array",
- )
- if len(items) > max_items:
- raise ItaProtocolError(
- "item_limit_exceeded",
- "response contains more items than the configured parsing limit",
- )
- result: list[Mapping[str, Any]] = []
- for index, item in enumerate(items):
- if not isinstance(item, Mapping):
- raise ItaProtocolError(
- "item_type",
- "every response item must be an object",
- path=f"items[{index}]",
- )
- result.append(item)
- return tuple(result)
- def parse_calendar_availability(
- payload: str,
- *,
- max_items: int = MAX_PROTOCOL_ITEMS,
- ) -> tuple[CalendarDay, ...]:
- """Parse and classify calendar-day capacity without guessing conflicts."""
- items = decode_double_json_array(payload, max_items=max_items)
- days: list[CalendarDay] = []
- seen_days: set[date] = set()
- for index, item in enumerate(items):
- path = f"availability[{index}]"
- parsed_day = _parse_site_date(
- _require_key(item, "DateLibere", path),
- f"{path}.DateLibere",
- )
- if parsed_day in seen_days:
- raise ItaProtocolError(
- "duplicate_calendar_day",
- "calendar response contains a duplicate date",
- path=path,
- )
- seen_days.add(parsed_day)
- slots_free = _require_int(
- _require_key(item, "SlotLiberi", path),
- f"{path}.SlotLiberi",
- )
- slots_remaining = _require_int(
- _require_key(item, "SlotRimanenti", path),
- f"{path}.SlotRimanenti",
- )
- state = _classify_inventory(
- slots_free,
- slots_remaining,
- path=path,
- )
- days.append(
- CalendarDay(
- day=parsed_day,
- slots_free=slots_free,
- slots_remaining=slots_remaining,
- state=state,
- )
- )
- return tuple(sorted(days, key=lambda item: item.day))
- def parse_time_slots(
- payload: str,
- *,
- max_items: int = MAX_PROTOCOL_ITEMS,
- ) -> tuple[SlotCandidate, ...]:
- """Parse TimeSlots items while keeping the runtime ID memory-only."""
- items = decode_double_json_array(payload, max_items=max_items)
- candidates: list[SlotCandidate] = []
- seen_ranges: set[tuple[date, time, time]] = set()
- seen_daily_ids: set[str] = set()
- for index, item in enumerate(items):
- path = f"time_slots[{index}]"
- parsed_day = _parse_site_date(
- _require_key(item, "Data", path),
- f"{path}.Data",
- )
- start_time = _parse_site_time(
- _require_key(item, "OrarioInizioFascia", path),
- f"{path}.OrarioInizioFascia",
- )
- end_time = _parse_site_time(
- _require_key(item, "OrarioFineFascia", path),
- f"{path}.OrarioFineFascia",
- )
- if start_time >= end_time:
- raise ItaProtocolError(
- "time_range_invalid",
- "slot start time must be earlier than end time",
- path=path,
- )
- slots_free = _require_int(
- _require_key(item, "SlotLiberi", path),
- f"{path}.SlotLiberi",
- )
- slots_remaining = _require_int(
- _require_key(item, "SlotRimanenti", path),
- f"{path}.SlotRimanenti",
- )
- state = _classify_inventory(
- slots_free,
- slots_remaining,
- path=path,
- )
- daily_id = str(
- _require_positive_int(
- _require_key(item, "IDCalendarioServizioGiornaliero", path),
- f"{path}.IDCalendarioServizioGiornaliero",
- )
- )
- time_range = (parsed_day, start_time, end_time)
- if time_range in seen_ranges:
- raise ItaProtocolError(
- "duplicate_time_range",
- "time-slot response contains a duplicate time range",
- path=path,
- )
- if daily_id in seen_daily_ids:
- raise ItaProtocolError(
- "duplicate_daily_id",
- "time-slot response reuses a runtime daily identifier",
- path=path,
- )
- seen_ranges.add(time_range)
- seen_daily_ids.add(daily_id)
- candidates.append(
- SlotCandidate(
- day=parsed_day,
- start_time=start_time,
- end_time=end_time,
- slots_free=slots_free,
- slots_remaining=slots_remaining,
- state=state,
- daily_calendar_id=daily_id,
- )
- )
- return tuple(
- sorted(
- candidates,
- key=lambda item: (item.day, item.start_time, item.end_time),
- )
- )
- def available_calendar_days(
- days: Sequence[CalendarDay],
- *,
- start_day: date | None = None,
- end_day: date | None = None,
- ) -> tuple[CalendarDay, ...]:
- """Return positive days in an inclusive date range, sorted ascending."""
- start, end = _validate_date_range(start_day, end_day)
- seen: set[date] = set()
- selected: list[CalendarDay] = []
- for index, item in enumerate(days):
- if not isinstance(item, CalendarDay):
- raise ItaProtocolError(
- "calendar_day_type",
- "days must contain CalendarDay values",
- path=f"days[{index}]",
- )
- if item.day in seen:
- raise ItaProtocolError(
- "duplicate_calendar_day",
- "days contain a duplicate date",
- path=f"days[{index}]",
- )
- seen.add(item.day)
- if item.is_available and _date_in_range(item.day, start, end):
- selected.append(item)
- return tuple(sorted(selected, key=lambda item: item.day))
- def available_slot_candidates(
- candidates: Sequence[SlotCandidate],
- *,
- start_day: date | None = None,
- end_day: date | None = None,
- ) -> tuple[SlotCandidate, ...]:
- """Filter and deterministically order positive Book-side candidates."""
- start, end = _validate_date_range(start_day, end_day)
- seen_ranges: set[tuple[date, time, time]] = set()
- selected: list[SlotCandidate] = []
- for index, item in enumerate(candidates):
- if not isinstance(item, SlotCandidate):
- raise ItaProtocolError(
- "slot_candidate_type",
- "candidates must contain SlotCandidate values",
- path=f"candidates[{index}]",
- )
- identity = (item.day, item.start_time, item.end_time)
- if identity in seen_ranges:
- raise ItaProtocolError(
- "duplicate_time_range",
- "candidates contain a duplicate time range",
- path=f"candidates[{index}]",
- )
- seen_ranges.add(identity)
- if item.is_available and _date_in_range(item.day, start, end):
- selected.append(item)
- return tuple(
- sorted(
- selected,
- key=lambda item: (
- item.day,
- -item.slots_free,
- item.start_time,
- item.end_time,
- ),
- )
- )
- def parse_otp_body(
- body: str,
- *,
- max_chars: int = MAX_PROTOCOL_PAYLOAD_CHARS,
- ) -> str:
- """Extract exactly one Prenot@Mi OTP from a cloud-mail body.
- The cloud endpoint returns a body-only string and may include both the
- plain-text and HTML MIME alternatives. HTML tags are replaced with
- spaces, then only the observed ``OTP Code:`` marker followed by six ASCII
- digits is accepted. Repeated identical matches (plain + HTML) are fine;
- different candidates fail closed. No caller should log ``body`` or the
- returned code.
- """
- if not isinstance(body, str) or not body.strip():
- raise ItaProtocolError(
- "otp_body_invalid",
- "OTP mail body must be a non-empty string",
- path="mail.body",
- )
- if not isinstance(max_chars, int) or isinstance(max_chars, bool) or max_chars <= 0:
- raise ItaProtocolError(
- "otp_body_limit_invalid",
- "OTP body limit must be a positive integer",
- path="mail.max_chars",
- )
- if len(body) > max_chars:
- raise ItaProtocolError(
- "otp_body_too_large",
- "OTP mail body exceeds the local parsing limit",
- path="mail.body",
- )
- # The existing cloud service can concatenate text/plain and text/html.
- # Projecting HTML to text avoids depending on a browser or executing any
- # markup while preserving the marker when tags surround the code.
- projected = html.unescape(re.sub(r"<[^>]{0,4096}>", " ", body))
- projected = re.sub(r"\s+", " ", projected).strip()
- matches = _OTP_CONTEXT_PATTERN.findall(projected)
- unique = tuple(dict.fromkeys(matches))
- if not unique:
- raise ItaProtocolError(
- "otp_not_found",
- "mail body did not contain the expected OTP marker",
- path="mail.body",
- )
- if len(unique) != 1:
- raise ItaProtocolError(
- "otp_ambiguous",
- "mail body contained multiple different OTP candidates",
- path="mail.body",
- )
- return unique[0]
- def month_starts(anchor_day: date, lookahead_months: int) -> tuple[date, ...]:
- """Return deterministic month starts for the configured scan window."""
- anchor = _require_date(anchor_day, "anchor_day")
- months = _require_lookahead_months(lookahead_months, "lookahead_months")
- result: list[date] = []
- year = anchor.year
- month = anchor.month
- for _ in range(months):
- result.append(date(year, month, 1))
- month += 1
- if month == 13:
- year += 1
- month = 1
- return tuple(result)
- def approve_precommit(
- calendar_day: CalendarDay,
- candidate: SlotCandidate,
- date_state: DateSelectionState,
- slot_state: SlotSelectionState,
- ) -> PrecommitApproval:
- """Approve final-button readiness only when every observed invariant holds."""
- if not isinstance(calendar_day, CalendarDay):
- raise ItaProtocolError(
- "precommit_type",
- "calendar_day must be a CalendarDay",
- )
- if not isinstance(candidate, SlotCandidate):
- raise ItaProtocolError(
- "precommit_type",
- "candidate must be a SlotCandidate",
- )
- if not isinstance(date_state, DateSelectionState):
- raise ItaProtocolError(
- "precommit_type",
- "date_state must be a DateSelectionState",
- )
- if not isinstance(slot_state, SlotSelectionState):
- raise ItaProtocolError(
- "precommit_type",
- "slot_state must be a SlotSelectionState",
- )
- checks = (
- (calendar_day.is_available, "calendar day is not positively available"),
- (candidate.is_available, "slot candidate is not positively available"),
- (calendar_day.day == candidate.day, "calendar and slot dates differ"),
- (
- date_state.planned_day == candidate.day,
- "selected date differs from the planned date",
- ),
- (
- date_state.matching_availability_count == 1,
- "planned date must map to exactly one availability item",
- ),
- (
- date_state.timeline_selected_days == (candidate.day,),
- "timeline must have exactly one matching selected date",
- ),
- (
- date_state.content_selected_days == (candidate.day,),
- "content must have exactly one matching selected date",
- ),
- (not date_state.day_disabled, "selected date is disabled"),
- (
- not date_state.day_not_available,
- "selected date has a negative availability marker",
- ),
- (
- date_state.day_has_positive_state,
- "selected date lacks the verified positive state",
- ),
- (
- slot_state.active_slot_count == 1,
- "there must be exactly one active slot",
- ),
- (
- slot_state.active_is_candidate,
- "active slot is not the approved candidate",
- ),
- (
- not slot_state.active_has_unavailable_class,
- "active slot has an unavailable class",
- ),
- (
- not slot_state.active_has_red_dot,
- "active slot has a negative red marker",
- ),
- (
- slot_state.active_hidden_input_count == 1,
- "active slot must contain exactly one runtime identifier input",
- ),
- (
- slot_state.active_daily_id_matches_candidate,
- "active slot runtime identifier differs from the candidate",
- ),
- (
- slot_state.active_day_matches_candidate,
- "active slot date differs from the candidate",
- ),
- (
- slot_state.active_time_matches_candidate,
- "active slot time differs from the candidate",
- ),
- (
- slot_state.active_capacity_matches_candidate,
- "active slot capacity differs from the candidate",
- ),
- )
- for passed, message in checks:
- if not passed:
- raise ItaProtocolError("precommit_rejected", message)
- return PrecommitApproval(calendar_day=calendar_day, candidate=candidate)
- def _parse_form_control(
- form: Mapping[str, Any],
- *,
- prefix: str,
- path: str,
- ) -> FormControlConfig:
- return FormControlConfig(
- control_id=_require_nonempty_string(
- form.get(f"{prefix}_control_id"),
- f"{path}.{prefix}_control_id",
- ),
- value=_require_nonempty_string(
- form.get(f"{prefix}_value"),
- f"{path}.{prefix}_value",
- ),
- labels=_require_string_tuple(
- form.get(f"{prefix}_labels"),
- f"{path}.{prefix}_labels",
- ),
- )
- def _parse_mail_config(
- raw_mail: Any,
- *,
- path: str,
- ) -> OtpMailConfig | None:
- if raw_mail is None:
- return None
- mail = _require_mapping(raw_mail, path)
- sender = mail.get("sender", PRENOTAMI_OTP_SENDER)
- if not isinstance(sender, str) or sender.strip().casefold() != PRENOTAMI_OTP_SENDER:
- raise ItaProtocolError(
- "otp_sender_not_allowlisted",
- "mail sender must match Prenot@Mi's official OTP address",
- path=f"{path}.sender",
- )
- return OtpMailConfig(
- authorization_email=mail.get("authorization_email"),
- subject_keywords=mail.get("subject_keywords", "OTP Code"),
- body_keywords=mail.get("body_keywords", "OTP Code:"),
- expiry_seconds=mail.get("expiry_seconds", 300),
- authorization_source=mail.get("authorization_source", "configured"),
- )
- def _classify_inventory(
- slots_free: int,
- slots_remaining: int,
- *,
- path: str,
- ) -> InventoryState:
- if slots_free > 0 and slots_remaining >= 0:
- return InventoryState.AVAILABLE
- if slots_free == 0 and slots_remaining < 0:
- return InventoryState.UNAVAILABLE
- raise ItaProtocolError(
- "inventory_conflict",
- "slot counters do not match an observed allowlisted state",
- path=path,
- )
- def _parse_site_date(value: Any, path: str) -> date:
- if not isinstance(value, str) or not _SITE_DATE_PATTERN.fullmatch(value):
- raise ItaProtocolError(
- "date_format",
- "date must match DD/MM/YYYY 00:00:00",
- path=path,
- )
- try:
- return datetime.strptime(value, "%d/%m/%Y %H:%M:%S").date()
- except ValueError as exc:
- raise ItaProtocolError(
- "date_invalid",
- "date is not a real calendar date",
- path=path,
- ) from exc
- def _parse_site_time(value: Any, path: str) -> time:
- mapping = _require_mapping(value, path)
- hours = _require_int(_require_key(mapping, "Hours", path), f"{path}.Hours")
- minutes = _require_int(
- _require_key(mapping, "Minutes", path),
- f"{path}.Minutes",
- )
- seconds = _require_int(mapping.get("Seconds", 0), f"{path}.Seconds")
- milliseconds = _require_int(
- mapping.get("Milliseconds", 0),
- f"{path}.Milliseconds",
- )
- if seconds != 0 or milliseconds != 0:
- raise ItaProtocolError(
- "time_precision",
- "sub-minute slot precision is not supported by the observed protocol",
- path=path,
- )
- try:
- return time(hour=hours, minute=minutes)
- except ValueError as exc:
- raise ItaProtocolError(
- "time_invalid",
- "slot time is outside the 24-hour clock",
- path=path,
- ) from exc
- def _validate_date_range(
- start_day: date | None,
- end_day: date | None,
- ) -> tuple[date | None, date | None]:
- start = _require_date(start_day, "start_day") if start_day is not None else None
- end = _require_date(end_day, "end_day") if end_day is not None else None
- if start is not None and end is not None and start > end:
- raise ItaProtocolError(
- "date_range_invalid",
- "start_day must not be later than end_day",
- )
- return start, end
- def _date_in_range(
- value: date,
- start_day: date | None,
- end_day: date | None,
- ) -> bool:
- return (
- (start_day is None or value >= start_day)
- and (end_day is None or value <= end_day)
- )
- def _require_mapping(value: Any, path: str) -> Mapping[str, Any]:
- if not isinstance(value, Mapping):
- raise ItaProtocolError(
- "mapping_required",
- "value must be an object",
- path=path,
- )
- return value
- def _require_key(mapping: Mapping[str, Any], key: str, path: str) -> Any:
- if key not in mapping:
- raise ItaProtocolError(
- "field_missing",
- "required field is missing",
- path=f"{path}.{key}",
- )
- return mapping[key]
- def _require_nonempty_string(value: Any, path: str) -> str:
- if not isinstance(value, str) or not value.strip():
- raise ItaProtocolError(
- "string_required",
- "value must be a non-empty string",
- path=path,
- )
- return value.strip()
- def _require_string_tuple(value: Any, path: str) -> tuple[str, ...]:
- if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
- raise ItaProtocolError(
- "labels_required",
- "labels must be a non-empty array of strings",
- path=path,
- )
- labels = tuple(
- _require_nonempty_string(item, f"{path}[{index}]")
- for index, item in enumerate(value)
- )
- if not labels:
- raise ItaProtocolError(
- "labels_required",
- "labels must be a non-empty array of strings",
- path=path,
- )
- if len(set(labels)) != len(labels):
- raise ItaProtocolError(
- "labels_duplicate",
- "labels must not contain duplicates",
- path=path,
- )
- return labels
- def _is_positive_int(value: Any) -> bool:
- return isinstance(value, int) and not isinstance(value, bool) and value > 0
- def _require_positive_int(value: Any, path: str) -> int:
- if not _is_positive_int(value):
- raise ItaProtocolError(
- "positive_integer_required",
- "value must be a positive integer",
- path=path,
- )
- return value
- def _require_int(value: Any, path: str) -> int:
- if not isinstance(value, int) or isinstance(value, bool):
- raise ItaProtocolError(
- "integer_required",
- "value must be an integer",
- path=path,
- )
- return value
- def _require_nonnegative_int(value: Any, path: str) -> int:
- number = _require_int(value, path)
- if number < 0:
- raise ItaProtocolError(
- "nonnegative_integer_required",
- "value must be a non-negative integer",
- path=path,
- )
- return number
- def _require_bool(value: Any, path: str) -> bool:
- if not isinstance(value, bool):
- raise ItaProtocolError(
- "boolean_required",
- "value must be a boolean",
- path=path,
- )
- return value
- def _require_lookahead_months(value: Any, path: str) -> int:
- months = _require_positive_int(value, path)
- if months > MAX_LOOKAHEAD_MONTHS:
- raise ItaProtocolError(
- "lookahead_too_large",
- "lookahead exceeds the local scan safety limit",
- path=path,
- )
- return months
- def _require_date(value: Any, path: str) -> date:
- if not isinstance(value, date) or isinstance(value, datetime):
- raise ItaProtocolError(
- "date_required",
- "value must be a date",
- path=path,
- )
- return value
- def _require_date_tuple(value: Any, path: str) -> tuple[date, ...]:
- if not isinstance(value, tuple):
- raise ItaProtocolError(
- "date_tuple_required",
- "value must be a tuple of dates",
- path=path,
- )
- for index, item in enumerate(value):
- _require_date(item, f"{path}[{index}]")
- return value
- def _require_time(value: Any, path: str) -> time:
- if not isinstance(value, time):
- raise ItaProtocolError(
- "time_required",
- "value must be a time",
- path=path,
- )
- if value.second != 0 or value.microsecond != 0:
- raise ItaProtocolError(
- "time_precision",
- "slot time must use minute precision",
- path=path,
- )
- return value
- __all__ = [
- "CalendarDay",
- "CalendarScanConfig",
- "DateSelectionState",
- "FormControlConfig",
- "InventoryState",
- "ItaCapability",
- "ItaProtocolError",
- "ItaRouteConfig",
- "MAX_LOOKAHEAD_MONTHS",
- "MAX_PROTOCOL_ITEMS",
- "OtpMailConfig",
- "PrecommitApproval",
- "PRENOTAMI_OTP_SENDER",
- "SlotCandidate",
- "SlotSelectionState",
- "approve_precommit",
- "available_calendar_days",
- "available_slot_candidates",
- "decode_double_json_array",
- "month_starts",
- "parse_calendar_availability",
- "parse_otp_body",
- "parse_time_slots",
- "resolve_route_config",
- ]
|