"""Opt-in local final discovery. Never enables the production Book switch. Reuses the final core, native website click and bound receipt reader. A private, exclusive file prevents a second attempt in this checkout even after a crash. It is deliberately never removed automatically. This is NOT a distributed production fence, nor proof that an unknown receipt is an active appointment. """ from __future__ import annotations import json import os from pathlib import Path from plugins.ita_booking_final import ( FinalBookingAttempt, FinalBookingError, FinalOutcomeUnknown, NativeFinalSubmitter, ReservationState, SubmissionSignal, VerifiedSubmission, ) from plugins.ita_calendar_book import verify_precommit_selection from plugins.ita_final_read_port import FinalReceiptReadPort, _cancelled_record from tools.ita_local_handoff import ITA_LOCAL_HANDOFF_ROOT, _ensure_private_directory FINAL_CLAIM = ITA_LOCAL_HANDOFF_ROOT / "final-evidence-once.claim" def require_unused_claim(path: Path = FINAL_CLAIM) -> None: # Includes dangling symlinks. No file/directory creation during preflight. if path.exists() or path.is_symlink(): raise FinalBookingError("Local final attempt is already fenced; reconcile before any new attempt") def claim_once(path: Path = FINAL_CLAIM) -> None: """O_EXCL before dispatch; even partial/empty files remain blocking.""" parent = _ensure_private_directory(path.parent) if parent != path.parent.resolve(): raise FinalBookingError("Local final fence directory changed") descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600) with os.fdopen(descriptor, "wb") as stream: stream.write(b'{"schema":1,"state":"possibly_submitted","automaticRetry":false}\n') stream.flush() os.fsync(stream.fileno()) directory = os.open(parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) try: os.fsync(directory) finally: os.close(directory) class FinalEvidenceRun: """One local diagnostic, using the original Book session and selection.""" def __init__(self, plugin, route, *, observe_tab=None, claim_path=FINAL_CLAIM, verify_submission=None): self.plugin = plugin self.port = FinalReceiptReadPort(plugin, route, observe_tab=observe_tab) self.claim_path = claim_path self.possibly_submitted = False self.signal = SubmissionSignal.UNKNOWN self._used = False self.before = None self.result = None self._verify_submission = verify_submission self.report = {"attempted": False, "automaticRetry": False, "bookingConfirmed": False, "receiptEvidence": None, "outcome": "not_submitted"} def _current_selection(self): if not self.port.session_is_current(): raise FinalBookingError("Final evidence Session changed") verify_precommit_selection(self.plugin.page, runtime_service=self.port.target.runtime_service, approval=self.port.target.approval) def execute(self, *, confirm=input) -> dict: if self._used: raise FinalBookingError("Local final evidence run is already consumed") self._used = True require_unused_claim(self.claim_path) self._current_selection() slot = self.port.target.approval.candidate phrase = f"BOOK {slot.day.isoformat()} {slot.time_label}" print("ITA_FINAL_CONFIRM_TARGET=" + json.dumps({ "routingKey": self.port.target.routing_key, "serviceId": self.port.target.service_id, "date": slot.day.isoformat(), "timeRange": slot.time_label, "remainingAtSelection": slot.slots_free, }, sort_keys=True), flush=True) answer = confirm( "This creates a REAL appointment in the current applicant account. " f"Type exactly '{phrase}' to submit ONCE; anything else cancels: " ) if answer != phrase: self.report["outcome"] = "confirmation_declined" return self.report def read(): snapshot = self.port() if not self.possibly_submitted: self.before = snapshot return snapshot def submit(): self._current_selection() # Fail closed before native dispatch if exclusive creation/fsync fails. claim_once(self.claim_path) self.possibly_submitted = True self.report.update(attempted=True, outcome="unknown_do_not_retry") native = NativeFinalSubmitter( self.plugin.page, self.port.target, self.port.session_is_current, ) self.signal = native() diagnostic = getattr(native, "diagnostic", None) if type(diagnostic) is dict and set(diagnostic) == {"requestMatched", "reason"}: self.report["submissionDiagnostic"] = diagnostic proof = getattr(native, "submitted_selection", None) if (isinstance(proof, VerifiedSubmission) and callable(self._verify_submission) and self._verify_submission() is True): self.port.record_submission(proof) return self.signal attempt = FinalBookingAttempt(self.port.target, read_reservations=read, submit_native=submit, session_is_current=self.port.session_is_current) try: self.result = attempt.execute(enabled=True) if self.result.success is True: self.report.update(bookingConfirmed=True, outcome="confirmed", confirmedDate=self.result.book_date, confirmedTime=self.result.book_time) elif self.result.success is False and self.possibly_submitted: self.report["outcome"] = "rejected_do_not_retry" except FinalOutcomeUnknown: if not self.possibly_submitted: raise FinalBookingError("Final evidence blocked before native dispatch") from None finally: self.report["submissionSignal"] = self.signal.value if self.possibly_submitted: self.report["receiptEvidence"] = self.collect_receipts() return self.report def collect_receipts(self) -> dict: """One read-only observation. No receipt/reference/PII payload persisted.""" if not self.possibly_submitted or self.before is None: raise FinalBookingError("No local final attempt to observe") try: observed = self.port.observe_receipts() before = {r.reference: r for r in self.before.records} current = {row.reference: (row, detail) for row, detail in observed.records} unchanged = all(ref in current and _cancelled_record(*current[ref]) == old for ref, old in before.items()) new = [(row, detail) for row, detail in observed.records if row.reference not in before] slot = self.port.target.approval.candidate # Observation alone never establishes attribution. Only mirror an # already verified final-core result when this fresh read agrees. confirmed = bool( self.result is not None and self.result.success is True and unchanged and len(new) == 1 and new[0][1].reference == self.result.urn and new[0][1].state is ReservationState.ACTIVE and new[0][1].status_code == "2" and new[0][1].booking_type == "Prenotazione Singola" and new[0][1].service_name == self.port.target.service_name and new[0][1].day.isoformat() == self.result.book_date and new[0][1].appointment_time == self.result.book_time ) return { "readVerified": True, "historicalRecordsUnchanged": unchanged, "recordCount": len(current), "newRecordCount": len(new), "newRecordsTruncated": len(new) > 3, "bookingConfirmed": confirmed, "newRecords": [{ "officeText": d.office, "serviceText": d.service_name, "bookingTypeText": d.booking_type, "date": d.day.isoformat(), "assignedTime": d.appointment_time, "statusText": d.status_text, "statusCode": d.status_code, "classifiedState": d.state.value, "dateMatchesSelection": d.day == slot.day, "assignedTimeWithinSelection": slot.time_label[:5] <= d.appointment_time <= slot.time_label[-5:], } for _, d in new[:3]], } except Exception: # Browser/DOM errors and page bodies never enter logs. The fence stays. return {"readVerified": False, "bookingConfirmed": False} def wait_for_receipt_review(*, reader=input) -> None: print("ITA_FINAL_REVIEW_REQUIRED: Do NOT rerun or submit again. The browser is kept open. " "Inspect Reservation / the new receipt only; do not cancel an appointment. " "Share the diagnostic and redact personal data from any screenshot.", flush=True) reader("After inspection, press Enter to close this temporary browser: ")