_cli.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. """CLI dispatcher for room_cal sync/refresh/diff actions.
  2. Usage:
  3. room-cal fetch-reservations 2026-07-01 2026-07-31
  4. room-cal fetch-closed 2026-07-01
  5. room-cal push-closed 2026-07-01 2026-07-31
  6. room-cal fetch-user-cal 2026-07-01 2026-07-31
  7. room-cal apply-rules 2026-07-01 2026-07-31 [--pipeline-name this_month]
  8. room-cal fetch-feed 2026-07-01 2026-07-31 [--feed-name Fire] [--title "Block"]
  9. room-cal fill-prices 2026-07-01 2026-07-31 [--weekday 150] [--weekend 200]
  10. room-cal fetch-prices 2026-07-01 2026-07-31 [--service airbnb]
  11. room-cal push-prices 2026-07-01 2026-07-31
  12. room-cal apply-discounts 2026-07-01 2026-07-31
  13. room-cal local-sync 2026-07-01 2026-07-31
  14. room-cal local-refresh 2026-07-01 2026-07-31
  15. room-cal diff 2026-07-01 2026-07-31
  16. """
  17. import argparse
  18. import asyncio
  19. from datetime import date
  20. def _date(s: str) -> date:
  21. return date.fromisoformat(s)
  22. async def _fetch_reservations(start: date, end: date, args) -> None:
  23. from room_cal.actions.fetch_reservations import fetch_reservations
  24. result = await fetch_reservations(start, end)
  25. for r in result.data:
  26. print(f" {r['service']} {r['checkin_date']} – {r['checkout_date']}: {r['guest_name']}")
  27. print(f" {len(result.data)} reservation(s) synced" + (" (changed)" if result.changed else ""))
  28. async def _fetch_closed(start: date, end: date, args) -> None:
  29. from room_cal.actions.fetch_closed import fetch_closed
  30. result = await fetch_closed(start, end)
  31. for r in result.data:
  32. print(f" {r['date']}: {', '.join(r['closed_services'])}")
  33. print(f" {len(result.data)} closed event(s) synced" + (" (changed)" if result.changed else ""))
  34. async def _fetch_user_cal(start: date, end: date, args) -> None:
  35. from room_cal.actions.fetch_user_cal import fetch_user_cal
  36. result = await fetch_user_cal(start, end)
  37. for d in result.data['closed']:
  38. print(f" closed: {d}")
  39. print(f" {len(result.data['closed'])} date(s) closed synced from user_cal" + (" (changed)" if result.changed else ""))
  40. async def _push_closed(start: date, end: date, args) -> None:
  41. from room_cal.actions.push_closed import push_closed
  42. results = await push_closed(start, end)
  43. for r in results:
  44. print(f" {r['date']}: {r['action']}")
  45. print(f" {len(results)} date(s) changed")
  46. async def _apply_rules(start: date, end: date, args) -> None:
  47. from room_cal.actions.apply_rules import apply_rules
  48. results = await apply_rules(start, end, pipeline_name=args.pipeline_name or None)
  49. total = 0
  50. for name, dates in results.items():
  51. for d in dates:
  52. print(f" {name}: {d}")
  53. total += len(dates)
  54. print(f" {total} event(s) synced from rules")
  55. async def _fetch_feed(start: date, end: date, args) -> None:
  56. from room_cal.actions.fetch_feed import fetch_feed
  57. result = await fetch_feed(start, end, feed_name=args.feed_name, title=args.title or None)
  58. for d in result.data:
  59. print(f" {d}")
  60. print(f" {len(result.data)} date(s) marked closed" + (" (changed)" if result.changed else ""))
  61. async def _fetch_prices(start: date, end: date, args) -> None:
  62. from room_cal.actions.fetch_prices import fetch_prices
  63. result = await fetch_prices(start, end, service=args.service or None)
  64. for r in result.data:
  65. print(f" {r['date']}: net ${r['net']}")
  66. print(f" {len(result.data)} price event(s) written" + (" (changed)" if result.changed else ""))
  67. async def _push_prices(start: date, end: date, args) -> None:
  68. from room_cal.actions.push_prices import push_prices
  69. results = await push_prices(start, end)
  70. for r in results:
  71. prices_str = ' '.join(f"{s}: ${v}" for s, v in r['prices'].items())
  72. print(f" {r['date']}: {prices_str}")
  73. print(f" {len(results)} date(s) pushed")
  74. async def _fill_prices(start: date, end: date, args) -> None:
  75. from room_cal.actions.fill_prices import fill_prices
  76. results = await fill_prices(
  77. start, end,
  78. weekday=int(args.weekday) if args.weekday else None,
  79. weekend=int(args.weekend) if args.weekend else None,
  80. )
  81. for r in results:
  82. print(f" {r['date']}: net ${r['net']}")
  83. print(f" {len(results)} price event(s) created")
  84. async def _apply_discounts(start: date, end: date, args) -> None:
  85. from room_cal.actions.apply_discounts import apply_discounts
  86. results = await apply_discounts(start, end)
  87. for r in results:
  88. old = ' '.join(f"{s}: ${v}" for s, v in r['old_prices'].items() if v is not None)
  89. new = ' '.join(f"{s}: ${v}" for s, v in r['new_prices'].items())
  90. print(f" {r['date']}: {old} → {new}")
  91. print(f" {len(results)} date(s) updated")
  92. async def _local_sync(start: date, end: date, args) -> None:
  93. from room_cal.actions.local_sync import local_sync
  94. await local_sync(start, end)
  95. async def _local_refresh(start: date, end: date, args) -> None:
  96. from room_cal.actions.local_refresh import local_refresh
  97. await local_refresh(start, end)
  98. async def _remote_sync(start: date, end: date, args) -> None:
  99. from room_cal.actions.remote_sync import remote_sync
  100. result = await remote_sync(start, end)
  101. any_fixed = False
  102. for svc, issues in result.items():
  103. if not issues:
  104. continue
  105. any_fixed = True
  106. n = len(issues)
  107. print(f"\n Fixed: {svc} ({n} date{'s' if n != 1 else ''})")
  108. _fmt_table(
  109. [[str(i['date']), str(i['actual_rts']), str(i['expected_rts'])] for i in issues],
  110. ['date', 'was', 'now'],
  111. )
  112. if not any_fixed:
  113. print(" no issues found")
  114. def _fmt_table(rows: list[list[str]], header: list[str]) -> None:
  115. all_rows = [header] + rows
  116. widths = [max(len(r[i]) for r in all_rows) for i in range(len(header))]
  117. sep = ' '
  118. fmt = sep.join(f'{{:<{w}}}' for w in widths)
  119. print(' ' + fmt.format(*header))
  120. print(' ' + sep.join('-' * w for w in widths))
  121. for row in rows:
  122. print(' ' + fmt.format(*row))
  123. def _fmt_price(local: int | None, remote: int | None) -> str:
  124. if local is None and remote is None:
  125. return '—'
  126. if local is None:
  127. return f'—→${remote}'
  128. if remote is None:
  129. return f'${local}→—'
  130. if local != remote:
  131. return f'${local}→${remote}'
  132. return f'${remote}'
  133. def _fmt_discount(d: dict | None) -> str:
  134. if d is None:
  135. return '—'
  136. if d['type'] == 'flat':
  137. return f"flat:${d['value']}"
  138. return f"pct:{d['value']}%"
  139. async def _diff(start: date, end: date, args) -> None:
  140. from room_cal.actions.diff import diff
  141. from room_cal._utils import services
  142. result = await diff(start, end)
  143. svc_keys = services()
  144. any_diff = False
  145. prices = result['prices']
  146. if prices:
  147. any_diff = True
  148. n = len(prices)
  149. print(f"\n Prices ({n} date{'s' if n != 1 else ''} differ)")
  150. header = ['date', 'local'] + svc_keys
  151. rows = []
  152. for p in prices:
  153. net_str = f"${p['net']}" if p['net'] is not None else '—'
  154. svc_cols = [
  155. _fmt_price(
  156. p['per_service'][svc]['local'] if svc in p['per_service'] else None,
  157. p['per_service'][svc]['remote'] if svc in p['per_service'] else None,
  158. )
  159. for svc in svc_keys
  160. ]
  161. rows.append([str(p['date']), net_str] + svc_cols)
  162. _fmt_table(rows, header)
  163. closed = result['closed']
  164. if closed:
  165. any_diff = True
  166. n = len(closed)
  167. print(f"\n Closed vs service_api ({n} date{'s' if n != 1 else ''} differ)")
  168. header = ['date', 'local'] + svc_keys
  169. rows = []
  170. for c in closed:
  171. local_str = ', '.join(c['local']) if c['local'] else '—'
  172. remote = c['remote'] or []
  173. svc_cols = ['closed' if svc in remote else 'open' for svc in svc_keys]
  174. rows.append([str(c['date']), local_str] + svc_cols)
  175. _fmt_table(rows, header)
  176. reservations = result['reservations']
  177. if reservations:
  178. any_diff = True
  179. n = len(reservations)
  180. print(f"\n Reservations ({n} {'change' if n == 1 else 'changes'})")
  181. for r in reservations:
  182. if r['status'] == 'added':
  183. print(f" [+] {r['service']} {r['checkin_date']} → {r['checkout_date']} {r['guest_name']} ({r['reservation_id']})")
  184. elif r['status'] == 'removed':
  185. print(f" [-] {r['service']} {r['checkin_date']} → {r['checkout_date']} {r['guest_name']} ({r['reservation_id']})")
  186. elif r['status'] == 'changed':
  187. for c in r['changes']:
  188. print(f" [~] {r['reservation_id']} {c['field']}: {c['local']!r} → {c['remote']!r}")
  189. double_bookings = result['double_bookings']
  190. if double_bookings:
  191. any_diff = True
  192. n = len(double_bookings)
  193. print(f"\n Double bookings ({n} overlap{'s' if n != 1 else ''})")
  194. for db in double_bookings:
  195. a, b = db['a'], db['b']
  196. print(f" [!] {db['overlap_start']} – {db['overlap_end']}")
  197. print(f" {a['service']} {a['checkin_date']} → {a['checkout_date']} {a['guest_name']} ({a['id']})")
  198. print(f" {b['service']} {b['checkin_date']} → {b['checkout_date']} {b['guest_name']} ({b['id']})")
  199. uc_closed = result['user_cal_closed']
  200. if uc_closed:
  201. any_diff = True
  202. n = len(uc_closed)
  203. print(f"\n Closed vs user_cal ({n} date{'s' if n != 1 else ''} differ)")
  204. _fmt_table(
  205. [[str(r['date']), 'closed' if r['in_room'] else 'open', 'closed' if r['in_user_cal'] else 'open']
  206. for r in uc_closed],
  207. ['date', 'room', 'user_cal'],
  208. )
  209. ical_feeds_closed = result['ical_feeds_closed']
  210. for feed_name, rows_data in ical_feeds_closed.items():
  211. any_diff = True
  212. n = len(rows_data)
  213. print(f"\n Closed vs ical_feeds \"{feed_name}\" ({n} date{'s' if n != 1 else ''} differ)")
  214. _fmt_table(
  215. [[str(r['date']), 'closed' if r['in_room'] else 'open', 'blocked' if r['in_ical_feeds'] else 'open']
  216. for r in rows_data],
  217. ['date', 'room', 'ical_feeds'],
  218. )
  219. rule_discounts = result['rule_discounts']
  220. for pipeline_name, rows_data in rule_discounts.items():
  221. any_diff = True
  222. n = len(rows_data)
  223. print(f"\n Discounts vs rule \"{pipeline_name}\" ({n} date{'s' if n != 1 else ''} differ)")
  224. _fmt_table(
  225. [[str(d['date']), _fmt_discount(d['local']), _fmt_discount(d['rule'])] for d in rows_data],
  226. ['date', 'local', 'rule'],
  227. )
  228. rule_closed = result['rule_closed']
  229. for pipeline_name, rows_data in rule_closed.items():
  230. any_diff = True
  231. n = len(rows_data)
  232. print(f"\n Closed vs rule \"{pipeline_name}\" ({n} date{'s' if n != 1 else ''} differ)")
  233. _fmt_table(
  234. [[str(r['date']), 'closed' if r['in_room'] else 'open', 'closed' if r['in_rule'] else 'open']
  235. for r in rows_data],
  236. ['date', 'room', 'rule'],
  237. )
  238. rule_prices = result['rule_prices']
  239. for pipeline_name, rows_data in rule_prices.items():
  240. any_diff = True
  241. n = len(rows_data)
  242. print(f"\n Prices vs rule \"{pipeline_name}\" ({n} date{'s' if n != 1 else ''} differ)")
  243. _fmt_table(
  244. [[str(r['date']), f"${r['local_base']}" if r['local_base'] is not None else '(none)', f"${r['rule_min']}"]
  245. for r in rows_data],
  246. ['date', 'local_base', 'rule_min'],
  247. )
  248. orphans = result['orphans']
  249. if orphans:
  250. any_diff = True
  251. n = len(orphans)
  252. print(f"\n Orphans ({n} event{'s' if n != 1 else ''})")
  253. rows = []
  254. for o in orphans:
  255. src = o['source']
  256. src_str = f"{src['domain']}:{src.get('id','')}" if src else '(none)'
  257. rows.append([str(o['date']), o['event_type'], o['title'], src_str])
  258. _fmt_table(rows, ['date', 'type', 'title', 'source'])
  259. remote_sync = result.get('remote_sync', {})
  260. for svc, issues in remote_sync.items():
  261. if not issues:
  262. continue
  263. any_diff = True
  264. n = len(issues)
  265. print(f"\n Remote sync issues: {svc} ({n} date{'s' if n != 1 else ''})")
  266. _fmt_table(
  267. [[str(i['date']), str(i['actual_rts']), str(i['expected_rts'])] for i in issues],
  268. ['date', 'actual_rts', 'expected_rts'],
  269. )
  270. if not any_diff:
  271. print(" no differences")
  272. timings = result.get('_timings', {})
  273. if timings:
  274. total = timings.pop('_total', None)
  275. header = f" Timings (wall: {total:.1f}s)" if total is not None else " Timings"
  276. print(f"\n{header}")
  277. for k, v in sorted(timings.items(), key=lambda x: -x[1]):
  278. print(f" {k:<22} {v:.2f}s")
  279. _ACTIONS: dict[str, tuple] = {
  280. 'fetch-reservations': (_fetch_reservations, 'Fetch reservations from all services and write to CalDAV'),
  281. 'fetch-closed': (_fetch_closed, 'Fetch per-service blocked dates and write to CalDAV'),
  282. 'fetch-user-cal': (_fetch_user_cal, 'Sync Room Closed events from user_cal to the main calendar'),
  283. 'apply-rules': (_apply_rules, 'Sync rule-generated discounts and closed events into the main calendar'),
  284. 'push-closed': (_push_closed, 'Read local CalDAV closed events and push changes to all services'),
  285. 'fetch-feed': (_fetch_feed, 'Mark days with events on an iCal feed as closed on all services'),
  286. 'fill-prices': (_fill_prices, 'Create default price events for dates with no local price'),
  287. 'fetch-prices': (_fetch_prices, 'Fetch service API list prices and write net prices to CalDAV'),
  288. 'push-prices': (_push_prices, 'Read local CalDAV price events and push list prices to all services'),
  289. 'apply-discounts': (_apply_discounts, 'Re-apply discount events to price calendar and push changed list prices'),
  290. 'local-sync': (_local_sync, 'Fetch all iCal feeds, apply rules, and fill prices — no service API calls'),
  291. 'local-refresh': (_local_refresh, 'Re-write all local Room calendar events (prices, closed, discounts, reservations)'),
  292. 'remote-sync': (_remote_sync, 'Integrity-check and repair service-side data (e.g. Booking.com rooms_to_sell drift)'),
  293. 'diff': (_diff, 'Compare local CalDAV data to live service APIs and report all differences (read-only)'),
  294. }
  295. def main() -> None:
  296. parser = argparse.ArgumentParser(
  297. prog='room-cal',
  298. description=__doc__,
  299. formatter_class=argparse.RawDescriptionHelpFormatter,
  300. )
  301. parser.add_argument(
  302. 'action', choices=list(_ACTIONS), metavar='ACTION',
  303. help='Action to run: ' + ', '.join(_ACTIONS),
  304. )
  305. parser.add_argument('start', type=_date, help='Start date (YYYY-MM-DD)')
  306. parser.add_argument('end', type=_date, nargs='?', help='End date inclusive (default: same as start)')
  307. parser.add_argument(
  308. '--feed-name', default='Fire', metavar='NAME',
  309. help='iCal feed name for fetch-feed (default: Fire)',
  310. )
  311. parser.add_argument(
  312. '--title', default=None, metavar='TITLE',
  313. help='Only close dates for feed events whose summary exactly matches TITLE',
  314. )
  315. parser.add_argument(
  316. '--pipeline-name', default=None, metavar='PIPELINE',
  317. help='Pipeline name for apply-rules (default: all pipelines)',
  318. )
  319. parser.add_argument(
  320. '--service', default=None, metavar='SERVICE',
  321. help='Service key to use for fetch-prices (default: first available)',
  322. )
  323. parser.add_argument(
  324. '--weekday', default=None, metavar='PRICE',
  325. help='Weekday net price override for fill-prices',
  326. )
  327. parser.add_argument(
  328. '--weekend', default=None, metavar='PRICE',
  329. help='Weekend net price override for fill-prices',
  330. )
  331. args = parser.parse_args()
  332. end = args.end or args.start
  333. if end < args.start:
  334. parser.error(f"end date {end} is before start date {args.start}")
  335. from room_cal.service_api.types import ServiceAuthError
  336. fn, _ = _ACTIONS[args.action]
  337. print(f"{args.action} {args.start} – {end}")
  338. try:
  339. asyncio.run(fn(args.start, end, args))
  340. except ServiceAuthError as e:
  341. print(f" error: {e}")
  342. raise SystemExit(1)