notifications.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. """API routes for notification providers."""
  2. import json
  3. import logging
  4. from datetime import datetime, timedelta, timezone
  5. from fastapi import APIRouter, Depends, HTTPException, Query
  6. from sqlalchemy import delete, desc, func, select
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  9. from backend.app.core.database import get_db
  10. from backend.app.core.permissions import Permission
  11. from backend.app.models.notification import NotificationLog, NotificationProvider
  12. from backend.app.models.user import User
  13. from backend.app.schemas.notification import (
  14. NotificationLogResponse,
  15. NotificationLogStats,
  16. NotificationProviderCreate,
  17. NotificationProviderResponse,
  18. NotificationProviderUpdate,
  19. NotificationTestRequest,
  20. NotificationTestResponse,
  21. )
  22. from backend.app.services.notification_service import notification_service
  23. logger = logging.getLogger(__name__)
  24. router = APIRouter(prefix="/notifications", tags=["notifications"])
  25. def _provider_to_dict(provider: NotificationProvider) -> dict:
  26. """Convert a NotificationProvider model to a response dictionary."""
  27. return {
  28. "id": provider.id,
  29. "name": provider.name,
  30. "provider_type": provider.provider_type,
  31. "enabled": provider.enabled,
  32. "config": json.loads(provider.config) if isinstance(provider.config, str) else provider.config,
  33. # Print lifecycle events
  34. "on_print_start": provider.on_print_start,
  35. "on_print_complete": provider.on_print_complete,
  36. "on_print_failed": provider.on_print_failed,
  37. "on_print_stopped": provider.on_print_stopped,
  38. "on_print_progress": provider.on_print_progress,
  39. "on_print_missing_spool_assignment": provider.on_print_missing_spool_assignment,
  40. "on_billing_charge_failed": provider.on_billing_charge_failed,
  41. # Printer status events
  42. "on_printer_offline": provider.on_printer_offline,
  43. "on_printer_error": provider.on_printer_error,
  44. "on_ai_failure_detection": provider.on_ai_failure_detection,
  45. "on_filament_low": provider.on_filament_low,
  46. "on_maintenance_due": provider.on_maintenance_due,
  47. # AMS environmental alarms (regular AMS)
  48. "on_ams_humidity_high": provider.on_ams_humidity_high,
  49. "on_ams_temperature_high": provider.on_ams_temperature_high,
  50. # AMS-HT environmental alarms
  51. "on_ams_ht_humidity_high": provider.on_ams_ht_humidity_high,
  52. "on_ams_ht_temperature_high": provider.on_ams_ht_temperature_high,
  53. # Build plate detection
  54. "on_plate_not_empty": provider.on_plate_not_empty,
  55. "on_plate_clear_required": provider.on_plate_clear_required,
  56. # Bed cooled
  57. "on_bed_cooled": provider.on_bed_cooled,
  58. # First layer complete
  59. "on_first_layer_complete": provider.on_first_layer_complete,
  60. # Print queue events
  61. "on_queue_job_added": provider.on_queue_job_added,
  62. "on_queue_job_assigned": provider.on_queue_job_assigned,
  63. "on_queue_job_started": provider.on_queue_job_started,
  64. "on_queue_job_waiting": provider.on_queue_job_waiting,
  65. "on_queue_job_skipped": provider.on_queue_job_skipped,
  66. "on_queue_job_failed": provider.on_queue_job_failed,
  67. "on_queue_completed": provider.on_queue_completed,
  68. # Quiet hours
  69. "quiet_hours_enabled": provider.quiet_hours_enabled,
  70. "quiet_hours_start": provider.quiet_hours_start,
  71. "quiet_hours_end": provider.quiet_hours_end,
  72. # Daily digest
  73. "daily_digest_enabled": provider.daily_digest_enabled,
  74. "daily_digest_time": provider.daily_digest_time,
  75. # Printer filter
  76. "printer_id": provider.printer_id,
  77. # Status tracking
  78. "last_success": provider.last_success,
  79. "last_error": provider.last_error,
  80. "last_error_at": provider.last_error_at,
  81. # Timestamps
  82. "created_at": provider.created_at,
  83. "updated_at": provider.updated_at,
  84. }
  85. # ============================================================================
  86. # Provider List/Create Routes (no path parameters)
  87. # ============================================================================
  88. @router.get("/", response_model=list[NotificationProviderResponse])
  89. async def list_notification_providers(
  90. db: AsyncSession = Depends(get_db),
  91. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  92. ):
  93. """List all notification providers."""
  94. result = await db.execute(select(NotificationProvider).order_by(NotificationProvider.created_at.desc()))
  95. providers = result.scalars().all()
  96. return [_provider_to_dict(provider) for provider in providers]
  97. @router.post("/", response_model=NotificationProviderResponse)
  98. async def create_notification_provider(
  99. provider_data: NotificationProviderCreate,
  100. db: AsyncSession = Depends(get_db),
  101. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_CREATE),
  102. ):
  103. """Create a new notification provider."""
  104. provider = NotificationProvider(
  105. name=provider_data.name,
  106. provider_type=provider_data.provider_type.value,
  107. enabled=provider_data.enabled,
  108. config=json.dumps(provider_data.config),
  109. # Print lifecycle events
  110. on_print_start=provider_data.on_print_start,
  111. on_print_complete=provider_data.on_print_complete,
  112. on_print_failed=provider_data.on_print_failed,
  113. on_print_stopped=provider_data.on_print_stopped,
  114. on_print_progress=provider_data.on_print_progress,
  115. on_print_missing_spool_assignment=provider_data.on_print_missing_spool_assignment,
  116. on_billing_charge_failed=provider_data.on_billing_charge_failed,
  117. # Printer status events
  118. on_printer_offline=provider_data.on_printer_offline,
  119. on_printer_error=provider_data.on_printer_error,
  120. on_ai_failure_detection=provider_data.on_ai_failure_detection,
  121. on_filament_low=provider_data.on_filament_low,
  122. on_maintenance_due=provider_data.on_maintenance_due,
  123. # AMS environmental alarms (regular AMS)
  124. on_ams_humidity_high=provider_data.on_ams_humidity_high,
  125. on_ams_temperature_high=provider_data.on_ams_temperature_high,
  126. # AMS-HT environmental alarms
  127. on_ams_ht_humidity_high=provider_data.on_ams_ht_humidity_high,
  128. on_ams_ht_temperature_high=provider_data.on_ams_ht_temperature_high,
  129. # Build plate detection
  130. on_plate_not_empty=provider_data.on_plate_not_empty,
  131. on_plate_clear_required=provider_data.on_plate_clear_required,
  132. # Bed cooled
  133. on_bed_cooled=provider_data.on_bed_cooled,
  134. # First layer complete
  135. on_first_layer_complete=provider_data.on_first_layer_complete,
  136. # Print queue events
  137. on_queue_job_added=provider_data.on_queue_job_added,
  138. on_queue_job_assigned=provider_data.on_queue_job_assigned,
  139. on_queue_job_started=provider_data.on_queue_job_started,
  140. on_queue_job_waiting=provider_data.on_queue_job_waiting,
  141. on_queue_job_skipped=provider_data.on_queue_job_skipped,
  142. on_queue_job_failed=provider_data.on_queue_job_failed,
  143. on_queue_completed=provider_data.on_queue_completed,
  144. # Quiet hours
  145. quiet_hours_enabled=provider_data.quiet_hours_enabled,
  146. quiet_hours_start=provider_data.quiet_hours_start,
  147. quiet_hours_end=provider_data.quiet_hours_end,
  148. # Daily digest
  149. daily_digest_enabled=provider_data.daily_digest_enabled,
  150. daily_digest_time=provider_data.daily_digest_time,
  151. # Printer filter
  152. printer_id=provider_data.printer_id,
  153. )
  154. db.add(provider)
  155. await db.commit()
  156. await db.refresh(provider)
  157. logger.info("Created notification provider: %s (%s)", provider.name, provider.provider_type)
  158. return _provider_to_dict(provider)
  159. # ============================================================================
  160. # Static Path Routes (must come BEFORE parameterized routes)
  161. # ============================================================================
  162. @router.post("/test-config", response_model=NotificationTestResponse)
  163. async def test_notification_config(
  164. test_request: NotificationTestRequest,
  165. db: AsyncSession = Depends(get_db),
  166. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_CREATE),
  167. ):
  168. """Test notification configuration before saving."""
  169. success, message = await notification_service.send_test_notification(
  170. test_request.provider_type.value, test_request.config, db
  171. )
  172. return NotificationTestResponse(success=success, message=message)
  173. @router.post("/test-all")
  174. async def test_all_notification_providers(
  175. db: AsyncSession = Depends(get_db),
  176. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  177. ):
  178. """Send a test notification to all enabled providers."""
  179. result = await db.execute(select(NotificationProvider).where(NotificationProvider.enabled.is_(True)))
  180. providers = result.scalars().all()
  181. if not providers:
  182. return {"tested": 0, "success": 0, "failed": 0, "results": []}
  183. results = []
  184. success_count = 0
  185. failed_count = 0
  186. for provider in providers:
  187. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  188. success, message = await notification_service.send_test_notification(provider.provider_type, config, db)
  189. # Update provider status
  190. if success:
  191. provider.last_success = datetime.now(timezone.utc)
  192. success_count += 1
  193. else:
  194. provider.last_error = message
  195. provider.last_error_at = datetime.now(timezone.utc)
  196. failed_count += 1
  197. results.append(
  198. {
  199. "provider_id": provider.id,
  200. "provider_name": provider.name,
  201. "provider_type": provider.provider_type,
  202. "success": success,
  203. "message": message,
  204. }
  205. )
  206. await db.commit()
  207. return {
  208. "tested": len(providers),
  209. "success": success_count,
  210. "failed": failed_count,
  211. "results": results,
  212. }
  213. # ============================================================================
  214. # Notification Log Routes (must come BEFORE /{provider_id} routes)
  215. # ============================================================================
  216. @router.get("/logs", response_model=list[NotificationLogResponse])
  217. async def get_notification_logs(
  218. limit: int = Query(default=100, ge=1, le=500),
  219. offset: int = Query(default=0, ge=0),
  220. provider_id: int | None = Query(default=None),
  221. event_type: str | None = Query(default=None),
  222. success: bool | None = Query(default=None),
  223. days: int | None = Query(default=7, ge=1, le=90, description="Filter logs from the last N days"),
  224. db: AsyncSession = Depends(get_db),
  225. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  226. ):
  227. """Get notification logs with optional filters."""
  228. query = select(NotificationLog).order_by(desc(NotificationLog.created_at))
  229. # Apply filters
  230. if provider_id is not None:
  231. query = query.where(NotificationLog.provider_id == provider_id)
  232. if event_type is not None:
  233. query = query.where(NotificationLog.event_type == event_type)
  234. if success is not None:
  235. query = query.where(NotificationLog.success == success)
  236. if days is not None:
  237. cutoff = datetime.now(timezone.utc) - timedelta(days=days)
  238. query = query.where(NotificationLog.created_at >= cutoff)
  239. query = query.offset(offset).limit(limit)
  240. result = await db.execute(query)
  241. logs = result.scalars().all()
  242. # Get provider info for each log
  243. response = []
  244. providers_cache: dict[int, NotificationProvider | None] = {}
  245. for log in logs:
  246. if log.provider_id not in providers_cache:
  247. provider_result = await db.execute(
  248. select(NotificationProvider).where(NotificationProvider.id == log.provider_id)
  249. )
  250. providers_cache[log.provider_id] = provider_result.scalar_one_or_none()
  251. provider = providers_cache[log.provider_id]
  252. response.append(
  253. NotificationLogResponse(
  254. id=log.id,
  255. provider_id=log.provider_id,
  256. provider_name=provider.name if provider else None,
  257. provider_type=provider.provider_type if provider else None,
  258. event_type=log.event_type,
  259. title=log.title,
  260. message=log.message,
  261. success=log.success,
  262. error_message=log.error_message,
  263. printer_id=log.printer_id,
  264. printer_name=log.printer_name,
  265. created_at=log.created_at,
  266. )
  267. )
  268. return response
  269. @router.get("/logs/stats", response_model=NotificationLogStats)
  270. async def get_notification_log_stats(
  271. days: int = Query(default=7, ge=1, le=90, description="Statistics for the last N days"),
  272. db: AsyncSession = Depends(get_db),
  273. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  274. ):
  275. """Get notification log statistics."""
  276. cutoff = datetime.now(timezone.utc) - timedelta(days=days)
  277. # Total counts
  278. total_result = await db.execute(select(func.count(NotificationLog.id)).where(NotificationLog.created_at >= cutoff))
  279. total = total_result.scalar() or 0
  280. success_result = await db.execute(
  281. select(func.count(NotificationLog.id)).where(
  282. NotificationLog.created_at >= cutoff, NotificationLog.success.is_(True)
  283. )
  284. )
  285. success_count = success_result.scalar() or 0
  286. # By event type
  287. event_result = await db.execute(
  288. select(NotificationLog.event_type, func.count(NotificationLog.id))
  289. .where(NotificationLog.created_at >= cutoff)
  290. .group_by(NotificationLog.event_type)
  291. )
  292. by_event_type = {row[0]: row[1] for row in event_result.fetchall()}
  293. # By provider (need to join to get name)
  294. provider_result = await db.execute(
  295. select(NotificationProvider.name, func.count(NotificationLog.id))
  296. .join(NotificationProvider, NotificationLog.provider_id == NotificationProvider.id)
  297. .where(NotificationLog.created_at >= cutoff)
  298. .group_by(NotificationProvider.name)
  299. )
  300. by_provider = {row[0]: row[1] for row in provider_result.fetchall()}
  301. return NotificationLogStats(
  302. total=total,
  303. success_count=success_count,
  304. failure_count=total - success_count,
  305. by_event_type=by_event_type,
  306. by_provider=by_provider,
  307. )
  308. @router.delete("/logs")
  309. async def clear_notification_logs(
  310. older_than_days: int = Query(default=30, ge=1, description="Delete logs older than N days"),
  311. db: AsyncSession = Depends(get_db),
  312. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_DELETE),
  313. ):
  314. """Clear old notification logs."""
  315. cutoff = datetime.now(timezone.utc) - timedelta(days=older_than_days)
  316. result = await db.execute(delete(NotificationLog).where(NotificationLog.created_at < cutoff))
  317. await db.commit()
  318. deleted_count = result.rowcount
  319. logger.info("Deleted %s notification logs older than %s days", deleted_count, older_than_days)
  320. return {"deleted": deleted_count, "message": f"Deleted {deleted_count} logs older than {older_than_days} days"}
  321. # ============================================================================
  322. # Provider Instance Routes (parameterized - must come LAST)
  323. # ============================================================================
  324. @router.get("/{provider_id}", response_model=NotificationProviderResponse)
  325. async def get_notification_provider(
  326. provider_id: int,
  327. db: AsyncSession = Depends(get_db),
  328. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  329. ):
  330. """Get a specific notification provider."""
  331. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  332. provider = result.scalar_one_or_none()
  333. if not provider:
  334. raise HTTPException(status_code=404, detail="Notification provider not found")
  335. return _provider_to_dict(provider)
  336. @router.patch("/{provider_id}", response_model=NotificationProviderResponse)
  337. async def update_notification_provider(
  338. provider_id: int,
  339. update_data: NotificationProviderUpdate,
  340. db: AsyncSession = Depends(get_db),
  341. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  342. ):
  343. """Update a notification provider."""
  344. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  345. provider = result.scalar_one_or_none()
  346. if not provider:
  347. raise HTTPException(status_code=404, detail="Notification provider not found")
  348. # Update only provided fields
  349. update_dict = update_data.model_dump(exclude_unset=True)
  350. for key, value in update_dict.items():
  351. if key == "config" and value is not None:
  352. setattr(provider, key, json.dumps(value))
  353. elif key == "provider_type" and value is not None:
  354. setattr(provider, key, value.value)
  355. else:
  356. setattr(provider, key, value)
  357. await db.commit()
  358. await db.refresh(provider)
  359. logger.info("Updated notification provider: %s", provider.name)
  360. return _provider_to_dict(provider)
  361. @router.delete("/{provider_id}")
  362. async def delete_notification_provider(
  363. provider_id: int,
  364. db: AsyncSession = Depends(get_db),
  365. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_DELETE),
  366. ):
  367. """Delete a notification provider."""
  368. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  369. provider = result.scalar_one_or_none()
  370. if not provider:
  371. raise HTTPException(status_code=404, detail="Notification provider not found")
  372. name = provider.name
  373. await db.delete(provider)
  374. await db.commit()
  375. logger.info("Deleted notification provider: %s", name)
  376. return {"message": f"Notification provider '{name}' deleted"}
  377. @router.post("/{provider_id}/test", response_model=NotificationTestResponse)
  378. async def test_notification_provider(
  379. provider_id: int,
  380. db: AsyncSession = Depends(get_db),
  381. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  382. ):
  383. """Send a test notification using an existing provider."""
  384. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  385. provider = result.scalar_one_or_none()
  386. if not provider:
  387. raise HTTPException(status_code=404, detail="Notification provider not found")
  388. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  389. success, message = await notification_service.send_test_notification(provider.provider_type, config, db)
  390. # Update provider status
  391. if success:
  392. provider.last_success = datetime.now(timezone.utc)
  393. else:
  394. provider.last_error = message
  395. provider.last_error_at = datetime.now(timezone.utc)
  396. await db.commit()
  397. return NotificationTestResponse(success=success, message=message)