"""Read-port adapter shared by production Book and local final validation. Preserves the applicant Calendar in its original tab. Reads existing receipts in an owned background tab of the SAME browser/context. Baselines allow only empty or cancelled history. A new confirmed receipt may bind to a verified native POST; observed receipt fields remain distinct from submission evidence. """ from __future__ import annotations import hashlib import json import threading import time from dataclasses import dataclass, field from uuid import uuid4 from urllib.parse import parse_qsl from plugins.ita_booking_final import ( FinalBookingError, FinalTarget, ReservationRecord, ReservationSnapshot, ReservationState, VerifiedSubmission, ) from plugins.ita_calendar_query import CALENDAR_PATH, same_origin_path from plugins.ita_protocol import ItaCapability, ItaRouteConfig, PrecommitApproval from plugins.ita_reservation import read_reservation_detail, read_reservation_listing LIST_URL = "https://prenotami.esteri.it/Reservation" MAX_DETAIL_READS = 20 @dataclass(frozen=True, repr=False) class ReceiptObservation: """Bound display evidence only; UNKNOWN is never promoted to success.""" records: tuple = field(repr=False) # (verified list row, matching detail) def _require(condition, reason): if condition is not True: raise FinalBookingError(reason) def _cancelled_record(row, detail) -> ReservationRecord: _require(row.state is ReservationState.CANCELLED and detail.state is ReservationState.CANCELLED and detail.status_code == "3" and all(getattr(row, field) == getattr(detail, field) for field in ( "reference", "office", "service_name", "day", "appointment_time", "status_text")), "Italy cancelled receipt is not verified") # Equality of fingerprints preserves changes to fields absent from the final # model (office, displayed service, booking type). It is NOT identity proof. facts = [detail.reference, row.detail_url, detail.office, detail.service_name, detail.booking_type, detail.day.isoformat(), detail.appointment_time, detail.status_text, detail.status_code] digest = hashlib.sha256(json.dumps(facts, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest() return ReservationRecord(detail.reference, None, detail.day, None, ReservationState.CANCELLED, appointment_time=detail.appointment_time, receipt_fingerprint=digest) def _confirmed_record(row, detail, submission: VerifiedSubmission) -> ReservationRecord: target, slot = submission.target, submission.target.approval.candidate _require(row.state is ReservationState.ACTIVE and detail.state is ReservationState.ACTIVE and detail.status_code == "2" and detail.booking_type == "Prenotazione Singola" and isinstance(target.service_name, str) and detail.service_name == target.service_name and detail.day == slot.day and slot.time_label[:5] <= detail.appointment_time <= slot.time_label[-5:] and all(getattr(row, key) == getattr(detail, key) for key in ( "reference", "office", "service_name", "day", "appointment_time", "status_text")), "Italy confirmed receipt does not match the submitted selection") facts = [detail.reference, row.detail_url, detail.office, detail.service_name, detail.booking_type, detail.day.isoformat(), detail.appointment_time, detail.status_text, detail.status_code] digest = hashlib.sha256(json.dumps(facts, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest() # The website receipt supplies neither service_id nor the selected interval. # Keep them None; the separate evidence explicitly identifies the native POST. return ReservationRecord(detail.reference, None, detail.day, None, ReservationState.ACTIVE, appointment_time=detail.appointment_time, receipt_fingerprint=digest, submission=submission) class FinalReceiptReadPort: """Capture an existing applicant Book precommit, then read fresh snapshots. Uses the plugin's established session/route checks, not a caller-supplied username assertion. Constructor does no navigation. Calling the port reads only; it never touches final buttons, rebuilds calendars or generates OTP. The owning Book workflow must serialize this with other browser work. """ def __init__(self, plugin, route: ItaRouteConfig, *, observe_tab=None): try: _require(isinstance(route, ItaRouteConfig) and route.capability is ItaCapability.SINGLE_SCHENGEN_TOURISM, "Italy final read route is invalid") self._plugin, self._route = plugin, route _require(observe_tab is None or callable(observe_tab), "Italy receipt observer is invalid") self._observe_tab = observe_tab self._page = plugin.page self._browser = self._page.browser self._browser_id = self._browser.id self._generation = plugin.session_create_time self._prepared = plugin._calendar_book_prepared_context self._approval = plugin.last_booking_precommit self._username = plugin.config.account.username.strip().casefold() _require(isinstance(self._approval, PrecommitApproval) and isinstance(self._prepared, tuple) and len(self._prepared) == 7 and isinstance(self._browser_id, str) and bool(self._browser_id) and same_origin_path(self._page.url)[0] == CALENDAR_PATH, "Italy final read requires the current Book precommit") _, calendar_url = same_origin_path(self._page.url) names = [value for key, value in parse_qsl(calendar_url.query, keep_blank_values=True) if key == "selectedService"] service_name = names[0] if len(names) == 1 and names[0] else None self._target = FinalTarget(self._username, uuid4().hex, self._page.tab_id, route.routing_key, str(route.service_id), self._prepared[5], self._approval, service_name=service_name) self._lock = threading.Lock() self._unusable = False self._baseline = None self._submission = None _require(self.session_is_current(), "Italy final read Session is not current") except Exception: raise FinalBookingError("Italy final read context could not be captured") from None @property def target(self): return self._target def session_is_current(self) -> bool: try: p = self._plugin same_origin_path(self._page.url) return (not self._unusable and p.page is self._page and self._page.browser is self._browser and self._browser.id == self._browser_id and self._page.tab_id == self._target.tab_id and p.session_create_time == self._generation and p.is_healthy is True and p.last_booking_precommit is self._approval and p._calendar_book_prepared_context == self._prepared and p.config.account.username.strip().casefold() == self._username and p._calendar_book_context_matches(self._route, self._username) is True) except Exception: return False def __call__(self) -> ReservationSnapshot: snapshot = self._read(observation=False) if self._submission is None: self._baseline = snapshot return snapshot def record_submission(self, submission: VerifiedSubmission) -> None: """Called only after a matched native POST and one-request audit.""" _require(self.session_is_current() and self._baseline is not None and self._submission is None and isinstance(submission, VerifiedSubmission) and submission.target == self.target and self.target.service_name is not None, "Italy submission binding is not current") self._submission = submission def observe_receipts(self) -> ReceiptObservation: """Read unknown status text for controlled discovery, NOT reconciliation.""" return self._read(observation=True) def _read(self, *, observation: bool): if not self._lock.acquire(blocking=False): raise FinalBookingError("Italy receipt read is already running") receipt_page = None finish_observation = None close_failed = False cleanup_interrupt = None try: _require(self.session_is_current(), "Italy final read Session changed") origin = (self._page.url, self._page.tab_id) candidate = self._browser.new_tab(background=True, new_context=False) # Only close a separately identified tab created by our own browser. # A broken factory returning the original/foreign page is not owned. _require(candidate is not self._page and candidate.browser is self._browser and isinstance(candidate.tab_id, str) and bool(candidate.tab_id) and candidate.tab_id != self._target.tab_id, "Italy receipt tab ownership is unverified") receipt_page, receipt_tab = candidate, candidate.tab_id if self._observe_tab is not None: finish_observation = self._observe_tab(receipt_page) _require(callable(finish_observation), "Italy receipt observer did not start") def context(): _require(self.session_is_current() and (self._page.url, self._page.tab_id) == origin and receipt_page.browser is self._browser and receipt_page.tab_id == receipt_tab, "Italy receipt read context changed") def navigate(url): context() _require(receipt_page.get(url, retry=0, timeout=30) is not False, "Italy receipt navigation failed") context() same_origin_path(receipt_page.url) _require(receipt_page.url == url, "Italy receipt navigation was redirected") navigate(LIST_URL) before = read_reservation_listing(receipt_page) context() _require(before.waitlist_count == 0 and len(before.rows) <= MAX_DETAIL_READS, "Italy receipt coverage exceeds supported verification") if not observation and self._submission is None: _require(all(row.state is ReservationState.CANCELLED for row in before.rows), "Italy live receipt attribution is not verified") records = [] for row in before.rows: # Only actual links accepted by the established listing parser. navigate(row.detail_url) detail = read_reservation_detail(receipt_page) context() _require(all(getattr(row, key) == getattr(detail, key) for key in ( "reference", "office", "service_name", "day", "appointment_time", "status_text")), "Italy observed receipt does not match its list row") if observation: records.append((row, detail)) elif row.state is ReservationState.CANCELLED: records.append(_cancelled_record(row, detail)) else: _require(self._submission is not None and self._baseline is not None and row.reference not in {r.reference for r in self._baseline.records}, "Italy receipt is not new to this submission") records.append(_confirmed_record(row, detail, self._submission)) navigate(LIST_URL) after = read_reservation_listing(receipt_page) context() _require({r.reference: r for r in before.rows} == {r.reference: r for r in after.rows} and before.waitlist_count == after.waitlist_count, "Italy receipt history changed during read") snapshot = (ReceiptObservation(tuple(records)) if observation else ReservationSnapshot(self._target.applicant, self._target.session_key, time.monotonic(), True, tuple(records))) except Exception: raise FinalBookingError("Italy bound receipt read could not be verified") from None finally: if callable(finish_observation): try: finish_observation() except BaseException as exc: self._unusable = True if isinstance(exc, Exception): close_failed = True else: cleanup_interrupt = exc if receipt_page is not None: try: receipt_page.close() except BaseException as exc: # Do not trust a later read after losing control of an owned tab. self._unusable = True if isinstance(exc, Exception): close_failed = True else: cleanup_interrupt = exc self._lock.release() if cleanup_interrupt is not None: raise cleanup_interrupt if close_failed: raise FinalBookingError("Italy owned receipt tab cleanup failed") from None _require(self.session_is_current() and (self._page.url, self._page.tab_id) == origin, "Italy final read context changed during cleanup") return snapshot