ita_final_evidence.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """Opt-in local final discovery. Never enables the production Book switch.
  2. Reuses the final core, native website click and bound receipt reader. A private,
  3. exclusive file prevents a second attempt in this checkout even after a crash.
  4. It is deliberately never removed automatically. This is NOT a distributed
  5. production fence, nor proof that an unknown receipt is an active appointment.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import os
  10. from pathlib import Path
  11. from plugins.ita_booking_final import (
  12. FinalBookingAttempt, FinalBookingError, FinalOutcomeUnknown, NativeFinalSubmitter,
  13. ReservationState, SubmissionSignal, VerifiedSubmission,
  14. )
  15. from plugins.ita_calendar_book import verify_precommit_selection
  16. from plugins.ita_final_read_port import FinalReceiptReadPort, _cancelled_record
  17. from tools.ita_local_handoff import ITA_LOCAL_HANDOFF_ROOT, _ensure_private_directory
  18. FINAL_CLAIM = ITA_LOCAL_HANDOFF_ROOT / "final-evidence-once.claim"
  19. def require_unused_claim(path: Path = FINAL_CLAIM) -> None:
  20. # Includes dangling symlinks. No file/directory creation during preflight.
  21. if path.exists() or path.is_symlink():
  22. raise FinalBookingError("Local final attempt is already fenced; reconcile before any new attempt")
  23. def claim_once(path: Path = FINAL_CLAIM) -> None:
  24. """O_EXCL before dispatch; even partial/empty files remain blocking."""
  25. parent = _ensure_private_directory(path.parent)
  26. if parent != path.parent.resolve():
  27. raise FinalBookingError("Local final fence directory changed")
  28. descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
  29. with os.fdopen(descriptor, "wb") as stream:
  30. stream.write(b'{"schema":1,"state":"possibly_submitted","automaticRetry":false}\n')
  31. stream.flush()
  32. os.fsync(stream.fileno())
  33. directory = os.open(parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
  34. try:
  35. os.fsync(directory)
  36. finally:
  37. os.close(directory)
  38. class FinalEvidenceRun:
  39. """One local diagnostic, using the original Book session and selection."""
  40. def __init__(self, plugin, route, *, observe_tab=None, claim_path=FINAL_CLAIM, verify_submission=None):
  41. self.plugin = plugin
  42. self.port = FinalReceiptReadPort(plugin, route, observe_tab=observe_tab)
  43. self.claim_path = claim_path
  44. self.possibly_submitted = False
  45. self.signal = SubmissionSignal.UNKNOWN
  46. self._used = False
  47. self.before = None
  48. self.result = None
  49. self._verify_submission = verify_submission
  50. self.report = {"attempted": False, "automaticRetry": False, "bookingConfirmed": False,
  51. "receiptEvidence": None, "outcome": "not_submitted"}
  52. def _current_selection(self):
  53. if not self.port.session_is_current():
  54. raise FinalBookingError("Final evidence Session changed")
  55. verify_precommit_selection(self.plugin.page, runtime_service=self.port.target.runtime_service,
  56. approval=self.port.target.approval)
  57. def execute(self, *, confirm=input) -> dict:
  58. if self._used:
  59. raise FinalBookingError("Local final evidence run is already consumed")
  60. self._used = True
  61. require_unused_claim(self.claim_path)
  62. self._current_selection()
  63. slot = self.port.target.approval.candidate
  64. phrase = f"BOOK {slot.day.isoformat()} {slot.time_label}"
  65. print("ITA_FINAL_CONFIRM_TARGET=" + json.dumps({
  66. "routingKey": self.port.target.routing_key, "serviceId": self.port.target.service_id,
  67. "date": slot.day.isoformat(), "timeRange": slot.time_label,
  68. "remainingAtSelection": slot.slots_free,
  69. }, sort_keys=True), flush=True)
  70. answer = confirm(
  71. "This creates a REAL appointment in the current applicant account. "
  72. f"Type exactly '{phrase}' to submit ONCE; anything else cancels: "
  73. )
  74. if answer != phrase:
  75. self.report["outcome"] = "confirmation_declined"
  76. return self.report
  77. def read():
  78. snapshot = self.port()
  79. if not self.possibly_submitted:
  80. self.before = snapshot
  81. return snapshot
  82. def submit():
  83. self._current_selection()
  84. # Fail closed before native dispatch if exclusive creation/fsync fails.
  85. claim_once(self.claim_path)
  86. self.possibly_submitted = True
  87. self.report.update(attempted=True, outcome="unknown_do_not_retry")
  88. native = NativeFinalSubmitter(
  89. self.plugin.page, self.port.target, self.port.session_is_current,
  90. )
  91. self.signal = native()
  92. diagnostic = getattr(native, "diagnostic", None)
  93. if type(diagnostic) is dict and set(diagnostic) == {"requestMatched", "reason"}:
  94. self.report["submissionDiagnostic"] = diagnostic
  95. proof = getattr(native, "submitted_selection", None)
  96. if (isinstance(proof, VerifiedSubmission) and callable(self._verify_submission) and
  97. self._verify_submission() is True):
  98. self.port.record_submission(proof)
  99. return self.signal
  100. attempt = FinalBookingAttempt(self.port.target, read_reservations=read, submit_native=submit,
  101. session_is_current=self.port.session_is_current)
  102. try:
  103. self.result = attempt.execute(enabled=True)
  104. if self.result.success is True:
  105. self.report.update(bookingConfirmed=True, outcome="confirmed",
  106. confirmedDate=self.result.book_date, confirmedTime=self.result.book_time)
  107. elif self.result.success is False and self.possibly_submitted:
  108. self.report["outcome"] = "rejected_do_not_retry"
  109. except FinalOutcomeUnknown:
  110. if not self.possibly_submitted:
  111. raise FinalBookingError("Final evidence blocked before native dispatch") from None
  112. finally:
  113. self.report["submissionSignal"] = self.signal.value
  114. if self.possibly_submitted:
  115. self.report["receiptEvidence"] = self.collect_receipts()
  116. return self.report
  117. def collect_receipts(self) -> dict:
  118. """One read-only observation. No receipt/reference/PII payload persisted."""
  119. if not self.possibly_submitted or self.before is None:
  120. raise FinalBookingError("No local final attempt to observe")
  121. try:
  122. observed = self.port.observe_receipts()
  123. before = {r.reference: r for r in self.before.records}
  124. current = {row.reference: (row, detail) for row, detail in observed.records}
  125. unchanged = all(ref in current and _cancelled_record(*current[ref]) == old
  126. for ref, old in before.items())
  127. new = [(row, detail) for row, detail in observed.records if row.reference not in before]
  128. slot = self.port.target.approval.candidate
  129. # Observation alone never establishes attribution. Only mirror an
  130. # already verified final-core result when this fresh read agrees.
  131. confirmed = bool(
  132. self.result is not None and self.result.success is True and unchanged and len(new) == 1 and
  133. new[0][1].reference == self.result.urn and new[0][1].state is ReservationState.ACTIVE and
  134. new[0][1].status_code == "2" and new[0][1].booking_type == "Prenotazione Singola" and
  135. new[0][1].service_name == self.port.target.service_name and
  136. new[0][1].day.isoformat() == self.result.book_date and
  137. new[0][1].appointment_time == self.result.book_time
  138. )
  139. return {
  140. "readVerified": True, "historicalRecordsUnchanged": unchanged,
  141. "recordCount": len(current), "newRecordCount": len(new),
  142. "newRecordsTruncated": len(new) > 3, "bookingConfirmed": confirmed,
  143. "newRecords": [{
  144. "officeText": d.office, "serviceText": d.service_name,
  145. "bookingTypeText": d.booking_type, "date": d.day.isoformat(),
  146. "assignedTime": d.appointment_time, "statusText": d.status_text,
  147. "statusCode": d.status_code, "classifiedState": d.state.value,
  148. "dateMatchesSelection": d.day == slot.day,
  149. "assignedTimeWithinSelection": slot.time_label[:5] <= d.appointment_time <= slot.time_label[-5:],
  150. } for _, d in new[:3]],
  151. }
  152. except Exception:
  153. # Browser/DOM errors and page bodies never enter logs. The fence stays.
  154. return {"readVerified": False, "bookingConfirmed": False}
  155. def wait_for_receipt_review(*, reader=input) -> None:
  156. print("ITA_FINAL_REVIEW_REQUIRED: Do NOT rerun or submit again. The browser is kept open. "
  157. "Inspect Reservation / the new receipt only; do not cancel an appointment. "
  158. "Share the diagnostic and redact personal data from any screenshot.", flush=True)
  159. reader("After inspection, press Enter to close this temporary browser: ")