notifications.py 16 KB

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