push_closed.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from datetime import date
  2. from typing import TYPE_CHECKING
  3. from room_cal.closed import Closed
  4. from room_cal._utils import safe_json_loads
  5. if TYPE_CHECKING:
  6. from room_cal.service_api import ServiceAPI
  7. ACTION_SPEC = ('push-closed', [])
  8. async def push_closed(
  9. start_date: date,
  10. end_date: date,
  11. *,
  12. api: 'ServiceAPI | None' = None,
  13. ) -> list[dict]:
  14. """Read local 'Closed' CalDAV events and push them to the service API.
  15. Dates with a local Closed event are blocked on all services.
  16. Dates without a local Closed event that are blocked in the API are opened.
  17. Skips booked dates (handled by set_available internally).
  18. Returns list of {date, action} for every date changed ('closed' or 'opened').
  19. """
  20. from room_cal.service_api import ServiceAPI as _ServiceAPI
  21. if api is None:
  22. api = _ServiceAPI()
  23. closed_cal = Closed()
  24. cal_events = await closed_cal.list(start_date, end_date)
  25. cal_by_date: set[str] = set()
  26. for e in cal_events:
  27. ds = e.start.date().isoformat()
  28. d = safe_json_loads(e.x_data)
  29. if d is None or d.get('closed_services'):
  30. cal_by_date.add(ds)
  31. api_by_date = await api.get_closed_by_date(start_date, end_date)
  32. # Always push locally-closed dates: set_availability skips if already fully closed
  33. # (checks both available and rooms_to_sell), catching hidden=1/rooms_to_sell=1 drift.
  34. to_close = sorted(cal_by_date)
  35. to_open = sorted(set(api_by_date) - cal_by_date)
  36. results: list[dict] = []
  37. for ds in to_close:
  38. await api.set_available(date.fromisoformat(ds), False)
  39. results.append({'date': date.fromisoformat(ds), 'action': 'closed'})
  40. for ds in to_open:
  41. await api.set_available(date.fromisoformat(ds), True)
  42. results.append({'date': date.fromisoformat(ds), 'action': 'opened'})
  43. results.sort(key=lambda r: r['date'])
  44. return results