| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782 |
- #!/usr/bin/env python3
- """Prepare an applicant Calendar; default stops before final booking.
- Default/preflight is local-only. --run permits one manual OTP and one AVANTI
- in a new temporary browser. --use-local-query-account explicitly reuses the
- saved credentials only; Query browser profiles are never loaded.
- Q-CAL supplies preparation/audit helpers; CS4B owns all Calendar decisions.
- --submit-once adds a separately confirmed REAL submission for local discovery,
- with a persistent local fence and manual receipt review, never production final.
- """
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import math
- import os
- import re
- import sys
- from dataclasses import dataclass, field
- from pathlib import Path
- from typing import Callable, Mapping
- REPO_ROOT = Path(__file__).resolve().parents[1]
- if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
- from plugins import ita_calendar_book as calendar_book
- from plugins.ita_final_read_port import FinalReceiptReadPort
- from plugins.ita_calendar_query import CALENDAR_PATH, guard_calendar, same_origin_path
- from plugins.ita_plugin import (
- BOOKING_CALENDAR_PREFINAL_STOP_LABEL,
- BOOKING_FORM_DISCOVERY_STOP_LABEL,
- BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
- PERSISTENT_BROWSER_PROFILE_KEY,
- SERVICES_PROBE_QUERY_MODE,
- ItaPlugin,
- )
- from plugins.ita_protocol import ItaRouteConfig, PrecommitApproval, resolve_route_config
- from tools import debug_ita_calendar_gate as preparation
- from tools import ita_final_evidence as final_evidence
- from tools.debug_ita_query import DEBUG_ROUTE_ENV_NAMES, _popup_text_for_log, resolve_debug_route
- from tools.debug_ita_session import _get_credentials, resolve_chrome_path
- from utils.ita_local_profile import ITA_QUERY_ACCOUNT_FILE
- from utils.local_account import LocalAccountConfigurationError, load_local_account
- from vs_types import AppointmentType, AvailabilityStatus, BizLogicError, VSBookResult, VSQueryResult
- BOOK_GATE_CONTRACT = "book-final-attribution-v9"
- CALENDAR_READY_TIMEOUT_SECONDS = 5
- BOOK_GATE_SOURCE_PATHS = (
- Path(__file__), Path(preparation.__file__),
- REPO_ROOT / "plugins" / "ita_calendar_session.py",
- REPO_ROOT / "plugins" / "ita_plugin.py",
- REPO_ROOT / "plugins" / "ita_calendar_book.py",
- REPO_ROOT / "plugins" / "ita_calendar_query.py",
- REPO_ROOT / "plugins" / "ita_protocol.py",
- REPO_ROOT / "plugins" / "ita_final_read_port.py",
- REPO_ROOT / "plugins" / "ita_reservation.py",
- REPO_ROOT / "plugins" / "ita_booking_final.py",
- REPO_ROOT / "tools" / "debug_ita_query.py",
- REPO_ROOT / "tools" / "debug_ita_session.py",
- REPO_ROOT / "tools" / "ita_final_evidence.py",
- REPO_ROOT / "tools" / "ita_local_handoff.py",
- REPO_ROOT / "utils" / "local_account.py",
- REPO_ROOT / "utils" / "ita_local_profile.py",
- )
- BOOK_GATE_FINGERPRINT = hashlib.sha256(
- b"".join(path.read_bytes() for path in BOOK_GATE_SOURCE_PATHS)
- ).hexdigest()[:12]
- _COUNT_KEYS = {"otpRequests", "avantiPosts", "availabilityRequests", "finalRequests"}
- class BookGateError(ValueError):
- """Tool-owned safe message, with no provider data or credential values."""
- @dataclass(frozen=True)
- class _ApplicantBinding:
- plugin_id: int
- page: object = field(repr=False)
- tab_id: str = field(repr=False)
- username: str = field(repr=False)
- login_generation: float
- route: ItaRouteConfig
- @classmethod
- def capture(cls, plugin: ItaPlugin, username: str, route: ItaRouteConfig):
- page = plugin.page
- generation = plugin.session_create_time
- if (not page or not isinstance(page.tab_id, str) or not page.tab_id
- or type(generation) not in (int, float)
- or not math.isfinite(generation) or generation <= 0):
- raise BookGateError("Applicant Session identity is unavailable")
- binding = cls(id(plugin), page, page.tab_id, username.strip().casefold(), generation, route)
- binding.require_current(plugin, expected_path="/UserArea")
- return binding
- def require_current(self, plugin: ItaPlugin, *, expected_path: str | None = None) -> None:
- if (id(plugin) != self.plugin_id or plugin.page is not self.page
- or self.page.tab_id != self.tab_id
- or not self.username
- or plugin.config.account.username.strip().casefold() != self.username
- or plugin.session_create_time != self.login_generation
- or plugin.free_config.get(PERSISTENT_BROWSER_PROFILE_KEY) is not None
- or getattr(plugin, "_persistent_profile_path", None) is not None
- or plugin.free_config.get("final_submit_enabled") is not False
- or plugin.free_config.get("query_mode") != SERVICES_PROBE_QUERY_MODE
- or getattr(plugin, "_calendar_query_route_key", None) is not None
- or plugin._resolve_route(
- AppointmentType(routing_key=self.route.routing_key)
- ) != self.route):
- raise BookGateError("Applicant, browser, route or preparation identity changed")
- path, _ = same_origin_path(self.page.url)
- if expected_path is not None and path != expected_path:
- raise BookGateError("Applicant browser is not on the expected stage")
- def _counts(audit: preparation.CalendarRequestAudit) -> dict[str, int]:
- raw = audit.settled_snapshot()
- if (not isinstance(raw, dict) or set(raw) != _COUNT_KEYS
- or any(type(value) is not int or value < 0 for value in raw.values())):
- raise BookGateError("Business-request audit shape changed")
- return raw
- def _budget(counts: dict[str, int], *, otp: int, avanti: int, before_calendar: bool = False) -> None:
- if (counts["otpRequests"] != otp or counts["avantiPosts"] != avanti
- or counts["finalRequests"] != 0
- or (before_calendar and counts["availabilityRequests"] != 0)):
- raise BookGateError("Business requests exceeded the current one-shot budget")
- def _current_packet(packet: object, binding: _ApplicantBinding) -> None:
- if (getattr(packet, "tab_id", None) != binding.tab_id
- or getattr(packet, "is_failed", None) is not False
- or type(packet.response.status) is not int):
- raise BookGateError("Preparation response is not a completed request from this applicant tab")
- def _guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
- return preparation.calendar_session.guarded_preflight_script(route, booking_path)
- def _wait_preflight(plugin: ItaPlugin, binding: _ApplicantBinding, stage) -> None:
- booking_path = f"/Services/Booking/{binding.route.service_id}"
- binding.require_current(plugin, expected_path=booking_path)
- preparation.wait_for_booking_preflight(
- binding.page, script=_guarded_preflight_script(binding.route, booking_path), stage=stage,
- )
- binding.require_current(plugin, expected_path=booking_path)
- def _native_click(plugin: ItaPlugin, binding: _ApplicantBinding, selector: str) -> None:
- binding.require_current(plugin, expected_path=f"/Services/Booking/{binding.route.service_id}")
- plugin.mouse.human_click_ele(preparation._element_or_fail(binding.page, selector))
- def _require_stop_result(result: object) -> VSBookResult:
- if (not isinstance(result, VSBookResult) or result.success is not False
- or any(getattr(result, key) for key in
- ("session_id", "urn", "account", "book_date", "book_time", "payment_link"))):
- raise BookGateError("Book returned appointment-success data during a pre-final gate")
- return result
- def _selection_readback(
- plugin: ItaPlugin, binding: _ApplicantBinding, user_inputs: dict, result: VSBookResult,
- ) -> dict:
- binding.require_current(plugin, expected_path=CALENDAR_PATH)
- guard_calendar(binding.page)
- if not plugin._calendar_book_context_matches(binding.route, binding.username):
- raise BookGateError("Book-specific Calendar preparation is no longer current")
- approval = plugin.last_booking_precommit
- if result.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL and approval is None:
- return {"selectionVerified": False, "selectedDate": None, "selectedTime": None,
- "remaining": None, "bookResultSuccess": False}
- if result.label != BOOKING_CALENDAR_PREFINAL_STOP_LABEL or not isinstance(approval, PrecommitApproval):
- raise BookGateError("Book did not return the expected pre-final checkpoint")
- candidate = approval.candidate
- start, end = calendar_book.book_date_preferences(user_inputs)
- if (not start <= candidate.day <= end or not approval.calendar_day.is_available
- or not candidate.is_available or candidate.day != approval.calendar_day.day):
- raise BookGateError("Book checkpoint does not match positive inventory and date preferences")
- service = calendar_book.read_calendar_service(binding.page)
- raw = calendar_book._snapshot(binding.page, service, candidate.day, candidate, click=False)
- calendar_book._require_ready(raw, candidate.day)
- if (raw["clicked"] or raw["activeCount"] != 1 or raw["activeInputCount"] != 1
- or raw["activeUnavailable"] or raw["activeRedDot"]
- or not all(raw[key] for key in (
- "activeIsCandidate", "activeIdMatches", "activeDayMatches",
- "activeTimeMatches", "activeCapacityMatches",
- ))):
- raise BookGateError("Selected slot changed before the read-only gate readback")
- return {"selectionVerified": True, "selectedDate": candidate.day.isoformat(),
- "selectedTime": candidate.time_label, "remaining": candidate.slots_free,
- "bookResultSuccess": False}
- def _book_credentials(
- env: Mapping[str, str], *, use_local_query_account: bool = False,
- ) -> tuple[str, str]:
- if use_local_query_account:
- try:
- account = load_local_account(ITA_QUERY_ACCOUNT_FILE)
- except LocalAccountConfigurationError:
- raise BookGateError(
- "Local Query account is invalid; check config/ita_query_account.local.json "
- "and its private file permissions"
- ) from None
- print("ITA_BOOK_GATE_CREDENTIALS role=applicant profile=temporary source=local_query_file", flush=True)
- return account.username, account.password
- # A projection rather than dict(env): Query/general credentials cannot leak
- # into the fallback helper even when inherited from the user's terminal.
- print("ITA_BOOK_GATE_CREDENTIALS role=applicant profile=temporary source=book_environment_or_prompt", flush=True)
- return _get_credentials({
- "ITA_USERNAME": env.get("ITA_BOOK_USERNAME", ""),
- "ITA_PASSWORD": env.get("ITA_BOOK_PASSWORD", ""),
- }, non_interactive=False)
- def _resolve_inputs(env: Mapping[str, str], user_inputs: Mapping[str, str] | None):
- if any(not str(env.get(name, "")).strip() for name in DEBUG_ROUTE_ENV_NAMES):
- raise BookGateError("Book gate requires all four explicit ITA route fields")
- preferences = dict(user_inputs or {})
- if not set(preferences) <= {"expected_start_date", "expected_end_date"}:
- raise BookGateError("Gate inputs may only contain the two date preferences")
- calendar_book.book_date_preferences(preferences)
- debug_route = resolve_debug_route(env)
- chrome_path = resolve_chrome_path(env)
- # Synthetic values only validate the existing config builder. Nothing leaves
- # this process, and no account file or real credential is read in preflight.
- config = preparation.build_calendar_gate_config(
- env, username="preflight@example.test", password="local-only", route=debug_route,
- )
- route = resolve_route_config(config.free_config["apt_configs"], debug_route.routing_key)
- return debug_route, route, chrome_path, preferences
- _PREPARATION_FAILURES = {
- "Italy Book preparation requires a single-tourism Calendar route": "route_not_supported",
- "Italy Book cannot reuse a Query preparation or another route": "query_or_route_mismatch",
- "Italy Book preparation requires an authenticated user Session and final disabled": "applicant_session_not_ready",
- "Italy Book preparation did not identify the current Calendar service": "calendar_service_unidentified",
- "Italy Book Calendar service did not initialize before timeout": "calendar_service_not_ready",
- }
- _PRODUCTION_BOOK_FAILURES = {
- "Book date control structure changed": "date_snapshot_structure_changed",
- "Book date control types changed": "date_snapshot_types_changed",
- "Book date control context was not unique and guarded": "date_context_not_ready",
- "Book date readback unexpectedly clicked": "date_readback_clicked",
- "Book date is already selected without a fresh captured response": "date_selected_without_fresh_response",
- "Book date control was not ready before timeout": "date_control_timeout",
- "Book date click was not acknowledged": "date_click_not_acknowledged",
- "Book selected date did not match the response before timeout": "selected_date_timeout",
- "Book TimeSlots request date format changed": "timeslot_request_date_format_changed",
- "Book TimeSlots request method or path changed": "timeslot_request_route_changed",
- "Book TimeSlots response status was not 200": "timeslot_response_status_rejected",
- "Book TimeSlots request fields changed": "timeslot_request_fields_changed",
- "Book TimeSlots request does not match the current service": "timeslot_service_mismatch",
- "Book TimeSlots request does not match the target day": "timeslot_request_day_mismatch",
- "Book TimeSlots response contains another day": "timeslot_response_day_mismatch",
- "Book TimeSlots packet could not be validated": "timeslot_packet_invalid",
- "Book slot snapshot fields changed": "slot_snapshot_fields_changed",
- "Book slot snapshot boolean types changed": "slot_snapshot_types_changed",
- "Book selected-date snapshot types changed": "selected_date_snapshot_types_changed",
- "Book slot DOM changed its context or uniqueness": "slot_context_changed",
- "Book slot DOM did not match the response before timeout": "slot_dom_timeout",
- "Book candidate is not safely selectable": "candidate_not_selectable",
- "Book selected day is marked unavailable": "selected_day_unavailable",
- "Book date or slot is not unique": "date_or_slot_not_unique",
- "Book timeline and content dates do not match the target": "selected_dates_mismatch",
- "Book Availability and TimeSlots disagree": "inventory_disagreement",
- "Book read-only snapshot unexpectedly clicked": "slot_snapshot_clicked",
- "Book slot click was not acknowledged": "slot_click_not_acknowledged",
- "Book readback unexpectedly clicked": "slot_readback_clicked",
- "Book precommit rejected (precommit_rejected)": "precommit_readback_rejected",
- "Book Calendar selection or final guard failed": "selection_or_guard_failed",
- "Book applicant, route or browser Session changed": "applicant_context_changed",
- "Book Calendar runtime service changed": "calendar_service_changed",
- "Book response did not belong to the current browser tab": "response_tab_mismatch",
- "Book browser request failed": "browser_request_failed",
- "Book Calendar recheck failed; no further action was attempted": "calendar_recheck_failed",
- "Italy Book Calendar failed before final confirmation": "calendar_internal_failure",
- "Book final-button guard could not be verified": "final_guard_failed",
- }
- BOOK_FAILURE_STATE_SCRIPT = r"""
- /* coordinate:ita-book-failure-state-readonly */
- const service = Array.from(document.querySelectorAll('#idServizio'));
- const timeline = Array.from(document.querySelectorAll('.events a.selected'));
- const content = Array.from(document.querySelectorAll('.events-content li.selected'));
- const slots = content.length === 1 ? Array.from(content[0].querySelectorAll('.fascia')) : [];
- const finalButtons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
- const states = slots.slice(0, 12).map(slot => {
- const style = window.getComputedStyle(slot), rect = slot.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);
- const inViewport = right > left && bottom > top;
- const hit = inViewport ? document.elementFromPoint((left + right)/2, (top + bottom)/2) : null;
- return {
- active: slot.classList.contains('act'),
- markedUnavailable: slot.classList.contains('notAvailableFascia'),
- redDot: Boolean(slot.querySelector('.dotRed')),
- cssVisible: style.display !== 'none' && style.visibility !== 'hidden' &&
- style.pointerEvents !== 'none' && Number.parseFloat(style.opacity || '1') > 0,
- hasSize: rect.width > 0 && rect.height > 0,
- inViewport,
- centerHit: Boolean(hit && (hit === slot || slot.contains(hit))),
- hiddenInputCount: slot.querySelectorAll('input[type="hidden"]').length,
- };
- });
- return {
- pathMatches: location.origin === 'https://prenotami.esteri.it' && location.pathname === '/BookingCalendar',
- serviceControlCount: service.length,
- serviceValuePresent: service.length === 1 && typeof service[0].value === 'string' && Boolean(service[0].value),
- timelineSelectedCount: timeline.length, contentSelectedCount: content.length,
- firstSelectedIsTimeline: timeline.length === 1 && document.querySelector('.selected') === timeline[0],
- selectedDatesMatch: timeline.length === 1 && content.length === 1 && Boolean(timeline[0].dataset.date) &&
- timeline[0].dataset.date === content[0].dataset.date,
- slotCount: slots.length, activeSlotCount: document.querySelectorAll('.fascia.act').length,
- finalButtonCount: finalButtons.length,
- finalGuarded: finalButtons.length === 1 && finalButtons[0].disabled === true &&
- finalButtons[0].dataset.coordinateFinalGuard === 'enabled',
- timeSlotResourceEntries: performance.getEntriesByType('resource').filter(entry => {
- try { const url = new URL(entry.name); return url.origin === location.origin &&
- url.pathname === '/BookingCalendar/RetrieveTimeSlots'; } catch (_) { return false; }
- }).length,
- slotStatesTruncated: slots.length > states.length, slotStates: states,
- };
- """
- _BOOK_STATE_BOOLS = {"pathMatches", "serviceValuePresent", "selectedDatesMatch", "firstSelectedIsTimeline",
- "finalGuarded", "slotStatesTruncated"}
- _BOOK_STATE_COUNTS = {"serviceControlCount", "timelineSelectedCount", "contentSelectedCount", "slotCount",
- "activeSlotCount", "finalButtonCount", "timeSlotResourceEntries"}
- _BOOK_SLOT_BOOLS = {"active", "markedUnavailable", "redDot", "cssVisible", "hasSize", "inViewport", "centerHit"}
- def _print_production_book_diagnostic(page: object) -> None:
- """After-failure shape/visibility only; never emit browser text or field values."""
- result = {"contract": BOOK_GATE_CONTRACT, "afterFailure": True, "readSucceeded": False}
- try:
- if same_origin_path(page.url)[0] != CALENDAR_PATH:
- raise ValueError("Not Calendar")
- raw = page.run_js(BOOK_FAILURE_STATE_SCRIPT)
- if (not isinstance(raw, dict) or set(raw) != _BOOK_STATE_BOOLS | _BOOK_STATE_COUNTS | {"slotStates"}
- or any(type(raw[key]) is not bool for key in _BOOK_STATE_BOOLS)
- or any(type(raw[key]) is not int or not 0 <= raw[key] <= 100000 for key in _BOOK_STATE_COUNTS)
- or not isinstance(raw["slotStates"], list) or len(raw["slotStates"]) > 12):
- raise ValueError("Unrecognized state shape")
- for slot in raw["slotStates"]:
- if (not isinstance(slot, dict) or set(slot) != _BOOK_SLOT_BOOLS | {"hiddenInputCount"}
- or any(type(slot[key]) is not bool for key in _BOOK_SLOT_BOOLS)
- or type(slot["hiddenInputCount"]) is not int or not 0 <= slot["hiddenInputCount"] <= 100000):
- raise ValueError("Unrecognized slot shape")
- result.update(readSucceeded=True, state=raw)
- except Exception:
- pass # Diagnostics must neither expose raw data nor replace the original failure.
- print("ITA_BOOK_GATE_SELECTION_DIAGNOSTIC=" + json.dumps(result, sort_keys=True), flush=True)
- def _print_calendar_preparation_diagnostic(page: object) -> None:
- """Read structural metadata after failure; never log the runtime ID itself."""
- diagnostic = {"contract": BOOK_GATE_CONTRACT, "afterFailure": True, "readSucceeded": False}
- try:
- diagnostic["pathMatches"] = same_origin_path(page.url)[0] == CALENDAR_PATH
- if diagnostic["pathMatches"]:
- tab_id = getattr(page, "tab_id", None)
- diagnostic["tabIdPresent"] = isinstance(tab_id, str) and bool(tab_id)
- raw = page.run_js(calendar_book.RUNTIME_SERVICE_SCRIPT)
- diagnostic["readSucceeded"] = True
- diagnostic["snapshotIsObject"] = isinstance(raw, dict)
- if isinstance(raw, dict):
- count, value = raw.get("count"), raw.get("value")
- diagnostic.update(
- snapshotKeysMatch=set(raw) == {"path", "count", "value"},
- snapshotPathMatches=raw.get("path") == CALENDAR_PATH,
- controlCountType=(type(count).__name__ if type(count) in (int, float, bool, str, type(None)) else "other"),
- controlCount=(count if type(count) is int and 0 <= count <= 10000 else None),
- valueType=(type(value).__name__ if type(value) in (str, int, float, bool, type(None)) else "other"),
- valueLength=len(value) if isinstance(value, str) else None,
- valuePresent=bool(value) if isinstance(value, str) else None,
- valueTrimmed=value == value.strip() if isinstance(value, str) else None,
- valueAccepted=False,
- )
- if isinstance(value, str):
- try:
- calendar_book._runtime_id(value)
- diagnostic["valueAccepted"] = True
- except calendar_book.CalendarBookError:
- pass
- except Exception:
- # The original failure must survive a failed best-effort readback.
- diagnostic["readSucceeded"] = False
- print("ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC=" + json.dumps(diagnostic, sort_keys=True), flush=True)
- def _stop_listener_if_active(page: object) -> None:
- # listen_once already stops it; the installed SDK's stop is not idempotent.
- listener = page.listen
- if listener.listening:
- listener.stop()
- def _failure(stage: str, exc: BaseException) -> None:
- # Provider exception strings may contain bodies, URLs, credentials or OTP.
- message = str(exc) if type(exc) is BookGateError else "Stage failed; use the allowlisted diagnostic"
- failure = {
- "stage": stage, "type": type(exc).__name__, "message": message,
- }
- if stage == "calendar_preparation" and type(exc) is BizLogicError and isinstance(exc.message, str):
- reason = _PREPARATION_FAILURES.get(exc.message)
- if reason:
- failure["reason"] = reason
- elif stage == "production_book" and type(exc) is BizLogicError and isinstance(exc.message, str):
- failure["reason"] = _PRODUCTION_BOOK_FAILURES.get(exc.message, "unclassified_book_failure")
- if failure["reason"] == "unclassified_book_failure":
- # Dynamic protocol codes never enter output; emit only a fixed category.
- protocol = re.fullmatch(
- r"Book (TimeSlots protocol|Calendar protocol|precommit) rejected \([a-z_]{1,64}\)",
- exc.message,
- )
- if protocol:
- failure["reason"] = {
- "TimeSlots protocol": "timeslot_protocol_rejected",
- "Calendar protocol": "calendar_protocol_rejected",
- "precommit": "precommit_readback_rejected",
- }[protocol[1]]
- print("ITA_BOOK_GATE_FAILED=" + json.dumps(failure, sort_keys=True), flush=True)
- def _receipt_observer(observed):
- def observe(page):
- audit = preparation.CalendarRequestAudit(page, include_time_slots=True)
- audit.start()
- def finish():
- try:
- counts = audit.settled_snapshot()
- expected = _COUNT_KEYS | {"timeSlotRequests"}
- if (not isinstance(counts, dict) or set(counts) != expected or
- any(type(value) is not int or value != 0 for value in counts.values())):
- raise BookGateError("Receipt tab emitted unexpected business requests")
- observed.append(counts)
- finally:
- audit.stop()
- return finish
- return observe
- def _single_submission_verified(audit, before):
- after = _counts(audit)
- return (before["finalRequests"] == 0 and after["finalRequests"] == 1 and
- all(after[k] == before[k] for k in _COUNT_KEYS - {"finalRequests"}))
- def _verify_receipt_baseline(plugin, route) -> dict:
- """Optional background-tab acceptance; no final submission is reachable."""
- observed = []
- port = FinalReceiptReadPort(plugin, route, observe_tab=_receipt_observer(observed))
- snapshot = port()
- if not port.session_is_current() or len(observed) != 1:
- raise BookGateError("Receipt read acceptance did not finish")
- calendar_book.verify_precommit_selection(plugin.page, runtime_service=port.target.runtime_service,
- approval=port.target.approval)
- return {"verified": True, "recordCount": len(snapshot.records), "calendarSelectionPreserved": True,
- "businessRequests": observed[0], "finalSubmissionEnabled": False}
- def run_book_gate(
- env: Mapping[str, str], *, execute: bool = False,
- use_local_query_account: bool = False,
- user_inputs: Mapping[str, str] | None = None,
- otp_reader: Callable[[], str] = preparation._read_manual_otp,
- verify_receipts: bool = False,
- submit_once: bool = False,
- final_confirm: Callable[[str], str] = input,
- review_reader: Callable[[str], str] = input,
- ) -> int:
- print(f"ITA_BOOK_GATE_TOOL_CONTRACT version={BOOK_GATE_CONTRACT} source_sha256={BOOK_GATE_FINGERPRINT}", flush=True)
- plugin = binding = audit = None
- before = after = observed = None
- preparation_counts = book_counts = None
- selection: dict = {}
- receipt_baseline = None
- final_run = None
- audit_verified = False
- entry_calls = calendar_calls = 0
- stage, outcome, exit_code = "configuration", "failed", 1
- try:
- if type(verify_receipts) is not bool:
- raise BookGateError("Receipt verification flag must be boolean")
- if type(submit_once) is not bool or (submit_once and not verify_receipts):
- raise BookGateError("One-shot final requires explicit receipt verification")
- if submit_once:
- final_evidence.require_unused_claim()
- debug_route, route, chrome_path, preferences = _resolve_inputs(env, user_inputs)
- if not execute:
- print("ITA_BOOK_GATE_PREFLIGHT_OK external_requests=0 credentials_read=false browser_created=false", flush=True)
- return 0
- if execute is not True:
- raise BookGateError("Book gate execute must be an explicit boolean")
- stage = "applicant_credentials"
- username, password = _book_credentials(env, use_local_query_account=use_local_query_account)
- config = preparation.build_calendar_gate_config(
- env, username=username, password=password, route=debug_route,
- )
- os.environ["CHROME_BIN"] = str(chrome_path)
- plugin = ItaPlugin(group_id="ita-book-prefinal-gate")
- plugin.set_log(lambda message: print(
- _popup_text_for_log(str(message).replace(username, "<applicant>").replace(password, "<password>")),
- flush=True,
- ))
- plugin.set_config(config)
- stage = "applicant_login"
- plugin.create_session()
- binding = _ApplicantBinding.capture(plugin, username, route)
- stage = "reservation_before"
- audit = preparation.CalendarRequestAudit(binding.page)
- audit.start()
- before = preparation.read_reservation_snapshot(binding.page)
- _budget(_counts(audit), otp=0, avanti=0, before_calendar=True)
- print(f"ITA_BOOK_GATE_RESERVATION_BEFORE reservations={before.reservations} waitlist={before.waitlist}", flush=True)
- inputs = {**preferences, "username": username}
- trigger = VSQueryResult(
- success=True, apt_type=debug_route.appointment_type(),
- availability_status=AvailabilityStatus.NoneAvailable,
- )
- stage = "booking_form_entry"
- binding.require_current(plugin)
- entry_calls += 1
- entry = _require_stop_result(plugin.book(trigger, user_inputs=inputs))
- binding.require_current(plugin)
- _budget(_counts(audit), otp=0, avanti=0, before_calendar=True)
- if entry.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL:
- outcome, exit_code = "entry_unavailable", 2
- elif entry.label != BOOKING_FORM_DISCOVERY_STOP_LABEL:
- raise BookGateError("Entry did not stop at the configured booking form")
- else:
- stage = "before_otp_send"
- _wait_preflight(plugin, binding, preparation.BookingPreflightStage.BEFORE_OTP_SEND)
- _budget(_counts(audit), otp=0, avanti=0, before_calendar=True)
- otp_guard = preparation.OneShotAction("Book OTP")
- stage = "otp_send"
- otp_packet = otp_guard.run(lambda: preparation.listen_once(
- binding.page, target=preparation.OTP_PATH, method="GET", timeout=30,
- action=lambda: _native_click(plugin, binding, "#otp-send"),
- ))
- _current_packet(otp_packet, binding)
- preparation.validate_otp_packet(otp_packet, service_id=route.service_id)
- del otp_packet
- _budget(_counts(audit), otp=1, avanti=0, before_calendar=True)
- print("ITA_BOOK_GATE_OTP_SENT requests=1", flush=True)
- stage = "manual_otp_input"
- otp = otp_reader()
- try:
- if not isinstance(otp, str) or re.fullmatch(r"[0-9]{4,12}", otp) is None:
- raise BookGateError("Manual OTP must contain 4-12 ASCII digits")
- binding.require_current(plugin, expected_path=debug_route.booking_path)
- preparation._enter_otp(plugin, otp)
- finally:
- del otp
- stage = "after_otp_send"
- _wait_preflight(plugin, binding, preparation.BookingPreflightStage.AFTER_OTP_SEND)
- _budget(_counts(audit), otp=1, avanti=0, before_calendar=True)
- stage = "avanti_transition"
- avanti_guard = preparation.OneShotAction("Book AVANTI")
- avanti_packet = None
- try:
- binding.page.set.auto_handle_alert(accept=True)
- avanti_packet = avanti_guard.run(lambda: preparation.listen_once(
- binding.page, target=debug_route.booking_path, method="POST", timeout=30,
- action=lambda: _native_click(plugin, binding, "#btnAvanti"),
- ))
- _current_packet(avanti_packet, binding)
- preparation._wait_for_calendar(binding.page)
- binding.require_current(plugin, expected_path=CALENDAR_PATH)
- transition = preparation.validate_avanti_packet(
- avanti_packet, booking_path=debug_route.booking_path, final_page_url=binding.page.url,
- )
- except Exception:
- preparation._print_avanti_failure_diagnostic(
- binding.page, avanti_packet, booking_path=debug_route.booking_path,
- )
- raise
- finally:
- binding.page.set.auto_handle_alert(on_off=False)
- avanti_packet = None
- stage = "calendar_preparation"
- try:
- guard_calendar(binding.page)
- preparation_counts = _counts(audit)
- _budget(preparation_counts, otp=1, avanti=1)
- binding.require_current(plugin, expected_path=CALENDAR_PATH)
- try:
- calendar_book.wait_for_calendar_service(
- binding.page,
- session_is_current=lambda: binding.require_current(
- plugin, expected_path=CALENDAR_PATH,
- ) is None,
- timeout=CALENDAR_READY_TIMEOUT_SECONDS,
- )
- except calendar_book.CalendarServiceNotReadyError:
- raise BizLogicError("Italy Book Calendar service did not initialize before timeout") from None
- except BookGateError:
- raise
- except Exception:
- raise BizLogicError("Italy Book preparation did not identify the current Calendar service") from None
- plugin._record_calendar_book_prepared_route(route)
- preparation_counts = _counts(audit)
- _budget(preparation_counts, otp=1, avanti=1)
- except Exception:
- _print_calendar_preparation_diagnostic(binding.page)
- raise
- print(f"ITA_BOOK_GATE_CALENDAR_READY transition={transition} final_requests=0", flush=True)
- stage = "production_book"
- calendar_calls += 1
- result = _require_stop_result(plugin.book(trigger, user_inputs=inputs))
- stage = "selection_readback"
- selection = _selection_readback(plugin, binding, inputs, result)
- book_counts = _counts(audit)
- _budget(book_counts, otp=1, avanti=1)
- if book_counts["availabilityRequests"] <= preparation_counts["availabilityRequests"]:
- raise BookGateError("Book did not observe fresh Calendar availability requests")
- print("ITA_BOOK_GATE_SELECTION=" + json.dumps(selection, sort_keys=True), flush=True)
- if verify_receipts and selection["selectionVerified"]:
- stage = "receipt_baseline"
- receipt_baseline = _verify_receipt_baseline(plugin, route)
- if receipt_baseline["recordCount"] != before.reservations:
- raise BookGateError("Receipt baseline count differs from the pre-run inventory")
- binding.require_current(plugin, expected_path=CALENDAR_PATH)
- print("ITA_BOOK_GATE_RECEIPT_BASELINE=" + json.dumps(receipt_baseline, sort_keys=True), flush=True)
- outcome = "pre_final" if selection["selectionVerified"] else "no_candidate_in_scan_range"
- exit_code = 0 if selection["selectionVerified"] else 2
- if submit_once and selection["selectionVerified"]:
- stage = "final_evidence"
- binding.require_current(plugin, expected_path=CALENDAR_PATH)
- _budget(_counts(audit), otp=1, avanti=1)
- final_run = final_evidence.FinalEvidenceRun(
- plugin, route, observe_tab=_receipt_observer([]),
- verify_submission=lambda: _single_submission_verified(audit, book_counts),
- )
- final_run.execute(confirm=final_confirm)
- outcome = final_run.report["outcome"]
- exit_code = 4 if final_run.possibly_submitted else 2
- except (KeyboardInterrupt, EOFError):
- print(f"ITA_BOOK_GATE_CANCELLED stage={stage} retries=0", flush=True)
- outcome, exit_code = "cancelled", 130
- except Exception as exc:
- if stage == "production_book" and binding is not None:
- _print_production_book_diagnostic(binding.page)
- _failure(stage, exc)
- exit_code = 1
- finally:
- if final_run is not None and final_run.possibly_submitted:
- # Never report an interrupted/lost acknowledgement as safely retryable.
- outcome = final_run.report["outcome"]
- exit_code = 0 if final_run.report["bookingConfirmed"] is True else 4
- print("ITA_BOOK_GATE_FINAL_EVIDENCE=" + json.dumps(final_run.report, sort_keys=True), flush=True)
- try:
- final_evidence.wait_for_receipt_review(reader=review_reader)
- except (KeyboardInterrupt, EOFError):
- print("ITA_FINAL_REVIEW_INTERRUPTED do_not_retry=true", flush=True)
- except Exception:
- print("ITA_FINAL_REVIEW_UNAVAILABLE do_not_retry=true", flush=True)
- # Best-effort read-only reconciliation, including failures after a write.
- # No OTP, form action, or Calendar retry is performed during cleanup.
- if binding is not None:
- try:
- binding.require_current(plugin)
- # NativeFinalSubmitter re-guards its button. The pre-final guard
- # asserts ZERO historical final requests, so it must not run
- # after an authorized submission; the final audit checks <=1.
- if (same_origin_path(binding.page.url)[0] == CALENDAR_PATH and
- not (final_run is not None and final_run.possibly_submitted)):
- guard_calendar(binding.page)
- if before is not None:
- after = preparation.read_reservation_snapshot(binding.page)
- binding.require_current(plugin)
- print(f"ITA_BOOK_GATE_RESERVATION_AFTER reservations={after.reservations} waitlist={after.waitlist}", flush=True)
- if before != after and not (final_run is not None and final_run.possibly_submitted):
- raise BookGateError("Reservation or waitlist counts changed; do not retry")
- except Exception as exc:
- _failure("read_only_reconciliation", exc)
- if exit_code in (0, 2):
- exit_code = 1
- if audit is not None:
- try:
- observed = _counts(audit)
- final_limit = 1 if final_run is not None and final_run.possibly_submitted else 0
- if (observed["finalRequests"] > final_limit or observed["otpRequests"] > 1
- or observed["avantiPosts"] > 1):
- raise BookGateError("Final audit exceeded the one-shot side-effect budget")
- if final_run is not None and final_run.report["bookingConfirmed"] is True:
- if (observed["finalRequests"] != 1 or before is None or after is None or
- after.reservations != before.reservations + 1 or after.waitlist != before.waitlist):
- raise BookGateError("Confirmed booking did not retain its final audit evidence")
- if book_counts is not None and any(observed[k] != book_counts[k] for k in _COUNT_KEYS
- if k != "finalRequests" or final_limit == 0):
- raise BookGateError("Business requests changed after the Book readback")
- audit_verified = True
- except Exception as exc:
- _failure("final_request_audit", exc)
- if exit_code in (0, 2):
- exit_code = 1
- cleanup_failed = False
- for name, action in (
- ("listener", (lambda: _stop_listener_if_active(binding.page)) if binding is not None else None),
- ("audit", audit.stop if audit is not None else None),
- ("browser", plugin.cleanup if plugin is not None else None),
- ):
- if action is not None:
- try:
- action()
- except Exception as exc:
- cleanup_failed = True
- _failure(f"cleanup_{name}", exc)
- if cleanup_failed:
- exit_code = 3
- elif plugin is not None:
- print("ITA_BOOK_GATE_CLEANUP_OK", flush=True)
- report = {
- "contract": BOOK_GATE_CONTRACT, "outcome": outcome, "passed": exit_code == 0,
- "receiptBaseline": receipt_baseline,
- "finalEvidence": final_run.report if final_run is not None else None,
- "requestAuditVerified": audit_verified,
- "exitCode": exit_code, "entryBookCalls": entry_calls, "calendarBookCalls": calendar_calls,
- "requests": observed,
- "bookRequestDelta": (
- {key: book_counts[key] - preparation_counts[key] for key in _COUNT_KEYS}
- if book_counts is not None and preparation_counts is not None else None
- ),
- "reservationCountBefore": before.reservations if before is not None else None,
- "reservationCountAfter": after.reservations if after is not None else None,
- "waitlistCountBefore": before.waitlist if before is not None else None,
- "waitlistCountAfter": after.waitlist if after is not None else None,
- **selection,
- }
- if final_run is not None:
- report["bookResultSuccess"] = (exit_code == 0 and final_run.result is not None and
- final_run.result.success is True)
- print("ITA_BOOK_GATE_RESULT=" + json.dumps(report, sort_keys=True), flush=True)
- return exit_code
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- mode = parser.add_mutually_exclusive_group()
- mode.add_argument("--preflight", action="store_true", help="Local config check only (default).")
- mode.add_argument("--run", action="store_true", help="Allow one OTP, one AVANTI and pre-final selection; never final booking.")
- parser.add_argument(
- "--use-local-query-account", action="store_true",
- help="Use saved local Query credentials for this Book run, in a separate temporary browser.",
- )
- parser.add_argument("--expected-start-date", help="Inclusive applicant date preference, YYYY-MM-DD.")
- parser.add_argument("--expected-end-date", help="Inclusive applicant date preference, YYYY-MM-DD.")
- parser.add_argument("--verify-receipts", action="store_true", help="After selection, verify receipts in an owned background tab; never final booking.")
- parser.add_argument("--submit-once", action="store_true",
- help="With --run --verify-receipts: confirm a REAL appointment once, then inspect receipts. Exit 4 means do NOT retry.")
- args = parser.parse_args(argv)
- preferences = {key: value for key in ("expected_start_date", "expected_end_date")
- if (value := getattr(args, key)) is not None}
- return run_book_gate(
- os.environ, execute=args.run, user_inputs=preferences,
- use_local_query_account=args.use_local_query_account,
- verify_receipts=args.verify_receipts,
- submit_once=args.submit_once,
- )
- if __name__ == "__main__":
- raise SystemExit(main())
|