| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import asyncio
- import dataclasses
- from datetime import date, timedelta
- from room_cal.closed import Closed
- from room_cal.discount import Discount
- from room_cal._utils import drop_stale_events, iter_dates, safe_json_loads
- import room_cal.rules as _rules
- ACTION_SPEC = ('apply-rules', ['pipeline_name'])
- # Price rules must run after discounts are written so CalPrice.set picks up current discounts.
- _TYPE_ORDER = {'closed': 0, 'discount': 1, 'price': 2}
- async def apply_rules(
- start_date: date,
- end_date: date,
- *,
- pipeline_name: str | None = None,
- ) -> dict:
- """Sync rule-generated discounts, closed events, and price floors into the main calendar.
- Runs all configured pipelines, or only the named one if pipeline_name is given.
- Pipelines run in type order: closed → discount → price, so price floors see
- current discounts when computing net prices.
- Always calls apply_discounts afterward so prices reflect current discount state.
- Returns {pipeline_name: [date, ...]}.
- """
- names = [pipeline_name] if pipeline_name else _rules.list_pipelines()
- if pipeline_name and pipeline_name not in _rules.list_pipelines():
- raise ValueError(f"Unknown pipeline: {pipeline_name!r}")
- names = sorted(names, key=lambda n: _TYPE_ORDER.get(_rules.pipeline_type(n), 99))
- discount_cal = Discount()
- closed_cal = Closed()
- results: dict[str, list[date]] = {}
- for name in names:
- rule_type = _rules.pipeline_type(name)
- pipeline_source = {'domain': 'rules', 'name': 'Rule =>', 'id': name}
- if rule_type == 'closed':
- existing_closed = await closed_cal.list(start_date, end_date)
- generated = await _rules.run_pipeline(name, start_date, end_date, initial_data=await closed_cal.get_range(start_date, end_date, events=existing_closed))
- to_close = {d: rec for d, rec in generated.items() if rec.services}
- await drop_stale_events(existing_closed, set(to_close), domain='rules', id_=name, cal=closed_cal)
- closed_by_date = {e.start.date(): e for e in existing_closed}
- async def _write_closed(d):
- rec = dataclasses.replace(to_close[d], source=to_close[d].source or pipeline_source)
- await closed_cal.set(d, rec, existing=closed_by_date.get(d))
- return d
- results[name] = list(await asyncio.gather(*[_write_closed(d) for d in sorted(to_close)]))
- elif rule_type == 'price':
- from room_cal.pricing import CalPrice
- from room_cal.reservations import Reservation
- generated = await _rules.run_pipeline(name, start_date, end_date)
- price_cal = CalPrice()
- price_events, res_events = await asyncio.gather(
- price_cal.list(start_date, end_date),
- Reservation().list(start_date, end_date),
- )
- booked: set[date] = set()
- for e in res_events:
- last_night = e.end.date() - timedelta(days=1)
- for d in iter_dates(e.start.date(), last_night):
- booked.add(d)
- price_by_date: dict[date, tuple] = {}
- for e in price_events:
- d = e.start.date()
- xd = safe_json_loads(e.x_data)
- if xd:
- base = xd.get('base') or xd.get('net')
- price_by_date[d] = (base, e)
- async def _write_price(d):
- if d in booked:
- return None
- rec = generated[d]
- current_base, existing_event = price_by_date.get(d, (None, None))
- if current_base is None or current_base < rec.min_base:
- await price_cal.set(d, rec.min_base, existing=existing_event)
- return d
- return None
- gathered = await asyncio.gather(*[_write_price(d) for d in sorted(generated)])
- results[name] = [d for d in gathered if d is not None]
- else:
- existing_discounts = await discount_cal.list(start_date, end_date)
- generated = await _rules.run_pipeline(name, start_date, end_date, initial_data=await discount_cal.get_range(start_date, end_date, events=existing_discounts))
- await drop_stale_events(existing_discounts, set(generated), domain='rules', id_=name, cal=discount_cal)
- discount_by_date = {e.start.date(): e for e in existing_discounts}
- async def _write_discount(d):
- rec = dataclasses.replace(generated[d], source=generated[d].source or pipeline_source)
- await discount_cal.set(d, rec, existing=discount_by_date.get(d))
- return d
- results[name] = list(await asyncio.gather(*[_write_discount(d) for d in sorted(generated)]))
- from room_cal.actions.apply_discounts import apply_discounts
- await apply_discounts(start_date, end_date)
- return results
|