notifications.py 16 KB

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