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