fetch_prices.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import asyncio
  2. from datetime import date, timedelta
  3. from typing import TYPE_CHECKING
  4. from room_cal.pricing import CalPrice
  5. from room_cal.pricing.calc import list_to_net
  6. from room_cal.reservations import Reservation
  7. from room_cal._utils import FetchResult, services as _services, safe_json_loads, iter_dates
  8. if TYPE_CHECKING:
  9. from room_cal.service_api import ServiceAPI
  10. ACTION_SPEC = ('fetch-prices', ['service'])
  11. async def fetch_prices(
  12. start_date: date,
  13. end_date: date,
  14. *,
  15. api: 'ServiceAPI | None' = None,
  16. service: str | None = None,
  17. booked_only: bool = True,
  18. ) -> FetchResult[list[dict]]:
  19. """Fetch per-service list prices from the API and write net prices to the calendar.
  20. Converts each service's list price back to a net price via the calc module, then
  21. calls CalPrice.set so all derived list/retail prices are recomputed consistently.
  22. Dates where all services report None (booked or unavailable) are skipped.
  23. Returns FetchResult with list of {date, net} for each date written, and a changed flag.
  24. If `service` is given, only that service's prices are used; otherwise the
  25. first service with a non-None price wins.
  26. If `booked_only` is True (the default), only dates with an active reservation are
  27. updated; open days are skipped. Pass booked_only=False for initial data imports,
  28. but note that prices are written as-is with no discount applied — callers are
  29. responsible for following up with local_sync or apply_discounts if needed.
  30. """
  31. from room_cal.service_api import ServiceAPI as _ServiceAPI
  32. if api is None:
  33. api = _ServiceAPI()
  34. api_prices, booked_nets = await asyncio.gather(
  35. api.get_prices_range(start_date, end_date),
  36. api.get_booked_nets(start_date, end_date),
  37. )
  38. if not api_prices:
  39. return FetchResult(data=[], changed=False)
  40. service_keys = [service] if service else _services()
  41. cal = CalPrice()
  42. existing_events, res_events = await asyncio.gather(
  43. cal.list(start_date, end_date),
  44. Reservation().list(start_date, end_date),
  45. )
  46. existing_by_date = {e.start.date(): e for e in existing_events}
  47. booked_svc_by_date: dict[str, str] = {}
  48. for e in res_events:
  49. xd = safe_json_loads(e.x_data)
  50. if xd:
  51. svc = xd.get('service')
  52. if svc:
  53. last_night = e.end.date() - timedelta(days=1)
  54. for d in iter_dates(e.start.date(), last_night):
  55. booked_svc_by_date[d.isoformat()] = svc
  56. changed = False
  57. results: list[dict] = []
  58. for ds in sorted(api_prices):
  59. service_prices = api_prices[ds]
  60. booked_svc = booked_svc_by_date.get(ds)
  61. if booked_only and not booked_svc:
  62. continue
  63. keys_to_try = [booked_svc] if booked_svc and not service else service_keys
  64. net = None
  65. for svc in keys_to_try:
  66. svc_booked_net = (booked_nets.get(ds) or {}).get(svc)
  67. if svc_booked_net is not None:
  68. net = svc_booked_net
  69. break
  70. list_price = service_prices.get(svc)
  71. if list_price is not None:
  72. net = list_to_net(svc, list_price)
  73. break
  74. if net is None:
  75. continue
  76. d = date.fromisoformat(ds)
  77. existing = existing_by_date.get(d)
  78. if existing is None:
  79. changed = True
  80. else:
  81. xd = safe_json_loads(existing.x_data)
  82. if (xd or {}).get('net') != net:
  83. changed = True
  84. await cal.set(d, net, existing=existing, discount_rec=None)
  85. results.append({'date': d, 'net': net})
  86. return FetchResult(data=results, changed=changed)