notifications.py 19 KB

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