ita_calendar_book.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. """Book-side Calendar response binding and native slot selection.
  2. The caller owns login, route continuity, date preferences and fresh packet
  3. capture in the applicant's browser. This adapter neither fetches inventory nor
  4. accepts a Query snapshot. A returned approval is a pre-final checkpoint, never
  5. permission to submit or evidence of a completed booking.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import time
  10. from dataclasses import dataclass, field
  11. from datetime import date, datetime
  12. from typing import Callable, Mapping
  13. from plugins.ita_calendar_query import (
  14. CALENDAR_PATH,
  15. AVAILABILITY_PATH,
  16. DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
  17. CalendarGateError,
  18. CalendarProbeResult,
  19. click_next_month,
  20. guard_calendar,
  21. listen_once,
  22. month_text,
  23. next_month_value,
  24. parse_availability_packet,
  25. refresh_calendar,
  26. require_plain_nonnegative_int,
  27. same_origin_path,
  28. )
  29. from plugins.ita_protocol import (
  30. CalendarDay,
  31. DateSelectionState,
  32. ItaProtocolError,
  33. PrecommitApproval,
  34. SlotCandidate,
  35. SlotSelectionState,
  36. approve_precommit,
  37. available_calendar_days,
  38. available_slot_candidates,
  39. month_starts,
  40. parse_time_slots,
  41. )
  42. TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
  43. RUNTIME_SERVICE_SCRIPT = r"""
  44. /* coordinate:ita-book-runtime-service */
  45. const controls = Array.from(document.querySelectorAll('#idServizio'));
  46. return {
  47. path: window.location.pathname,
  48. count: controls.length,
  49. value: controls.length === 1 ? controls[0].value : null,
  50. };
  51. """
  52. SLOT_SELECTION_SCRIPT = r"""
  53. /* coordinate:ita-book-slot-selection */
  54. const [serviceId, day, dailyId, timeLabel, capacity, shouldClick] = arguments;
  55. const normalize = (text) => String(text || '').replace(/\s+/g, ' ').trim();
  56. const service = Array.from(document.querySelectorAll('#idServizio'));
  57. const runtimeMatches = window.location.origin === 'https://prenotami.esteri.it' &&
  58. window.location.pathname === '/BookingCalendar' &&
  59. service.length === 1 && service[0].value === serviceId;
  60. const finalButtons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
  61. const finalGuarded = finalButtons.length === 1 && finalButtons[0].disabled &&
  62. finalButtons[0].dataset.coordinateFinalGuard === 'enabled';
  63. const timeline = Array.from(document.querySelectorAll('.events a.selected'));
  64. const content = Array.from(document.querySelectorAll('.events-content li.selected'));
  65. const links = Array.from(document.querySelectorAll('.events a[data-date]'))
  66. .filter((element) => element.dataset.date === day);
  67. const link = links.length === 1 ? links[0] : null;
  68. const datesMatch = timeline.length === 1 && content.length === 1 &&
  69. timeline[0].dataset.date === day && content[0].dataset.date === day;
  70. const firstSelectedMatches = datesMatch && document.querySelector('.selected') === timeline[0];
  71. const disabled = (element) => !element || element.hasAttribute('disabled') ||
  72. element.getAttribute('aria-disabled') === 'true' ||
  73. element.classList.contains('disabled') ||
  74. element.classList.contains('input-async-disabilitato');
  75. const dayNegative = !link || link.classList.contains('notAvailableDay');
  76. const dayPositive = Boolean(link && link.classList.contains('input-async-abilitato'));
  77. const inputs = (slot) => slot ? Array.from(slot.querySelectorAll('input')) : [];
  78. const idMatches = (slot) => {
  79. const fields = inputs(slot);
  80. return fields.length === 1 && fields[0].type === 'hidden' &&
  81. fields[0].id === 'idHiddenFasciaServizio' && fields[0].value === dailyId;
  82. };
  83. const timeMatches = (slot) => {
  84. const spans = slot ? slot.querySelectorAll('span') : [];
  85. return spans.length === 2 && normalize(spans[0].textContent) === timeLabel;
  86. };
  87. const capacityMatches = (slot) => {
  88. const spans = slot ? slot.querySelectorAll('span') : [];
  89. return spans.length === 2 && normalize(spans[1].textContent) === `(${capacity})`;
  90. };
  91. const negative = (slot) => !slot || slot.classList.contains('notAvailableFascia');
  92. const redDot = (slot) => Boolean(slot && slot.querySelector('.dotRed'));
  93. const actionable = (element) => {
  94. if (!element || !element.isConnected || disabled(element)) return false;
  95. const style = window.getComputedStyle(element);
  96. if (style.display === 'none' || style.visibility === 'hidden' ||
  97. style.pointerEvents === 'none' || Number.parseFloat(style.opacity || '1') <= 0) return false;
  98. const rect = element.getBoundingClientRect();
  99. const left = Math.max(0, rect.left), right = Math.min(window.innerWidth, rect.right);
  100. const top = Math.max(0, rect.top), bottom = Math.min(window.innerHeight, rect.bottom);
  101. if (right <= left || bottom <= top) return false;
  102. const hit = document.elementFromPoint((left + right) / 2, (top + bottom) / 2);
  103. return Boolean(hit && (hit === element || element.contains(hit)));
  104. };
  105. const slots = content.length === 1 ? Array.from(content[0].querySelectorAll('.fascia')) : [];
  106. const matches = slots.filter(idMatches);
  107. const candidate = matches.length === 1 ? matches[0] : null;
  108. const candidateReady = Boolean(candidate && !negative(candidate) && !redDot(candidate) &&
  109. timeMatches(candidate) && capacityMatches(candidate) && actionable(candidate));
  110. let active = Array.from(document.querySelectorAll('.fascia.act'));
  111. const alreadyActive = active.length === 1 && active[0] === candidate;
  112. let clicked = false;
  113. if (shouldClick === true && runtimeMatches && finalGuarded && datesMatch &&
  114. firstSelectedMatches && links.length === 1 && !disabled(link) && !dayNegative &&
  115. dayPositive && candidateReady && !alreadyActive) {
  116. candidate.click();
  117. clicked = true;
  118. }
  119. active = Array.from(document.querySelectorAll('.fascia.act'));
  120. const selected = active.length === 1 ? active[0] : null;
  121. return {
  122. runtimeMatches, finalGuarded, firstSelectedMatches,
  123. timelineDays: timeline.map((element) => element.dataset.date || ''),
  124. contentDays: content.map((element) => element.dataset.date || ''),
  125. matchingDateCount: links.length,
  126. dayDisabled: disabled(link), dayNegative, dayPositive,
  127. candidateCount: matches.length, candidateReady, clicked,
  128. activeCount: active.length,
  129. activeIsCandidate: Boolean(selected && selected === candidate),
  130. activeUnavailable: negative(selected), activeRedDot: redDot(selected),
  131. activeInputCount: inputs(selected).length,
  132. activeIdMatches: idMatches(selected),
  133. activeDayMatches: Boolean(selected && datesMatch && content[0].contains(selected)),
  134. activeTimeMatches: timeMatches(selected),
  135. activeCapacityMatches: capacityMatches(selected),
  136. };
  137. """
  138. class CalendarBookError(CalendarGateError):
  139. """A safe stage error; never includes response bodies or runtime IDs."""
  140. def __init__(self, message: str, *, http_status: int | None = None):
  141. super().__init__(message)
  142. self.http_status = http_status
  143. class CalendarServiceNotReadyError(CalendarBookError):
  144. """The service control stayed empty during a known initialization boundary."""
  145. _BOOL_FIELDS = {
  146. "runtimeMatches", "finalGuarded", "firstSelectedMatches", "dayDisabled",
  147. "dayNegative", "dayPositive", "candidateReady", "clicked",
  148. "activeIsCandidate", "activeUnavailable", "activeRedDot", "activeIdMatches",
  149. "activeDayMatches", "activeTimeMatches", "activeCapacityMatches",
  150. }
  151. _COUNT_FIELDS = {"matchingDateCount", "candidateCount", "activeCount", "activeInputCount"}
  152. _DATE_FIELDS = {"timelineDays", "contentDays"}
  153. def _runtime_id(value: object) -> str:
  154. if type(value) is int and value > 0:
  155. return str(value)
  156. if isinstance(value, str) and value and value == value.strip() and len(value) <= 128:
  157. return value
  158. raise CalendarBookError("Book runtime service identifier was invalid")
  159. def _read_calendar_service_value(page: object) -> str:
  160. path, _ = same_origin_path(page.url)
  161. if path != CALENDAR_PATH:
  162. raise CalendarBookError("Book selection requires the current Calendar page")
  163. raw = page.run_js(RUNTIME_SERVICE_SCRIPT)
  164. if not isinstance(raw, dict) or set(raw) != {"path", "count", "value"}:
  165. raise CalendarBookError("Book Calendar runtime context changed")
  166. if raw["path"] != CALENDAR_PATH or type(raw["count"]) is not int or raw["count"] != 1:
  167. raise CalendarBookError("Book Calendar requires one runtime service control")
  168. if not isinstance(raw["value"], str):
  169. raise CalendarBookError("Book Calendar runtime service control has no value")
  170. return raw["value"]
  171. def read_calendar_service(page: object) -> str:
  172. """Strict read for stable phases; empty values are never a valid identity."""
  173. return _runtime_id(_read_calendar_service_value(page))
  174. def wait_for_calendar_service(
  175. page: object, *, session_is_current: Callable[[], bool],
  176. expected_service: str | None = None, timeout: float = 5,
  177. ) -> str:
  178. """Await the site's field assignment without requesting or retrying anything.
  179. Call only after AVANTI or native Calendar loading. Stable-phase checks stay
  180. strict: only an exactly empty string is pending, not malformed identities,
  181. missing/duplicate controls, another service, or a changed applicant/tab.
  182. The deadline bounds polling; browser transport failures propagate normally.
  183. """
  184. if type(timeout) not in (int, float) or not 0 <= timeout < float("inf"):
  185. raise CalendarBookError("Book Calendar readiness timeout must be finite and nonnegative")
  186. if not callable(session_is_current):
  187. raise CalendarBookError("Book Calendar readiness requires a Session check")
  188. if expected_service is not None:
  189. expected_service = _runtime_id(expected_service)
  190. tab_id = getattr(page, "tab_id", None)
  191. if not isinstance(tab_id, str) or not tab_id:
  192. raise CalendarBookError("Book Calendar tab identity was unavailable")
  193. deadline = time.monotonic() + timeout
  194. def require_session() -> None:
  195. if session_is_current() is not True or getattr(page, "tab_id", None) != tab_id:
  196. raise CalendarBookError("Book applicant, route or browser Session changed")
  197. if same_origin_path(page.url)[0] != CALENDAR_PATH:
  198. raise CalendarBookError("Book readiness left the current Calendar page")
  199. while True:
  200. require_session()
  201. guard_calendar(page)
  202. value = _read_calendar_service_value(page)
  203. require_session()
  204. if value != "":
  205. service = _runtime_id(value)
  206. if expected_service is not None and service != expected_service:
  207. raise CalendarBookError("Book Calendar runtime service changed")
  208. return service
  209. remaining = deadline - time.monotonic()
  210. if remaining <= 0:
  211. raise CalendarServiceNotReadyError("Book Calendar service did not initialize before timeout")
  212. time.sleep(min(0.1, remaining))
  213. def _request_day(value: object) -> date:
  214. if isinstance(value, str):
  215. for date_format in ("%Y-%m-%d", "%d/%m/%Y"):
  216. try:
  217. return datetime.strptime(value, date_format).date()
  218. except ValueError:
  219. pass
  220. raise CalendarBookError("Book TimeSlots request date format changed")
  221. def parse_book_time_slots(
  222. packet: object, *, target_day: date, runtime_service_id: str,
  223. ) -> tuple[SlotCandidate, ...]:
  224. """Bind TimeSlots metadata to the selected day and current DOM service."""
  225. try:
  226. path, _ = same_origin_path(packet.url)
  227. if str(packet.method).upper() != "POST" or path != TIME_SLOTS_PATH:
  228. raise CalendarBookError("Book TimeSlots request method or path changed")
  229. if type(packet.response.status) is not int or packet.response.status != 200:
  230. raise CalendarBookError(
  231. "Book TimeSlots response status was not 200",
  232. http_status=packet.response.status if type(packet.response.status) is int else None,
  233. )
  234. body = packet.request.postData
  235. if isinstance(body, str):
  236. body = json.loads(body)
  237. if not isinstance(body, dict) or set(body) != {"selectedDay", "idService"}:
  238. raise CalendarBookError("Book TimeSlots request fields changed")
  239. if _runtime_id(body["idService"]) != runtime_service_id:
  240. raise CalendarBookError("Book TimeSlots request does not match the current service")
  241. if _request_day(body["selectedDay"]) != target_day:
  242. raise CalendarBookError("Book TimeSlots request does not match the target day")
  243. candidates = parse_time_slots(packet.response.raw_body)
  244. if any(item.day != target_day for item in candidates):
  245. raise CalendarBookError("Book TimeSlots response contains another day")
  246. return candidates
  247. except CalendarBookError:
  248. raise
  249. except ItaProtocolError as exc:
  250. raise CalendarBookError(f"Book TimeSlots protocol rejected ({exc.code})") from None
  251. except Exception:
  252. raise CalendarBookError("Book TimeSlots packet could not be validated") from None
  253. def _snapshot(page: object, service: str, target: date, candidate: SlotCandidate, *, click: bool) -> dict:
  254. raw = page.run_js(
  255. SLOT_SELECTION_SCRIPT, service, target.isoformat(), candidate.daily_calendar_id,
  256. candidate.time_label, candidate.slots_free, click,
  257. )
  258. if not isinstance(raw, dict) or set(raw) != _BOOL_FIELDS | _COUNT_FIELDS | _DATE_FIELDS:
  259. raise CalendarBookError("Book slot snapshot fields changed")
  260. if any(type(raw[key]) is not bool for key in _BOOL_FIELDS):
  261. raise CalendarBookError("Book slot snapshot boolean types changed")
  262. for key in _COUNT_FIELDS:
  263. require_plain_nonnegative_int(raw[key], key)
  264. for key in _DATE_FIELDS:
  265. if not isinstance(raw[key], list) or any(not isinstance(item, str) for item in raw[key]):
  266. raise CalendarBookError("Book selected-date snapshot types changed")
  267. return raw
  268. def _require_ready(raw: dict, target_day: date) -> None:
  269. positive = ("runtimeMatches", "finalGuarded", "firstSelectedMatches", "dayPositive", "candidateReady")
  270. if any(raw[key] is not True for key in positive):
  271. raise CalendarBookError("Book candidate is not safely selectable")
  272. if raw["dayDisabled"] or raw["dayNegative"]:
  273. raise CalendarBookError("Book selected day is marked unavailable")
  274. if raw["matchingDateCount"] != 1 or raw["candidateCount"] != 1:
  275. raise CalendarBookError("Book date or slot is not unique")
  276. expected = [target_day.isoformat()]
  277. if raw["timelineDays"] != expected or raw["contentDays"] != expected:
  278. raise CalendarBookError("Book timeline and content dates do not match the target")
  279. def _approve_selection_snapshot(
  280. calendar_day: CalendarDay, candidate: SlotCandidate, raw: dict,
  281. ) -> PrecommitApproval:
  282. _require_ready(raw, candidate.day)
  283. if raw["clicked"]:
  284. raise CalendarBookError("Book readback unexpectedly clicked")
  285. return approve_precommit(
  286. calendar_day, candidate,
  287. DateSelectionState(
  288. planned_day=candidate.day, matching_availability_count=1,
  289. timeline_selected_days=tuple(date.fromisoformat(item) for item in raw["timelineDays"]),
  290. content_selected_days=tuple(date.fromisoformat(item) for item in raw["contentDays"]),
  291. day_disabled=raw["dayDisabled"], day_not_available=raw["dayNegative"],
  292. day_has_positive_state=raw["dayPositive"],
  293. ),
  294. SlotSelectionState(
  295. active_slot_count=raw["activeCount"], active_is_candidate=raw["activeIsCandidate"],
  296. active_has_unavailable_class=raw["activeUnavailable"], active_has_red_dot=raw["activeRedDot"],
  297. active_hidden_input_count=raw["activeInputCount"],
  298. active_daily_id_matches_candidate=raw["activeIdMatches"],
  299. active_day_matches_candidate=raw["activeDayMatches"],
  300. active_time_matches_candidate=raw["activeTimeMatches"],
  301. active_capacity_matches_candidate=raw["activeCapacityMatches"],
  302. ),
  303. )
  304. def verify_precommit_selection(
  305. page: object, *, runtime_service: str, approval: PrecommitApproval,
  306. ) -> PrecommitApproval:
  307. """Read the current selected slot; never select, refresh, or submit anything.
  308. The caller still owns applicant/session binding and freshness of the Book
  309. inventory. This is a consistency check, not a reservation or inventory lock.
  310. """
  311. if not isinstance(approval, PrecommitApproval):
  312. raise CalendarBookError("Book selection requires a precommit approval")
  313. try:
  314. if read_calendar_service(page) != runtime_service:
  315. raise CalendarBookError("Book Calendar runtime service changed")
  316. raw = _snapshot(page, runtime_service, approval.candidate.day, approval.candidate, click=False)
  317. return _approve_selection_snapshot(approval.calendar_day, approval.candidate, raw)
  318. except CalendarBookError:
  319. raise
  320. except Exception:
  321. raise CalendarBookError("Book precommit readback failed") from None
  322. def select_slot_before_final(
  323. page: object, *, target_day: date, availability_packet: object, time_slots_packet: object,
  324. ) -> PrecommitApproval | None:
  325. """Select one positive slot from caller-captured Book packets; never submit.
  326. Both packets must be fresh captures from this page. Their content alone
  327. cannot prove capture time, applicant identity or route continuity. The
  328. orchestrator must establish these preconditions before calling this method.
  329. """
  330. if type(target_day) is not date:
  331. raise CalendarBookError("Book target day must be a date")
  332. try:
  333. service = read_calendar_service(page)
  334. guard_calendar(page)
  335. try:
  336. probe = parse_availability_packet(availability_packet)
  337. if probe.selected_month != (target_day.year, target_day.month):
  338. raise CalendarBookError("Book Availability belongs to another month")
  339. slots = parse_book_time_slots(
  340. time_slots_packet, target_day=target_day, runtime_service_id=service,
  341. )
  342. days = [item for item in probe.days if item.day == target_day]
  343. candidates = available_slot_candidates(slots, start_day=target_day, end_day=target_day)
  344. if not days or not days[0].is_available:
  345. if candidates:
  346. raise CalendarBookError("Book Availability and TimeSlots disagree")
  347. return None
  348. if not candidates:
  349. return None
  350. candidate = candidates[0]
  351. before = _snapshot(page, service, target_day, candidate, click=False)
  352. _require_ready(before, target_day)
  353. if before["clicked"]:
  354. raise CalendarBookError("Book read-only snapshot unexpectedly clicked")
  355. if not (before["activeCount"] == 1 and before["activeIsCandidate"]):
  356. acted = _snapshot(page, service, target_day, candidate, click=True)
  357. _require_ready(acted, target_day)
  358. if not acted["clicked"]:
  359. raise CalendarBookError("Book slot click was not acknowledged")
  360. after = _snapshot(page, service, target_day, candidate, click=False)
  361. return _approve_selection_snapshot(days[0], candidate, after)
  362. finally:
  363. guard_calendar(page)
  364. except CalendarBookError:
  365. raise
  366. except ItaProtocolError as exc:
  367. raise CalendarBookError(f"Book precommit rejected ({exc.code})") from None
  368. except Exception:
  369. raise CalendarBookError("Book Calendar selection or final guard failed") from None
  370. DATE_SELECTION_SCRIPT = r"""
  371. /* coordinate:ita-book-date-selection */
  372. const [serviceId, day, shouldClick] = arguments;
  373. const services = Array.from(document.querySelectorAll('#idServizio'));
  374. const runtimeMatches = window.location.origin === 'https://prenotami.esteri.it' &&
  375. window.location.pathname === '/BookingCalendar' && services.length === 1 &&
  376. services[0].value === serviceId;
  377. const buttons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
  378. const finalGuarded = buttons.length === 1 && buttons[0].disabled === true &&
  379. buttons[0].dataset.coordinateFinalGuard === 'enabled';
  380. const candidates = Array.from(document.querySelectorAll('.events a[data-date]'))
  381. .filter((link) => link.dataset.date === day);
  382. const link = candidates.length === 1 ? candidates[0] : null;
  383. const enabled = (element) => {
  384. if (!element || !element.isConnected || element.hasAttribute('disabled') ||
  385. element.getAttribute('aria-disabled') === 'true' ||
  386. element.classList.contains('disabled') || element.classList.contains('notAvailableDay') ||
  387. element.classList.contains('input-async-disabilitato') ||
  388. !element.classList.contains('input-async-abilitato')) return false;
  389. const style = window.getComputedStyle(element);
  390. // Calendar timeline links can have zero layout size while logically enabled.
  391. // The site's initialization uses HTMLElement.click(), as we do here, rather
  392. // than a pointer hit. Keep disabled/style checks and response/date readback;
  393. // do not require a clickable rectangle for this native date action.
  394. return style.display !== 'none' && style.visibility !== 'hidden' &&
  395. style.pointerEvents !== 'none' && Number.parseFloat(style.opacity || '1') > 0;
  396. };
  397. const timeline = Array.from(document.querySelectorAll('.events a.selected'));
  398. const content = Array.from(document.querySelectorAll('.events-content li.selected'));
  399. const selectedMatches = timeline.length === 1 && content.length === 1 &&
  400. timeline[0].dataset.date === day && content[0].dataset.date === day &&
  401. document.querySelector('.selected') === timeline[0];
  402. const candidateEnabled = enabled(link);
  403. let clicked = false;
  404. if (shouldClick === true && runtimeMatches && finalGuarded && candidateEnabled && !selectedMatches) {
  405. link.click();
  406. clicked = true;
  407. }
  408. return {runtimeMatches, finalGuarded, candidateCount: candidates.length,
  409. candidateEnabled, selectedMatches, clicked};
  410. """
  411. @dataclass(frozen=True, slots=True)
  412. class _CapturedMonth:
  413. probe: CalendarProbeResult
  414. availability_packet: object = field(repr=False)
  415. availability_service: str = field(repr=False)
  416. automatic_day: date | None = None
  417. automatic_slots_packet: object | None = field(default=None, repr=False)
  418. def book_date_preferences(user_inputs: Mapping[str, object]) -> tuple[date, date]:
  419. """Use the VFS preference keys and inclusive bounds without mutating inputs."""
  420. if not isinstance(user_inputs, Mapping):
  421. raise CalendarBookError("Book user inputs must be a mapping")
  422. dates = []
  423. for key, default in (("expected_start_date", "2000-01-01"),
  424. ("expected_end_date", "2100-01-01")):
  425. value = user_inputs.get(key, default)
  426. try:
  427. parsed = date.fromisoformat(value) if isinstance(value, str) else None
  428. except ValueError:
  429. parsed = None
  430. if parsed is None or parsed.isoformat() != value:
  431. raise CalendarBookError(f"Book {key} must use YYYY-MM-DD")
  432. dates.append(parsed)
  433. if dates[0] > dates[1]:
  434. raise CalendarBookError("Book date preference start exceeds end")
  435. return dates[0], dates[1]
  436. def _require_context(page: object, service: str, session_is_current: Callable[[], bool]) -> None:
  437. if session_is_current() is not True:
  438. raise CalendarBookError("Book applicant, route or browser Session changed")
  439. if read_calendar_service(page) != service:
  440. raise CalendarBookError("Book Calendar runtime service changed")
  441. guard_calendar(page)
  442. def _require_packet_tab(page: object, packet: object) -> None:
  443. tab = getattr(page, "tab_id", None)
  444. if not isinstance(tab, str) or not tab or getattr(packet, "tab_id", None) != tab:
  445. raise CalendarBookError("Book response did not belong to the current browser tab")
  446. if getattr(packet, "is_failed", False) is not False:
  447. raise CalendarBookError("Book browser request failed")
  448. def _post_body(packet: object) -> dict:
  449. body = packet.request.postData
  450. if isinstance(body, str):
  451. body = json.loads(body)
  452. if not isinstance(body, dict):
  453. raise CalendarBookError("Book request body was not an object")
  454. return body
  455. def _date_snapshot(page: object, service: str, day: date, *, click: bool = False) -> dict:
  456. raw = page.run_js(DATE_SELECTION_SCRIPT, service, day.isoformat(), click)
  457. boolean_keys = {"runtimeMatches", "finalGuarded", "candidateEnabled", "selectedMatches", "clicked"}
  458. if not isinstance(raw, dict) or set(raw) != boolean_keys | {"candidateCount"}:
  459. raise CalendarBookError("Book date control structure changed")
  460. if any(type(raw[key]) is not bool for key in boolean_keys):
  461. raise CalendarBookError("Book date control types changed")
  462. require_plain_nonnegative_int(raw["candidateCount"], "candidateCount")
  463. if not raw["runtimeMatches"] or not raw["finalGuarded"] or raw["candidateCount"] > 1:
  464. raise CalendarBookError("Book date control context was not unique and guarded")
  465. if not click and raw["clicked"]:
  466. raise CalendarBookError("Book date readback unexpectedly clicked")
  467. return raw
  468. def _wait_selected_day(page: object, service: str, day: date, *, timeout: float) -> None:
  469. deadline = time.monotonic() + timeout
  470. while True:
  471. raw = _date_snapshot(page, service, day)
  472. if raw["candidateCount"] == 1 and raw["selectedMatches"]:
  473. return
  474. if time.monotonic() >= deadline:
  475. raise CalendarBookError("Book selected date did not match the response before timeout")
  476. time.sleep(0.1)
  477. def _click_date(page: object, service: str, day: date, *, timeout: float) -> None:
  478. deadline = time.monotonic() + timeout
  479. while True:
  480. raw = _date_snapshot(page, service, day)
  481. if raw["selectedMatches"]:
  482. raise CalendarBookError("Book date is already selected without a fresh captured response")
  483. if raw["candidateCount"] == 1 and raw["candidateEnabled"]:
  484. break
  485. if time.monotonic() >= deadline:
  486. raise CalendarBookError("Book date control was not ready before timeout")
  487. time.sleep(0.1)
  488. acted = _date_snapshot(page, service, day, click=True)
  489. if not acted["clicked"]:
  490. raise CalendarBookError("Book date click was not acknowledged")
  491. def _capture_month(
  492. page: object, *, action: Callable[[], None], service: str,
  493. session_is_current: Callable[[], bool], timeout: float, dom_timeout: float,
  494. previous: _CapturedMonth | None = None,
  495. ) -> _CapturedMonth:
  496. """Capture Availability plus the site's automatic first-day TimeSlots."""
  497. _require_context(page, service, session_is_current)
  498. page.listen.start([AVAILABILITY_PATH, TIME_SLOTS_PATH], method="POST")
  499. try:
  500. action()
  501. wait_for_calendar_service(
  502. page, session_is_current=session_is_current,
  503. expected_service=service, timeout=min(dom_timeout, timeout),
  504. )
  505. _require_context(page, service, session_is_current)
  506. deadline = time.monotonic() + timeout
  507. captured = {}
  508. probe = None
  509. # Only two matching responses belong to one normal month-load action.
  510. for _ in range(2):
  511. remaining = deadline - time.monotonic()
  512. if remaining <= 0:
  513. raise CalendarBookError("Book month responses exceeded the time budget")
  514. packet = page.listen.wait(timeout=remaining, raise_err=False)
  515. if not packet:
  516. raise CalendarBookError("Book month response was not observed before timeout")
  517. _require_packet_tab(page, packet)
  518. status = packet.response.status
  519. if type(status) is not int or status != 200:
  520. raise CalendarBookError("Book Calendar response status was not 200",
  521. http_status=status if type(status) is int else None)
  522. path, _ = same_origin_path(packet.url)
  523. if path not in {AVAILABILITY_PATH, TIME_SLOTS_PATH} or path in captured:
  524. raise CalendarBookError("Book month produced an unexpected or duplicate response")
  525. captured[path] = packet
  526. if path == AVAILABILITY_PATH:
  527. probe = parse_availability_packet(packet)
  528. if previous and probe.selected_month != next_month_value(previous.probe.selected_month):
  529. raise CalendarBookError("Book Calendar did not advance exactly one month")
  530. if not probe.days or TIME_SLOTS_PATH in captured:
  531. break
  532. elif probe is not None:
  533. break
  534. if probe is None:
  535. raise CalendarBookError("Book month did not return Availability")
  536. availability_packet = captured[AVAILABILITY_PATH]
  537. availability_service = _runtime_id(_post_body(availability_packet).get("_Servizio"))
  538. if previous and availability_service != previous.availability_service:
  539. raise CalendarBookError("Book Availability runtime service changed")
  540. automatic = captured.get(TIME_SLOTS_PATH)
  541. automatic_day = None
  542. if probe.days:
  543. if automatic is None:
  544. raise CalendarBookError("Book automatic day response was not captured")
  545. automatic_day = _request_day(_post_body(automatic).get("selectedDay"))
  546. if automatic_day not in {item.day for item in probe.days}:
  547. raise CalendarBookError("Book automatic day escaped current Availability")
  548. auto_slots = parse_book_time_slots(automatic, target_day=automatic_day, runtime_service_id=service)
  549. auto_inventory = next(item for item in probe.days if item.day == automatic_day)
  550. if not auto_inventory.is_available and available_slot_candidates(auto_slots):
  551. raise CalendarBookError("Book automatic Availability and TimeSlots disagree")
  552. _wait_selected_day(page, service, automatic_day, timeout=dom_timeout)
  553. elif automatic is not None:
  554. raise CalendarBookError("Book empty Availability unexpectedly returned TimeSlots")
  555. _require_context(page, service, session_is_current)
  556. return _CapturedMonth(probe, availability_packet, availability_service, automatic_day, automatic)
  557. finally:
  558. page.listen.stop()
  559. def _try_day(
  560. page: object, month: _CapturedMonth, day: date, *, service: str,
  561. session_is_current: Callable[[], bool], timeout: float, dom_timeout: float,
  562. ) -> PrecommitApproval | None:
  563. _require_context(page, service, session_is_current)
  564. current_date = _date_snapshot(page, service, day)
  565. if day == month.automatic_day and current_date["selectedMatches"]:
  566. times_packet = month.automatic_slots_packet
  567. _wait_selected_day(page, service, day, timeout=dom_timeout)
  568. else:
  569. times_packet = listen_once(
  570. page, target=TIME_SLOTS_PATH, method="POST",
  571. action=lambda: _click_date(page, service, day, timeout=dom_timeout),
  572. timeout=timeout,
  573. )
  574. _require_packet_tab(page, times_packet)
  575. parse_book_time_slots(times_packet, target_day=day, runtime_service_id=service)
  576. _wait_selected_day(page, service, day, timeout=dom_timeout)
  577. slots = parse_book_time_slots(times_packet, target_day=day, runtime_service_id=service)
  578. candidates = available_slot_candidates(slots, start_day=day, end_day=day)
  579. if not candidates:
  580. # Inventory competition is not a protocol error. No slot was clicked.
  581. _require_context(page, service, session_is_current)
  582. return None
  583. deadline = time.monotonic() + dom_timeout
  584. while True:
  585. _require_context(page, service, session_is_current)
  586. raw = _snapshot(page, service, day, candidates[0], click=False)
  587. if not raw["runtimeMatches"] or not raw["finalGuarded"] or raw["candidateCount"] > 1:
  588. raise CalendarBookError("Book slot DOM changed its context or uniqueness")
  589. if raw["candidateReady"]:
  590. _require_ready(raw, day)
  591. break
  592. if time.monotonic() >= deadline:
  593. raise CalendarBookError("Book slot DOM did not match the response before timeout")
  594. time.sleep(0.1)
  595. approval = select_slot_before_final(
  596. page, target_day=day, availability_packet=month.availability_packet,
  597. time_slots_packet=times_packet,
  598. )
  599. _require_context(page, service, session_is_current)
  600. return approval
  601. def recheck_calendar_before_final(
  602. page: object, *, lookahead_months: int, start_day: date, end_day: date,
  603. session_is_current: Callable[[], bool], preferred_day: date | None = None,
  604. month_click_interval_seconds: float = DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
  605. timeout: float = 30, dom_timeout: float = 5,
  606. log: Callable[[str], None] | None = None,
  607. ) -> PrecommitApproval | None:
  608. """Fresh Book-only scan with an optional date hint; never submit a booking.
  609. There are at most two bounded passes: the hinted day, then an ascending
  610. fallback. The caller must attest the prepared applicant/route Session via
  611. session_is_current. No external snapshot or cached response is accepted.
  612. """
  613. try:
  614. # Use existing pure validators before starting any browser action.
  615. month_starts(date(2000, 1, 1), lookahead_months)
  616. if type(start_day) is not date or type(end_day) is not date:
  617. raise CalendarBookError("Book date bounds must be dates")
  618. available_calendar_days((), start_day=start_day, end_day=end_day)
  619. if preferred_day is not None and type(preferred_day) is not date:
  620. raise CalendarBookError("Book preferred day must be a date")
  621. for value in (timeout, dom_timeout, month_click_interval_seconds):
  622. if type(value) not in (int, float) or not 0 <= value < float("inf"):
  623. raise CalendarBookError("Book time budget must be finite and nonnegative")
  624. if timeout == 0 or not callable(session_is_current):
  625. raise CalendarBookError("Book requires a positive timeout and a Session check")
  626. service = read_calendar_service(page)
  627. _require_context(page, service, session_is_current)
  628. common = dict(service=service, session_is_current=session_is_current,
  629. timeout=timeout, dom_timeout=dom_timeout)
  630. def initial() -> _CapturedMonth:
  631. return _capture_month(page, action=lambda: refresh_calendar(page), **common)
  632. def advance(previous: _CapturedMonth) -> _CapturedMonth:
  633. if month_click_interval_seconds:
  634. time.sleep(month_click_interval_seconds)
  635. return _capture_month(page, action=lambda: click_next_month(page), previous=previous, **common)
  636. def positive_days(month: _CapturedMonth) -> tuple:
  637. return available_calendar_days(month.probe.days, start_day=start_day, end_day=end_day)
  638. first = initial()
  639. anchor = first.probe.selected_month
  640. current = first
  641. attempted = set()
  642. if preferred_day is not None and start_day <= preferred_day <= end_day:
  643. offset = (preferred_day.year - anchor[0]) * 12 + preferred_day.month - anchor[1]
  644. if 0 <= offset < lookahead_months:
  645. for _ in range(offset):
  646. current = advance(current)
  647. if preferred_day in {item.day for item in positive_days(current)}:
  648. attempted.add(preferred_day)
  649. approval = _try_day(page, current, preferred_day, **common)
  650. if approval is not None:
  651. return approval
  652. # A failed hint cannot cause a stale earlier month's response
  653. # to be reused. Restart the native scan once and recapture.
  654. first = initial()
  655. if (first.probe.selected_month != anchor or
  656. first.availability_service != current.availability_service):
  657. raise CalendarBookError("Book fallback restart changed the Calendar anchor")
  658. current = first
  659. for index in range(lookahead_months):
  660. if current.probe.selected_month > (end_day.year, end_day.month):
  661. return None
  662. days = positive_days(current)
  663. if log:
  664. log(f"Italy Book Calendar month={month_text(current.probe.selected_month)} candidates={len(days)}")
  665. for item in days:
  666. if item.day in attempted:
  667. continue
  668. attempted.add(item.day)
  669. approval = _try_day(page, current, item.day, **common)
  670. if approval is not None:
  671. return approval
  672. if current.probe.selected_month >= (end_day.year, end_day.month):
  673. return None
  674. if index + 1 < lookahead_months:
  675. current = advance(current)
  676. return None
  677. except CalendarBookError:
  678. raise
  679. except ItaProtocolError as exc:
  680. raise CalendarBookError(f"Book Calendar protocol rejected ({exc.code})") from None
  681. except Exception:
  682. raise CalendarBookError("Book Calendar recheck failed; no further action was attempted") from None
  683. finally:
  684. # Do not leave the final button enabled after a native refresh or error.
  685. try:
  686. if same_origin_path(page.url)[0] == CALENDAR_PATH:
  687. guard_calendar(page)
  688. except Exception:
  689. raise CalendarBookError("Book final-button guard could not be verified") from None