fetch_closed.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from datetime import date
  2. from typing import TYPE_CHECKING
  3. from room_cal.closed import Closed, ClosedData
  4. from room_cal.reservations import Reservation
  5. from room_cal._utils import FetchResult, is_ephemeral_domain, safe_json_loads
  6. if TYPE_CHECKING:
  7. from room_cal.service_api import ServiceAPI
  8. ACTION_SPEC = ('fetch-closed', [])
  9. async def fetch_closed(
  10. start_date: date,
  11. end_date: date,
  12. *,
  13. api: 'ServiceAPI | None' = None,
  14. ) -> FetchResult[list[dict]]:
  15. """Fetch per-service blocked dates and write them to the calendar as 'Closed' all-day events.
  16. Deletes any existing 'Closed' events for dates that are now open.
  17. Returns FetchResult with list of {date, closed_services} for dates that have
  18. closure events after sync, and a changed flag.
  19. """
  20. from room_cal.service_api import ServiceAPI as _ServiceAPI
  21. from room_cal.actions.fetch_reservations import fetch_reservations
  22. if api is None:
  23. api = _ServiceAPI()
  24. closed_cal = Closed()
  25. res_cal = Reservation()
  26. existing_events = await closed_cal.list(start_date, end_date)
  27. existing_by_date: dict[str, object] = {}
  28. for e in existing_events:
  29. ds = e.start.date().isoformat()
  30. existing_by_date[ds] = e
  31. closed_by_date = await api.get_closed_by_date(start_date, end_date)
  32. changed = False
  33. for ds, event in existing_by_date.items():
  34. if ds not in closed_by_date:
  35. xd = safe_json_loads(event.x_data)
  36. event_domain = (xd or {}).get('source', {}).get('domain')
  37. if event_domain == 'service_api' or is_ephemeral_domain(event_domain):
  38. changed = True
  39. await closed_cal.delete(event)
  40. synced: list[dict] = []
  41. for ds, closed_services in sorted(closed_by_date.items()):
  42. day = date.fromisoformat(ds)
  43. reservations_on_day = await res_cal.list(day, day)
  44. if reservations_on_day:
  45. res_start = min(e.start.date() for e in reservations_on_day)
  46. res_end = max(e.end.date() for e in reservations_on_day)
  47. await fetch_reservations(min(start_date, res_start), max(end_date, res_end), api=api)
  48. else:
  49. services_str = ', '.join(sorted(closed_services))
  50. source = {'domain': 'service_api', 'name': 'Upstream =>', 'id': services_str}
  51. existing = existing_by_date.get(ds)
  52. if existing is None:
  53. changed = True
  54. else:
  55. xd = safe_json_loads(existing.x_data)
  56. existing_services = sorted((xd or {}).get('closed_services') or [])
  57. if existing_services != sorted(closed_services):
  58. changed = True
  59. await closed_cal.set(day, ClosedData(services=closed_services, source=source))
  60. synced.append({'date': day, 'closed_services': closed_services})
  61. return FetchResult(data=synced, changed=changed)