apply_rules.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import asyncio
  2. import dataclasses
  3. from datetime import date, timedelta
  4. from room_cal.closed import Closed
  5. from room_cal.discount import Discount
  6. from room_cal._utils import drop_stale_events, iter_dates, safe_json_loads
  7. import room_cal.rules as _rules
  8. ACTION_SPEC = ('apply-rules', ['pipeline_name'])
  9. # Price rules must run after discounts are written so CalPrice.set picks up current discounts.
  10. _TYPE_ORDER = {'closed': 0, 'discount': 1, 'price': 2}
  11. async def apply_rules(
  12. start_date: date,
  13. end_date: date,
  14. *,
  15. pipeline_name: str | None = None,
  16. ) -> dict:
  17. """Sync rule-generated discounts, closed events, and price floors into the main calendar.
  18. Runs all configured pipelines, or only the named one if pipeline_name is given.
  19. Pipelines run in type order: closed → discount → price, so price floors see
  20. current discounts when computing net prices.
  21. Always calls apply_discounts afterward so prices reflect current discount state.
  22. Returns {pipeline_name: [date, ...]}.
  23. """
  24. names = [pipeline_name] if pipeline_name else _rules.list_pipelines()
  25. if pipeline_name and pipeline_name not in _rules.list_pipelines():
  26. raise ValueError(f"Unknown pipeline: {pipeline_name!r}")
  27. names = sorted(names, key=lambda n: _TYPE_ORDER.get(_rules.pipeline_type(n), 99))
  28. discount_cal = Discount()
  29. closed_cal = Closed()
  30. results: dict[str, list[date]] = {}
  31. for name in names:
  32. rule_type = _rules.pipeline_type(name)
  33. pipeline_source = {'domain': 'rules', 'name': 'Rule =>', 'id': name}
  34. if rule_type == 'closed':
  35. existing_closed = await closed_cal.list(start_date, end_date)
  36. generated = await _rules.run_pipeline(name, start_date, end_date, initial_data=await closed_cal.get_range(start_date, end_date, events=existing_closed))
  37. to_close = {d: rec for d, rec in generated.items() if rec.services}
  38. await drop_stale_events(existing_closed, set(to_close), domain='rules', id_=name, cal=closed_cal)
  39. closed_by_date = {e.start.date(): e for e in existing_closed}
  40. async def _write_closed(d):
  41. rec = dataclasses.replace(to_close[d], source=to_close[d].source or pipeline_source)
  42. await closed_cal.set(d, rec, existing=closed_by_date.get(d))
  43. return d
  44. results[name] = list(await asyncio.gather(*[_write_closed(d) for d in sorted(to_close)]))
  45. elif rule_type == 'price':
  46. from room_cal.pricing import CalPrice
  47. from room_cal.reservations import Reservation
  48. generated = await _rules.run_pipeline(name, start_date, end_date)
  49. price_cal = CalPrice()
  50. price_events, res_events = await asyncio.gather(
  51. price_cal.list(start_date, end_date),
  52. Reservation().list(start_date, end_date),
  53. )
  54. booked: set[date] = set()
  55. for e in res_events:
  56. last_night = e.end.date() - timedelta(days=1)
  57. for d in iter_dates(e.start.date(), last_night):
  58. booked.add(d)
  59. price_by_date: dict[date, tuple] = {}
  60. for e in price_events:
  61. d = e.start.date()
  62. xd = safe_json_loads(e.x_data)
  63. if xd:
  64. base = xd.get('base') or xd.get('net')
  65. price_by_date[d] = (base, e)
  66. async def _write_price(d):
  67. if d in booked:
  68. return None
  69. rec = generated[d]
  70. current_base, existing_event = price_by_date.get(d, (None, None))
  71. if current_base is None or current_base < rec.min_base:
  72. await price_cal.set(d, rec.min_base, existing=existing_event)
  73. return d
  74. return None
  75. gathered = await asyncio.gather(*[_write_price(d) for d in sorted(generated)])
  76. results[name] = [d for d in gathered if d is not None]
  77. else:
  78. existing_discounts = await discount_cal.list(start_date, end_date)
  79. generated = await _rules.run_pipeline(name, start_date, end_date, initial_data=await discount_cal.get_range(start_date, end_date, events=existing_discounts))
  80. await drop_stale_events(existing_discounts, set(generated), domain='rules', id_=name, cal=discount_cal)
  81. discount_by_date = {e.start.date(): e for e in existing_discounts}
  82. async def _write_discount(d):
  83. rec = dataclasses.replace(generated[d], source=generated[d].source or pipeline_source)
  84. await discount_cal.set(d, rec, existing=discount_by_date.get(d))
  85. return d
  86. results[name] = list(await asyncio.gather(*[_write_discount(d) for d in sorted(generated)]))
  87. from room_cal.actions.apply_discounts import apply_discounts
  88. await apply_discounts(start_date, end_date)
  89. return results