| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761 |
- """Book-side Calendar response binding and native slot selection.
- The caller owns login, route continuity, date preferences and fresh packet
- capture in the applicant's browser. This adapter neither fetches inventory nor
- accepts a Query snapshot. A returned approval is a pre-final checkpoint, never
- permission to submit or evidence of a completed booking.
- """
- from __future__ import annotations
- import json
- import time
- from dataclasses import dataclass, field
- from datetime import date, datetime
- from typing import Callable, Mapping
- from plugins.ita_calendar_query import (
- CALENDAR_PATH,
- AVAILABILITY_PATH,
- DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
- CalendarGateError,
- CalendarProbeResult,
- click_next_month,
- guard_calendar,
- listen_once,
- month_text,
- next_month_value,
- parse_availability_packet,
- refresh_calendar,
- require_plain_nonnegative_int,
- same_origin_path,
- )
- from plugins.ita_protocol import (
- CalendarDay,
- DateSelectionState,
- ItaProtocolError,
- PrecommitApproval,
- SlotCandidate,
- SlotSelectionState,
- approve_precommit,
- available_calendar_days,
- available_slot_candidates,
- month_starts,
- parse_time_slots,
- )
- TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
- RUNTIME_SERVICE_SCRIPT = r"""
- /* coordinate:ita-book-runtime-service */
- const controls = Array.from(document.querySelectorAll('#idServizio'));
- return {
- path: window.location.pathname,
- count: controls.length,
- value: controls.length === 1 ? controls[0].value : null,
- };
- """
- SLOT_SELECTION_SCRIPT = r"""
- /* coordinate:ita-book-slot-selection */
- const [serviceId, day, dailyId, timeLabel, capacity, shouldClick] = arguments;
- const normalize = (text) => String(text || '').replace(/\s+/g, ' ').trim();
- const service = Array.from(document.querySelectorAll('#idServizio'));
- const runtimeMatches = window.location.origin === 'https://prenotami.esteri.it' &&
- window.location.pathname === '/BookingCalendar' &&
- service.length === 1 && service[0].value === serviceId;
- const finalButtons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
- const finalGuarded = finalButtons.length === 1 && finalButtons[0].disabled &&
- finalButtons[0].dataset.coordinateFinalGuard === 'enabled';
- const timeline = Array.from(document.querySelectorAll('.events a.selected'));
- const content = Array.from(document.querySelectorAll('.events-content li.selected'));
- const links = Array.from(document.querySelectorAll('.events a[data-date]'))
- .filter((element) => element.dataset.date === day);
- const link = links.length === 1 ? links[0] : null;
- const datesMatch = timeline.length === 1 && content.length === 1 &&
- timeline[0].dataset.date === day && content[0].dataset.date === day;
- const firstSelectedMatches = datesMatch && document.querySelector('.selected') === timeline[0];
- const disabled = (element) => !element || element.hasAttribute('disabled') ||
- element.getAttribute('aria-disabled') === 'true' ||
- element.classList.contains('disabled') ||
- element.classList.contains('input-async-disabilitato');
- const dayNegative = !link || link.classList.contains('notAvailableDay');
- const dayPositive = Boolean(link && link.classList.contains('input-async-abilitato'));
- const inputs = (slot) => slot ? Array.from(slot.querySelectorAll('input')) : [];
- const idMatches = (slot) => {
- const fields = inputs(slot);
- return fields.length === 1 && fields[0].type === 'hidden' &&
- fields[0].id === 'idHiddenFasciaServizio' && fields[0].value === dailyId;
- };
- const timeMatches = (slot) => {
- const spans = slot ? slot.querySelectorAll('span') : [];
- return spans.length === 2 && normalize(spans[0].textContent) === timeLabel;
- };
- const capacityMatches = (slot) => {
- const spans = slot ? slot.querySelectorAll('span') : [];
- return spans.length === 2 && normalize(spans[1].textContent) === `(${capacity})`;
- };
- const negative = (slot) => !slot || slot.classList.contains('notAvailableFascia');
- const redDot = (slot) => Boolean(slot && slot.querySelector('.dotRed'));
- const actionable = (element) => {
- if (!element || !element.isConnected || disabled(element)) return false;
- const style = window.getComputedStyle(element);
- if (style.display === 'none' || style.visibility === 'hidden' ||
- style.pointerEvents === 'none' || Number.parseFloat(style.opacity || '1') <= 0) return false;
- const rect = element.getBoundingClientRect();
- const left = Math.max(0, rect.left), right = Math.min(window.innerWidth, rect.right);
- const top = Math.max(0, rect.top), bottom = Math.min(window.innerHeight, rect.bottom);
- if (right <= left || bottom <= top) return false;
- const hit = document.elementFromPoint((left + right) / 2, (top + bottom) / 2);
- return Boolean(hit && (hit === element || element.contains(hit)));
- };
- const slots = content.length === 1 ? Array.from(content[0].querySelectorAll('.fascia')) : [];
- const matches = slots.filter(idMatches);
- const candidate = matches.length === 1 ? matches[0] : null;
- const candidateReady = Boolean(candidate && !negative(candidate) && !redDot(candidate) &&
- timeMatches(candidate) && capacityMatches(candidate) && actionable(candidate));
- let active = Array.from(document.querySelectorAll('.fascia.act'));
- const alreadyActive = active.length === 1 && active[0] === candidate;
- let clicked = false;
- if (shouldClick === true && runtimeMatches && finalGuarded && datesMatch &&
- firstSelectedMatches && links.length === 1 && !disabled(link) && !dayNegative &&
- dayPositive && candidateReady && !alreadyActive) {
- candidate.click();
- clicked = true;
- }
- active = Array.from(document.querySelectorAll('.fascia.act'));
- const selected = active.length === 1 ? active[0] : null;
- return {
- runtimeMatches, finalGuarded, firstSelectedMatches,
- timelineDays: timeline.map((element) => element.dataset.date || ''),
- contentDays: content.map((element) => element.dataset.date || ''),
- matchingDateCount: links.length,
- dayDisabled: disabled(link), dayNegative, dayPositive,
- candidateCount: matches.length, candidateReady, clicked,
- activeCount: active.length,
- activeIsCandidate: Boolean(selected && selected === candidate),
- activeUnavailable: negative(selected), activeRedDot: redDot(selected),
- activeInputCount: inputs(selected).length,
- activeIdMatches: idMatches(selected),
- activeDayMatches: Boolean(selected && datesMatch && content[0].contains(selected)),
- activeTimeMatches: timeMatches(selected),
- activeCapacityMatches: capacityMatches(selected),
- };
- """
- class CalendarBookError(CalendarGateError):
- """A safe stage error; never includes response bodies or runtime IDs."""
- def __init__(self, message: str, *, http_status: int | None = None):
- super().__init__(message)
- self.http_status = http_status
- class CalendarServiceNotReadyError(CalendarBookError):
- """The service control stayed empty during a known initialization boundary."""
- _BOOL_FIELDS = {
- "runtimeMatches", "finalGuarded", "firstSelectedMatches", "dayDisabled",
- "dayNegative", "dayPositive", "candidateReady", "clicked",
- "activeIsCandidate", "activeUnavailable", "activeRedDot", "activeIdMatches",
- "activeDayMatches", "activeTimeMatches", "activeCapacityMatches",
- }
- _COUNT_FIELDS = {"matchingDateCount", "candidateCount", "activeCount", "activeInputCount"}
- _DATE_FIELDS = {"timelineDays", "contentDays"}
- def _runtime_id(value: object) -> str:
- if type(value) is int and value > 0:
- return str(value)
- if isinstance(value, str) and value and value == value.strip() and len(value) <= 128:
- return value
- raise CalendarBookError("Book runtime service identifier was invalid")
- def _read_calendar_service_value(page: object) -> str:
- path, _ = same_origin_path(page.url)
- if path != CALENDAR_PATH:
- raise CalendarBookError("Book selection requires the current Calendar page")
- raw = page.run_js(RUNTIME_SERVICE_SCRIPT)
- if not isinstance(raw, dict) or set(raw) != {"path", "count", "value"}:
- raise CalendarBookError("Book Calendar runtime context changed")
- if raw["path"] != CALENDAR_PATH or type(raw["count"]) is not int or raw["count"] != 1:
- raise CalendarBookError("Book Calendar requires one runtime service control")
- if not isinstance(raw["value"], str):
- raise CalendarBookError("Book Calendar runtime service control has no value")
- return raw["value"]
- def read_calendar_service(page: object) -> str:
- """Strict read for stable phases; empty values are never a valid identity."""
- return _runtime_id(_read_calendar_service_value(page))
- def wait_for_calendar_service(
- page: object, *, session_is_current: Callable[[], bool],
- expected_service: str | None = None, timeout: float = 5,
- ) -> str:
- """Await the site's field assignment without requesting or retrying anything.
- Call only after AVANTI or native Calendar loading. Stable-phase checks stay
- strict: only an exactly empty string is pending, not malformed identities,
- missing/duplicate controls, another service, or a changed applicant/tab.
- The deadline bounds polling; browser transport failures propagate normally.
- """
- if type(timeout) not in (int, float) or not 0 <= timeout < float("inf"):
- raise CalendarBookError("Book Calendar readiness timeout must be finite and nonnegative")
- if not callable(session_is_current):
- raise CalendarBookError("Book Calendar readiness requires a Session check")
- if expected_service is not None:
- expected_service = _runtime_id(expected_service)
- tab_id = getattr(page, "tab_id", None)
- if not isinstance(tab_id, str) or not tab_id:
- raise CalendarBookError("Book Calendar tab identity was unavailable")
- deadline = time.monotonic() + timeout
- def require_session() -> None:
- if session_is_current() is not True or getattr(page, "tab_id", None) != tab_id:
- raise CalendarBookError("Book applicant, route or browser Session changed")
- if same_origin_path(page.url)[0] != CALENDAR_PATH:
- raise CalendarBookError("Book readiness left the current Calendar page")
- while True:
- require_session()
- guard_calendar(page)
- value = _read_calendar_service_value(page)
- require_session()
- if value != "":
- service = _runtime_id(value)
- if expected_service is not None and service != expected_service:
- raise CalendarBookError("Book Calendar runtime service changed")
- return service
- remaining = deadline - time.monotonic()
- if remaining <= 0:
- raise CalendarServiceNotReadyError("Book Calendar service did not initialize before timeout")
- time.sleep(min(0.1, remaining))
- def _request_day(value: object) -> date:
- if isinstance(value, str):
- for date_format in ("%Y-%m-%d", "%d/%m/%Y"):
- try:
- return datetime.strptime(value, date_format).date()
- except ValueError:
- pass
- raise CalendarBookError("Book TimeSlots request date format changed")
- def parse_book_time_slots(
- packet: object, *, target_day: date, runtime_service_id: str,
- ) -> tuple[SlotCandidate, ...]:
- """Bind TimeSlots metadata to the selected day and current DOM service."""
- try:
- path, _ = same_origin_path(packet.url)
- if str(packet.method).upper() != "POST" or path != TIME_SLOTS_PATH:
- raise CalendarBookError("Book TimeSlots request method or path changed")
- if type(packet.response.status) is not int or packet.response.status != 200:
- raise CalendarBookError(
- "Book TimeSlots response status was not 200",
- http_status=packet.response.status if type(packet.response.status) is int else None,
- )
- body = packet.request.postData
- if isinstance(body, str):
- body = json.loads(body)
- if not isinstance(body, dict) or set(body) != {"selectedDay", "idService"}:
- raise CalendarBookError("Book TimeSlots request fields changed")
- if _runtime_id(body["idService"]) != runtime_service_id:
- raise CalendarBookError("Book TimeSlots request does not match the current service")
- if _request_day(body["selectedDay"]) != target_day:
- raise CalendarBookError("Book TimeSlots request does not match the target day")
- candidates = parse_time_slots(packet.response.raw_body)
- if any(item.day != target_day for item in candidates):
- raise CalendarBookError("Book TimeSlots response contains another day")
- return candidates
- except CalendarBookError:
- raise
- except ItaProtocolError as exc:
- raise CalendarBookError(f"Book TimeSlots protocol rejected ({exc.code})") from None
- except Exception:
- raise CalendarBookError("Book TimeSlots packet could not be validated") from None
- def _snapshot(page: object, service: str, target: date, candidate: SlotCandidate, *, click: bool) -> dict:
- raw = page.run_js(
- SLOT_SELECTION_SCRIPT, service, target.isoformat(), candidate.daily_calendar_id,
- candidate.time_label, candidate.slots_free, click,
- )
- if not isinstance(raw, dict) or set(raw) != _BOOL_FIELDS | _COUNT_FIELDS | _DATE_FIELDS:
- raise CalendarBookError("Book slot snapshot fields changed")
- if any(type(raw[key]) is not bool for key in _BOOL_FIELDS):
- raise CalendarBookError("Book slot snapshot boolean types changed")
- for key in _COUNT_FIELDS:
- require_plain_nonnegative_int(raw[key], key)
- for key in _DATE_FIELDS:
- if not isinstance(raw[key], list) or any(not isinstance(item, str) for item in raw[key]):
- raise CalendarBookError("Book selected-date snapshot types changed")
- return raw
- def _require_ready(raw: dict, target_day: date) -> None:
- positive = ("runtimeMatches", "finalGuarded", "firstSelectedMatches", "dayPositive", "candidateReady")
- if any(raw[key] is not True for key in positive):
- raise CalendarBookError("Book candidate is not safely selectable")
- if raw["dayDisabled"] or raw["dayNegative"]:
- raise CalendarBookError("Book selected day is marked unavailable")
- if raw["matchingDateCount"] != 1 or raw["candidateCount"] != 1:
- raise CalendarBookError("Book date or slot is not unique")
- expected = [target_day.isoformat()]
- if raw["timelineDays"] != expected or raw["contentDays"] != expected:
- raise CalendarBookError("Book timeline and content dates do not match the target")
- def _approve_selection_snapshot(
- calendar_day: CalendarDay, candidate: SlotCandidate, raw: dict,
- ) -> PrecommitApproval:
- _require_ready(raw, candidate.day)
- if raw["clicked"]:
- raise CalendarBookError("Book readback unexpectedly clicked")
- return approve_precommit(
- calendar_day, candidate,
- DateSelectionState(
- planned_day=candidate.day, matching_availability_count=1,
- timeline_selected_days=tuple(date.fromisoformat(item) for item in raw["timelineDays"]),
- content_selected_days=tuple(date.fromisoformat(item) for item in raw["contentDays"]),
- day_disabled=raw["dayDisabled"], day_not_available=raw["dayNegative"],
- day_has_positive_state=raw["dayPositive"],
- ),
- SlotSelectionState(
- active_slot_count=raw["activeCount"], active_is_candidate=raw["activeIsCandidate"],
- active_has_unavailable_class=raw["activeUnavailable"], active_has_red_dot=raw["activeRedDot"],
- active_hidden_input_count=raw["activeInputCount"],
- active_daily_id_matches_candidate=raw["activeIdMatches"],
- active_day_matches_candidate=raw["activeDayMatches"],
- active_time_matches_candidate=raw["activeTimeMatches"],
- active_capacity_matches_candidate=raw["activeCapacityMatches"],
- ),
- )
- def verify_precommit_selection(
- page: object, *, runtime_service: str, approval: PrecommitApproval,
- ) -> PrecommitApproval:
- """Read the current selected slot; never select, refresh, or submit anything.
- The caller still owns applicant/session binding and freshness of the Book
- inventory. This is a consistency check, not a reservation or inventory lock.
- """
- if not isinstance(approval, PrecommitApproval):
- raise CalendarBookError("Book selection requires a precommit approval")
- try:
- if read_calendar_service(page) != runtime_service:
- raise CalendarBookError("Book Calendar runtime service changed")
- raw = _snapshot(page, runtime_service, approval.candidate.day, approval.candidate, click=False)
- return _approve_selection_snapshot(approval.calendar_day, approval.candidate, raw)
- except CalendarBookError:
- raise
- except Exception:
- raise CalendarBookError("Book precommit readback failed") from None
- def select_slot_before_final(
- page: object, *, target_day: date, availability_packet: object, time_slots_packet: object,
- ) -> PrecommitApproval | None:
- """Select one positive slot from caller-captured Book packets; never submit.
- Both packets must be fresh captures from this page. Their content alone
- cannot prove capture time, applicant identity or route continuity. The
- orchestrator must establish these preconditions before calling this method.
- """
- if type(target_day) is not date:
- raise CalendarBookError("Book target day must be a date")
- try:
- service = read_calendar_service(page)
- guard_calendar(page)
- try:
- probe = parse_availability_packet(availability_packet)
- if probe.selected_month != (target_day.year, target_day.month):
- raise CalendarBookError("Book Availability belongs to another month")
- slots = parse_book_time_slots(
- time_slots_packet, target_day=target_day, runtime_service_id=service,
- )
- days = [item for item in probe.days if item.day == target_day]
- candidates = available_slot_candidates(slots, start_day=target_day, end_day=target_day)
- if not days or not days[0].is_available:
- if candidates:
- raise CalendarBookError("Book Availability and TimeSlots disagree")
- return None
- if not candidates:
- return None
- candidate = candidates[0]
- before = _snapshot(page, service, target_day, candidate, click=False)
- _require_ready(before, target_day)
- if before["clicked"]:
- raise CalendarBookError("Book read-only snapshot unexpectedly clicked")
- if not (before["activeCount"] == 1 and before["activeIsCandidate"]):
- acted = _snapshot(page, service, target_day, candidate, click=True)
- _require_ready(acted, target_day)
- if not acted["clicked"]:
- raise CalendarBookError("Book slot click was not acknowledged")
- after = _snapshot(page, service, target_day, candidate, click=False)
- return _approve_selection_snapshot(days[0], candidate, after)
- finally:
- guard_calendar(page)
- except CalendarBookError:
- raise
- except ItaProtocolError as exc:
- raise CalendarBookError(f"Book precommit rejected ({exc.code})") from None
- except Exception:
- raise CalendarBookError("Book Calendar selection or final guard failed") from None
- DATE_SELECTION_SCRIPT = r"""
- /* coordinate:ita-book-date-selection */
- const [serviceId, day, shouldClick] = arguments;
- const services = Array.from(document.querySelectorAll('#idServizio'));
- const runtimeMatches = window.location.origin === 'https://prenotami.esteri.it' &&
- window.location.pathname === '/BookingCalendar' && services.length === 1 &&
- services[0].value === serviceId;
- const buttons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
- const finalGuarded = buttons.length === 1 && buttons[0].disabled === true &&
- buttons[0].dataset.coordinateFinalGuard === 'enabled';
- const candidates = Array.from(document.querySelectorAll('.events a[data-date]'))
- .filter((link) => link.dataset.date === day);
- const link = candidates.length === 1 ? candidates[0] : null;
- const enabled = (element) => {
- if (!element || !element.isConnected || element.hasAttribute('disabled') ||
- element.getAttribute('aria-disabled') === 'true' ||
- element.classList.contains('disabled') || element.classList.contains('notAvailableDay') ||
- element.classList.contains('input-async-disabilitato') ||
- !element.classList.contains('input-async-abilitato')) return false;
- const style = window.getComputedStyle(element);
- // Calendar timeline links can have zero layout size while logically enabled.
- // The site's initialization uses HTMLElement.click(), as we do here, rather
- // than a pointer hit. Keep disabled/style checks and response/date readback;
- // do not require a clickable rectangle for this native date action.
- return style.display !== 'none' && style.visibility !== 'hidden' &&
- style.pointerEvents !== 'none' && Number.parseFloat(style.opacity || '1') > 0;
- };
- const timeline = Array.from(document.querySelectorAll('.events a.selected'));
- const content = Array.from(document.querySelectorAll('.events-content li.selected'));
- const selectedMatches = timeline.length === 1 && content.length === 1 &&
- timeline[0].dataset.date === day && content[0].dataset.date === day &&
- document.querySelector('.selected') === timeline[0];
- const candidateEnabled = enabled(link);
- let clicked = false;
- if (shouldClick === true && runtimeMatches && finalGuarded && candidateEnabled && !selectedMatches) {
- link.click();
- clicked = true;
- }
- return {runtimeMatches, finalGuarded, candidateCount: candidates.length,
- candidateEnabled, selectedMatches, clicked};
- """
- @dataclass(frozen=True, slots=True)
- class _CapturedMonth:
- probe: CalendarProbeResult
- availability_packet: object = field(repr=False)
- availability_service: str = field(repr=False)
- automatic_day: date | None = None
- automatic_slots_packet: object | None = field(default=None, repr=False)
- def book_date_preferences(user_inputs: Mapping[str, object]) -> tuple[date, date]:
- """Use the VFS preference keys and inclusive bounds without mutating inputs."""
- if not isinstance(user_inputs, Mapping):
- raise CalendarBookError("Book user inputs must be a mapping")
- dates = []
- for key, default in (("expected_start_date", "2000-01-01"),
- ("expected_end_date", "2100-01-01")):
- value = user_inputs.get(key, default)
- try:
- parsed = date.fromisoformat(value) if isinstance(value, str) else None
- except ValueError:
- parsed = None
- if parsed is None or parsed.isoformat() != value:
- raise CalendarBookError(f"Book {key} must use YYYY-MM-DD")
- dates.append(parsed)
- if dates[0] > dates[1]:
- raise CalendarBookError("Book date preference start exceeds end")
- return dates[0], dates[1]
- def _require_context(page: object, service: str, session_is_current: Callable[[], bool]) -> None:
- if session_is_current() is not True:
- raise CalendarBookError("Book applicant, route or browser Session changed")
- if read_calendar_service(page) != service:
- raise CalendarBookError("Book Calendar runtime service changed")
- guard_calendar(page)
- def _require_packet_tab(page: object, packet: object) -> None:
- tab = getattr(page, "tab_id", None)
- if not isinstance(tab, str) or not tab or getattr(packet, "tab_id", None) != tab:
- raise CalendarBookError("Book response did not belong to the current browser tab")
- if getattr(packet, "is_failed", False) is not False:
- raise CalendarBookError("Book browser request failed")
- def _post_body(packet: object) -> dict:
- body = packet.request.postData
- if isinstance(body, str):
- body = json.loads(body)
- if not isinstance(body, dict):
- raise CalendarBookError("Book request body was not an object")
- return body
- def _date_snapshot(page: object, service: str, day: date, *, click: bool = False) -> dict:
- raw = page.run_js(DATE_SELECTION_SCRIPT, service, day.isoformat(), click)
- boolean_keys = {"runtimeMatches", "finalGuarded", "candidateEnabled", "selectedMatches", "clicked"}
- if not isinstance(raw, dict) or set(raw) != boolean_keys | {"candidateCount"}:
- raise CalendarBookError("Book date control structure changed")
- if any(type(raw[key]) is not bool for key in boolean_keys):
- raise CalendarBookError("Book date control types changed")
- require_plain_nonnegative_int(raw["candidateCount"], "candidateCount")
- if not raw["runtimeMatches"] or not raw["finalGuarded"] or raw["candidateCount"] > 1:
- raise CalendarBookError("Book date control context was not unique and guarded")
- if not click and raw["clicked"]:
- raise CalendarBookError("Book date readback unexpectedly clicked")
- return raw
- def _wait_selected_day(page: object, service: str, day: date, *, timeout: float) -> None:
- deadline = time.monotonic() + timeout
- while True:
- raw = _date_snapshot(page, service, day)
- if raw["candidateCount"] == 1 and raw["selectedMatches"]:
- return
- if time.monotonic() >= deadline:
- raise CalendarBookError("Book selected date did not match the response before timeout")
- time.sleep(0.1)
- def _click_date(page: object, service: str, day: date, *, timeout: float) -> None:
- deadline = time.monotonic() + timeout
- while True:
- raw = _date_snapshot(page, service, day)
- if raw["selectedMatches"]:
- raise CalendarBookError("Book date is already selected without a fresh captured response")
- if raw["candidateCount"] == 1 and raw["candidateEnabled"]:
- break
- if time.monotonic() >= deadline:
- raise CalendarBookError("Book date control was not ready before timeout")
- time.sleep(0.1)
- acted = _date_snapshot(page, service, day, click=True)
- if not acted["clicked"]:
- raise CalendarBookError("Book date click was not acknowledged")
- def _capture_month(
- page: object, *, action: Callable[[], None], service: str,
- session_is_current: Callable[[], bool], timeout: float, dom_timeout: float,
- previous: _CapturedMonth | None = None,
- ) -> _CapturedMonth:
- """Capture Availability plus the site's automatic first-day TimeSlots."""
- _require_context(page, service, session_is_current)
- page.listen.start([AVAILABILITY_PATH, TIME_SLOTS_PATH], method="POST")
- try:
- action()
- wait_for_calendar_service(
- page, session_is_current=session_is_current,
- expected_service=service, timeout=min(dom_timeout, timeout),
- )
- _require_context(page, service, session_is_current)
- deadline = time.monotonic() + timeout
- captured = {}
- probe = None
- # Only two matching responses belong to one normal month-load action.
- for _ in range(2):
- remaining = deadline - time.monotonic()
- if remaining <= 0:
- raise CalendarBookError("Book month responses exceeded the time budget")
- packet = page.listen.wait(timeout=remaining, raise_err=False)
- if not packet:
- raise CalendarBookError("Book month response was not observed before timeout")
- _require_packet_tab(page, packet)
- status = packet.response.status
- if type(status) is not int or status != 200:
- raise CalendarBookError("Book Calendar response status was not 200",
- http_status=status if type(status) is int else None)
- path, _ = same_origin_path(packet.url)
- if path not in {AVAILABILITY_PATH, TIME_SLOTS_PATH} or path in captured:
- raise CalendarBookError("Book month produced an unexpected or duplicate response")
- captured[path] = packet
- if path == AVAILABILITY_PATH:
- probe = parse_availability_packet(packet)
- if previous and probe.selected_month != next_month_value(previous.probe.selected_month):
- raise CalendarBookError("Book Calendar did not advance exactly one month")
- if not probe.days or TIME_SLOTS_PATH in captured:
- break
- elif probe is not None:
- break
- if probe is None:
- raise CalendarBookError("Book month did not return Availability")
- availability_packet = captured[AVAILABILITY_PATH]
- availability_service = _runtime_id(_post_body(availability_packet).get("_Servizio"))
- if previous and availability_service != previous.availability_service:
- raise CalendarBookError("Book Availability runtime service changed")
- automatic = captured.get(TIME_SLOTS_PATH)
- automatic_day = None
- if probe.days:
- if automatic is None:
- raise CalendarBookError("Book automatic day response was not captured")
- automatic_day = _request_day(_post_body(automatic).get("selectedDay"))
- if automatic_day not in {item.day for item in probe.days}:
- raise CalendarBookError("Book automatic day escaped current Availability")
- auto_slots = parse_book_time_slots(automatic, target_day=automatic_day, runtime_service_id=service)
- auto_inventory = next(item for item in probe.days if item.day == automatic_day)
- if not auto_inventory.is_available and available_slot_candidates(auto_slots):
- raise CalendarBookError("Book automatic Availability and TimeSlots disagree")
- _wait_selected_day(page, service, automatic_day, timeout=dom_timeout)
- elif automatic is not None:
- raise CalendarBookError("Book empty Availability unexpectedly returned TimeSlots")
- _require_context(page, service, session_is_current)
- return _CapturedMonth(probe, availability_packet, availability_service, automatic_day, automatic)
- finally:
- page.listen.stop()
- def _try_day(
- page: object, month: _CapturedMonth, day: date, *, service: str,
- session_is_current: Callable[[], bool], timeout: float, dom_timeout: float,
- ) -> PrecommitApproval | None:
- _require_context(page, service, session_is_current)
- current_date = _date_snapshot(page, service, day)
- if day == month.automatic_day and current_date["selectedMatches"]:
- times_packet = month.automatic_slots_packet
- _wait_selected_day(page, service, day, timeout=dom_timeout)
- else:
- times_packet = listen_once(
- page, target=TIME_SLOTS_PATH, method="POST",
- action=lambda: _click_date(page, service, day, timeout=dom_timeout),
- timeout=timeout,
- )
- _require_packet_tab(page, times_packet)
- parse_book_time_slots(times_packet, target_day=day, runtime_service_id=service)
- _wait_selected_day(page, service, day, timeout=dom_timeout)
- slots = parse_book_time_slots(times_packet, target_day=day, runtime_service_id=service)
- candidates = available_slot_candidates(slots, start_day=day, end_day=day)
- if not candidates:
- # Inventory competition is not a protocol error. No slot was clicked.
- _require_context(page, service, session_is_current)
- return None
- deadline = time.monotonic() + dom_timeout
- while True:
- _require_context(page, service, session_is_current)
- raw = _snapshot(page, service, day, candidates[0], click=False)
- if not raw["runtimeMatches"] or not raw["finalGuarded"] or raw["candidateCount"] > 1:
- raise CalendarBookError("Book slot DOM changed its context or uniqueness")
- if raw["candidateReady"]:
- _require_ready(raw, day)
- break
- if time.monotonic() >= deadline:
- raise CalendarBookError("Book slot DOM did not match the response before timeout")
- time.sleep(0.1)
- approval = select_slot_before_final(
- page, target_day=day, availability_packet=month.availability_packet,
- time_slots_packet=times_packet,
- )
- _require_context(page, service, session_is_current)
- return approval
- def recheck_calendar_before_final(
- page: object, *, lookahead_months: int, start_day: date, end_day: date,
- session_is_current: Callable[[], bool], preferred_day: date | None = None,
- month_click_interval_seconds: float = DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
- timeout: float = 30, dom_timeout: float = 5,
- log: Callable[[str], None] | None = None,
- ) -> PrecommitApproval | None:
- """Fresh Book-only scan with an optional date hint; never submit a booking.
- There are at most two bounded passes: the hinted day, then an ascending
- fallback. The caller must attest the prepared applicant/route Session via
- session_is_current. No external snapshot or cached response is accepted.
- """
- try:
- # Use existing pure validators before starting any browser action.
- month_starts(date(2000, 1, 1), lookahead_months)
- if type(start_day) is not date or type(end_day) is not date:
- raise CalendarBookError("Book date bounds must be dates")
- available_calendar_days((), start_day=start_day, end_day=end_day)
- if preferred_day is not None and type(preferred_day) is not date:
- raise CalendarBookError("Book preferred day must be a date")
- for value in (timeout, dom_timeout, month_click_interval_seconds):
- if type(value) not in (int, float) or not 0 <= value < float("inf"):
- raise CalendarBookError("Book time budget must be finite and nonnegative")
- if timeout == 0 or not callable(session_is_current):
- raise CalendarBookError("Book requires a positive timeout and a Session check")
- service = read_calendar_service(page)
- _require_context(page, service, session_is_current)
- common = dict(service=service, session_is_current=session_is_current,
- timeout=timeout, dom_timeout=dom_timeout)
- def initial() -> _CapturedMonth:
- return _capture_month(page, action=lambda: refresh_calendar(page), **common)
- def advance(previous: _CapturedMonth) -> _CapturedMonth:
- if month_click_interval_seconds:
- time.sleep(month_click_interval_seconds)
- return _capture_month(page, action=lambda: click_next_month(page), previous=previous, **common)
- def positive_days(month: _CapturedMonth) -> tuple:
- return available_calendar_days(month.probe.days, start_day=start_day, end_day=end_day)
- first = initial()
- anchor = first.probe.selected_month
- current = first
- attempted = set()
- if preferred_day is not None and start_day <= preferred_day <= end_day:
- offset = (preferred_day.year - anchor[0]) * 12 + preferred_day.month - anchor[1]
- if 0 <= offset < lookahead_months:
- for _ in range(offset):
- current = advance(current)
- if preferred_day in {item.day for item in positive_days(current)}:
- attempted.add(preferred_day)
- approval = _try_day(page, current, preferred_day, **common)
- if approval is not None:
- return approval
- # A failed hint cannot cause a stale earlier month's response
- # to be reused. Restart the native scan once and recapture.
- first = initial()
- if (first.probe.selected_month != anchor or
- first.availability_service != current.availability_service):
- raise CalendarBookError("Book fallback restart changed the Calendar anchor")
- current = first
- for index in range(lookahead_months):
- if current.probe.selected_month > (end_day.year, end_day.month):
- return None
- days = positive_days(current)
- if log:
- log(f"Italy Book Calendar month={month_text(current.probe.selected_month)} candidates={len(days)}")
- for item in days:
- if item.day in attempted:
- continue
- attempted.add(item.day)
- approval = _try_day(page, current, item.day, **common)
- if approval is not None:
- return approval
- if current.probe.selected_month >= (end_day.year, end_day.month):
- return None
- if index + 1 < lookahead_months:
- current = advance(current)
- return None
- except CalendarBookError:
- raise
- except ItaProtocolError as exc:
- raise CalendarBookError(f"Book Calendar protocol rejected ({exc.code})") from None
- except Exception:
- raise CalendarBookError("Book Calendar recheck failed; no further action was attempted") from None
- finally:
- # Do not leave the final button enabled after a native refresh or error.
- try:
- if same_origin_path(page.url)[0] == CALENDAR_PATH:
- guard_calendar(page)
- except Exception:
- raise CalendarBookError("Book final-button guard could not be verified") from None
|