notifications.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. """API routes for notification providers."""
  2. import json
  3. import logging
  4. import time
  5. from collections import defaultdict, deque
  6. from datetime import datetime, timedelta, timezone
  7. from fastapi import APIRouter, Depends, HTTPException, Query
  8. from sqlalchemy import delete, desc, func, select
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from backend.app.core.auth import RequirePermissionIfAuthEnabled, ScopedCaller, require_notification_send
  11. from backend.app.core.database import get_db
  12. from backend.app.core.permissions import Permission
  13. from backend.app.models.notification import NotificationLog, NotificationProvider
  14. from backend.app.models.user import User
  15. from backend.app.schemas.notification import (
  16. AppMessage,
  17. AppMessageChannel,
  18. AppMessageResult,
  19. NotificationLogResponse,
  20. NotificationLogStats,
  21. NotificationProviderCreate,
  22. NotificationProviderResponse,
  23. NotificationProviderUpdate,
  24. NotificationTestRequest,
  25. NotificationTestResponse,
  26. )
  27. from backend.app.services.notification_service import notification_service
  28. from backend.app.services.telegram_reactions import telegram_reaction_poller
  29. logger = logging.getLogger(__name__)
  30. router = APIRouter(prefix="/notifications", tags=["notifications"])
  31. async def _resync_reaction_poller():
  32. """Start/stop Telegram reaction polls after a provider changed (#3046).
  33. Never fails the request: the provider row is already saved, and the
  34. poller catches up on the next restart at worst.
  35. """
  36. try:
  37. await telegram_reaction_poller.sync()
  38. except Exception as e:
  39. logger.warning("Telegram reaction poller resync failed: %s", e)
  40. def _provider_to_dict(provider: NotificationProvider) -> dict:
  41. """Convert a NotificationProvider model to a response dictionary."""
  42. return {
  43. "id": provider.id,
  44. "name": provider.name,
  45. "provider_type": provider.provider_type,
  46. "enabled": provider.enabled,
  47. "config": json.loads(provider.config) if isinstance(provider.config, str) else provider.config,
  48. # Print lifecycle events
  49. "on_print_start": provider.on_print_start,
  50. "on_print_complete": provider.on_print_complete,
  51. "on_print_failed": provider.on_print_failed,
  52. "on_print_stopped": provider.on_print_stopped,
  53. "on_print_progress": provider.on_print_progress,
  54. "on_print_missing_spool_assignment": provider.on_print_missing_spool_assignment,
  55. "on_billing_charge_failed": provider.on_billing_charge_failed,
  56. # Printer status events
  57. "on_printer_offline": provider.on_printer_offline,
  58. "on_printer_error": provider.on_printer_error,
  59. "on_ai_failure_detection": provider.on_ai_failure_detection,
  60. "on_filament_low": provider.on_filament_low,
  61. "on_maintenance_due": provider.on_maintenance_due,
  62. # Home Assistant sensor alerts (#1148, #2824). Both directions of this
  63. # file are hand-maintained field maps, so a column missing here reads
  64. # back as the schema default (False) no matter what the row holds.
  65. "on_ha_sensor_alert": provider.on_ha_sensor_alert,
  66. "on_location_ha_sensor_alert": provider.on_location_ha_sensor_alert,
  67. # AMS environmental alarms (regular AMS)
  68. "on_ams_humidity_high": provider.on_ams_humidity_high,
  69. "on_ams_temperature_high": provider.on_ams_temperature_high,
  70. "on_ams_drying_suspended": provider.on_ams_drying_suspended,
  71. # AMS-HT environmental alarms
  72. "on_ams_ht_humidity_high": provider.on_ams_ht_humidity_high,
  73. "on_ams_ht_temperature_high": provider.on_ams_ht_temperature_high,
  74. # Build plate detection
  75. "on_plate_not_empty": provider.on_plate_not_empty,
  76. "on_plate_clear_required": provider.on_plate_clear_required,
  77. # Post-print outcome confirmation (#1898)
  78. "on_print_confirm_request": provider.on_print_confirm_request,
  79. # Rows from before #3046 hold NULL here; "buttons" is what they did.
  80. "telegram_verdict_mode": provider.telegram_verdict_mode or "buttons",
  81. # Bed cooled
  82. "on_bed_cooled": provider.on_bed_cooled,
  83. # First layer complete
  84. "on_first_layer_complete": provider.on_first_layer_complete,
  85. # Messages from connected apps
  86. "on_app_message": bool(provider.on_app_message),
  87. # Inventory stock alerts. Absent here, the toggles above always read
  88. # back off no matter what the row holds — the same hand-maintained
  89. # field map the Home Assistant comment warns about.
  90. "on_stock_reorder_alert": provider.on_stock_reorder_alert,
  91. "on_stock_break_alert": provider.on_stock_break_alert,
  92. # Print queue events
  93. "on_queue_job_added": provider.on_queue_job_added,
  94. "on_queue_job_assigned": provider.on_queue_job_assigned,
  95. "on_queue_job_started": provider.on_queue_job_started,
  96. "on_queue_job_waiting": provider.on_queue_job_waiting,
  97. "on_queue_job_skipped": provider.on_queue_job_skipped,
  98. "on_queue_job_failed": provider.on_queue_job_failed,
  99. "on_queue_completed": provider.on_queue_completed,
  100. # Quiet hours
  101. "quiet_hours_enabled": provider.quiet_hours_enabled,
  102. "quiet_hours_start": provider.quiet_hours_start,
  103. "quiet_hours_end": provider.quiet_hours_end,
  104. # Daily digest
  105. "daily_digest_enabled": provider.daily_digest_enabled,
  106. "daily_digest_time": provider.daily_digest_time,
  107. # Printer filter
  108. "printer_id": provider.printer_id,
  109. # Status tracking
  110. "last_success": provider.last_success,
  111. "last_error": provider.last_error,
  112. "last_error_at": provider.last_error_at,
  113. # Timestamps
  114. "created_at": provider.created_at,
  115. "updated_at": provider.updated_at,
  116. }
  117. # ============================================================================
  118. # Provider List/Create Routes (no path parameters)
  119. # ============================================================================
  120. @router.get("/", response_model=list[NotificationProviderResponse])
  121. async def list_notification_providers(
  122. db: AsyncSession = Depends(get_db),
  123. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  124. ):
  125. """List all notification providers."""
  126. result = await db.execute(select(NotificationProvider).order_by(NotificationProvider.created_at.desc()))
  127. providers = result.scalars().all()
  128. return [_provider_to_dict(provider) for provider in providers]
  129. @router.post("/", response_model=NotificationProviderResponse)
  130. async def create_notification_provider(
  131. provider_data: NotificationProviderCreate,
  132. db: AsyncSession = Depends(get_db),
  133. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_CREATE),
  134. ):
  135. """Create a new notification provider."""
  136. provider = NotificationProvider(
  137. name=provider_data.name,
  138. provider_type=provider_data.provider_type.value,
  139. enabled=provider_data.enabled,
  140. config=json.dumps(provider_data.config),
  141. # Print lifecycle events
  142. on_print_start=provider_data.on_print_start,
  143. on_print_complete=provider_data.on_print_complete,
  144. on_print_failed=provider_data.on_print_failed,
  145. on_print_stopped=provider_data.on_print_stopped,
  146. on_print_progress=provider_data.on_print_progress,
  147. on_print_missing_spool_assignment=provider_data.on_print_missing_spool_assignment,
  148. on_billing_charge_failed=provider_data.on_billing_charge_failed,
  149. # Printer status events
  150. on_printer_offline=provider_data.on_printer_offline,
  151. on_printer_error=provider_data.on_printer_error,
  152. on_ai_failure_detection=provider_data.on_ai_failure_detection,
  153. on_filament_low=provider_data.on_filament_low,
  154. on_maintenance_due=provider_data.on_maintenance_due,
  155. # Home Assistant sensor alerts (#1148, #2824)
  156. on_ha_sensor_alert=provider_data.on_ha_sensor_alert,
  157. on_location_ha_sensor_alert=provider_data.on_location_ha_sensor_alert,
  158. # AMS environmental alarms (regular AMS)
  159. on_ams_humidity_high=provider_data.on_ams_humidity_high,
  160. on_ams_temperature_high=provider_data.on_ams_temperature_high,
  161. on_ams_drying_suspended=provider_data.on_ams_drying_suspended,
  162. # AMS-HT environmental alarms
  163. on_ams_ht_humidity_high=provider_data.on_ams_ht_humidity_high,
  164. on_ams_ht_temperature_high=provider_data.on_ams_ht_temperature_high,
  165. # Build plate detection
  166. on_plate_not_empty=provider_data.on_plate_not_empty,
  167. on_plate_clear_required=provider_data.on_plate_clear_required,
  168. # Post-print outcome confirmation (#1898)
  169. on_print_confirm_request=provider_data.on_print_confirm_request,
  170. telegram_verdict_mode=provider_data.telegram_verdict_mode,
  171. # Bed cooled
  172. on_bed_cooled=provider_data.on_bed_cooled,
  173. # First layer complete
  174. on_first_layer_complete=provider_data.on_first_layer_complete,
  175. on_app_message=provider_data.on_app_message,
  176. # Inventory stock alerts
  177. on_stock_reorder_alert=provider_data.on_stock_reorder_alert,
  178. on_stock_break_alert=provider_data.on_stock_break_alert,
  179. # Print queue events
  180. on_queue_job_added=provider_data.on_queue_job_added,
  181. on_queue_job_assigned=provider_data.on_queue_job_assigned,
  182. on_queue_job_started=provider_data.on_queue_job_started,
  183. on_queue_job_waiting=provider_data.on_queue_job_waiting,
  184. on_queue_job_skipped=provider_data.on_queue_job_skipped,
  185. on_queue_job_failed=provider_data.on_queue_job_failed,
  186. on_queue_completed=provider_data.on_queue_completed,
  187. # Quiet hours
  188. quiet_hours_enabled=provider_data.quiet_hours_enabled,
  189. quiet_hours_start=provider_data.quiet_hours_start,
  190. quiet_hours_end=provider_data.quiet_hours_end,
  191. # Daily digest
  192. daily_digest_enabled=provider_data.daily_digest_enabled,
  193. daily_digest_time=provider_data.daily_digest_time,
  194. # Printer filter
  195. printer_id=provider_data.printer_id,
  196. )
  197. db.add(provider)
  198. await db.commit()
  199. await db.refresh(provider)
  200. logger.info("Created notification provider: %s (%s)", provider.name, provider.provider_type)
  201. await _resync_reaction_poller()
  202. return _provider_to_dict(provider)
  203. # ============================================================================
  204. # Static Path Routes (must come BEFORE parameterized routes)
  205. # ============================================================================
  206. @router.post("/test-config", response_model=NotificationTestResponse)
  207. async def test_notification_config(
  208. test_request: NotificationTestRequest,
  209. db: AsyncSession = Depends(get_db),
  210. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_CREATE),
  211. ):
  212. """Test notification configuration before saving."""
  213. success, message = await notification_service.send_test_notification(
  214. test_request.provider_type.value, test_request.config, db
  215. )
  216. return NotificationTestResponse(success=success, message=message)
  217. @router.post("/test-all")
  218. async def test_all_notification_providers(
  219. db: AsyncSession = Depends(get_db),
  220. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  221. ):
  222. """Send a test notification to all enabled providers."""
  223. result = await db.execute(select(NotificationProvider).where(NotificationProvider.enabled.is_(True)))
  224. providers = result.scalars().all()
  225. if not providers:
  226. return {"tested": 0, "success": 0, "failed": 0, "results": []}
  227. results = []
  228. success_count = 0
  229. failed_count = 0
  230. for provider in providers:
  231. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  232. success, message = await notification_service.send_test_notification(provider.provider_type, config, db)
  233. # Update provider status
  234. if success:
  235. provider.last_success = datetime.now(timezone.utc)
  236. success_count += 1
  237. else:
  238. provider.last_error = message
  239. provider.last_error_at = datetime.now(timezone.utc)
  240. failed_count += 1
  241. results.append(
  242. {
  243. "provider_id": provider.id,
  244. "provider_name": provider.name,
  245. "provider_type": provider.provider_type,
  246. "success": success,
  247. "message": message,
  248. }
  249. )
  250. await db.commit()
  251. return {
  252. "tested": len(providers),
  253. "success": success_count,
  254. "failed": failed_count,
  255. "results": results,
  256. }
  257. # ============================================================================
  258. # Notification Log Routes (must come BEFORE /{provider_id} routes)
  259. # ============================================================================
  260. @router.get("/logs", response_model=list[NotificationLogResponse])
  261. async def get_notification_logs(
  262. limit: int = Query(default=100, ge=1, le=500),
  263. offset: int = Query(default=0, ge=0),
  264. provider_id: int | None = Query(default=None),
  265. event_type: str | None = Query(default=None),
  266. success: bool | None = Query(default=None),
  267. days: int | None = Query(default=7, ge=1, le=90, description="Filter logs from the last N days"),
  268. db: AsyncSession = Depends(get_db),
  269. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  270. ):
  271. """Get notification logs with optional filters."""
  272. query = select(NotificationLog).order_by(desc(NotificationLog.created_at))
  273. # Apply filters
  274. if provider_id is not None:
  275. query = query.where(NotificationLog.provider_id == provider_id)
  276. if event_type is not None:
  277. query = query.where(NotificationLog.event_type == event_type)
  278. if success is not None:
  279. query = query.where(NotificationLog.success == success)
  280. if days is not None:
  281. cutoff = datetime.now(timezone.utc) - timedelta(days=days)
  282. query = query.where(NotificationLog.created_at >= cutoff)
  283. query = query.offset(offset).limit(limit)
  284. result = await db.execute(query)
  285. logs = result.scalars().all()
  286. # Get provider info for each log
  287. response = []
  288. providers_cache: dict[int, NotificationProvider | None] = {}
  289. for log in logs:
  290. if log.provider_id not in providers_cache:
  291. provider_result = await db.execute(
  292. select(NotificationProvider).where(NotificationProvider.id == log.provider_id)
  293. )
  294. providers_cache[log.provider_id] = provider_result.scalar_one_or_none()
  295. provider = providers_cache[log.provider_id]
  296. response.append(
  297. NotificationLogResponse(
  298. id=log.id,
  299. provider_id=log.provider_id,
  300. provider_name=provider.name if provider else None,
  301. provider_type=provider.provider_type if provider else None,
  302. event_type=log.event_type,
  303. title=log.title,
  304. message=log.message,
  305. success=log.success,
  306. error_message=log.error_message,
  307. printer_id=log.printer_id,
  308. printer_name=log.printer_name,
  309. created_at=log.created_at,
  310. )
  311. )
  312. return response
  313. @router.get("/logs/stats", response_model=NotificationLogStats)
  314. async def get_notification_log_stats(
  315. days: int = Query(default=7, ge=1, le=90, description="Statistics for the last N days"),
  316. db: AsyncSession = Depends(get_db),
  317. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  318. ):
  319. """Get notification log statistics."""
  320. cutoff = datetime.now(timezone.utc) - timedelta(days=days)
  321. # Total counts
  322. total_result = await db.execute(select(func.count(NotificationLog.id)).where(NotificationLog.created_at >= cutoff))
  323. total = total_result.scalar() or 0
  324. success_result = await db.execute(
  325. select(func.count(NotificationLog.id)).where(
  326. NotificationLog.created_at >= cutoff, NotificationLog.success.is_(True)
  327. )
  328. )
  329. success_count = success_result.scalar() or 0
  330. # By event type
  331. event_result = await db.execute(
  332. select(NotificationLog.event_type, func.count(NotificationLog.id))
  333. .where(NotificationLog.created_at >= cutoff)
  334. .group_by(NotificationLog.event_type)
  335. )
  336. by_event_type = {row[0]: row[1] for row in event_result.fetchall()}
  337. # By provider (need to join to get name)
  338. provider_result = await db.execute(
  339. select(NotificationProvider.name, func.count(NotificationLog.id))
  340. .join(NotificationProvider, NotificationLog.provider_id == NotificationProvider.id)
  341. .where(NotificationLog.created_at >= cutoff)
  342. .group_by(NotificationProvider.name)
  343. )
  344. by_provider = {row[0]: row[1] for row in provider_result.fetchall()}
  345. return NotificationLogStats(
  346. total=total,
  347. success_count=success_count,
  348. failure_count=total - success_count,
  349. by_event_type=by_event_type,
  350. by_provider=by_provider,
  351. )
  352. @router.delete("/logs")
  353. async def clear_notification_logs(
  354. older_than_days: int = Query(default=30, ge=1, description="Delete logs older than N days"),
  355. db: AsyncSession = Depends(get_db),
  356. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_DELETE),
  357. ):
  358. """Clear old notification logs."""
  359. cutoff = datetime.now(timezone.utc) - timedelta(days=older_than_days)
  360. result = await db.execute(delete(NotificationLog).where(NotificationLog.created_at < cutoff))
  361. await db.commit()
  362. deleted_count = result.rowcount
  363. logger.info("Deleted %s notification logs older than %s days", deleted_count, older_than_days)
  364. return {"deleted": deleted_count, "message": f"Deleted {deleted_count} logs older than {older_than_days} days"}
  365. # ============================================================================
  366. # Provider Instance Routes (parameterized - must come LAST)
  367. # ============================================================================
  368. # Messages from other applications -------------------------------------------
  369. # Per caller, in memory: enough for any real app (Bambuddy Orders sends a few a
  370. # day), and a buggy or hostile one can't flood the channels.
  371. APP_MESSAGE_LIMIT = 20
  372. APP_MESSAGE_WINDOW_SECONDS = 60
  373. _app_message_times: dict[str, deque[float]] = defaultdict(deque)
  374. def _app_sender(caller: ScopedCaller) -> tuple[str, str]:
  375. """(rate-limit key, name shown in the log) for whoever sends the message."""
  376. if caller.api_key is not None:
  377. return f"key:{caller.api_key.id}", caller.api_key.name
  378. if caller.user is not None:
  379. return f"user:{caller.user.id}", caller.user.username
  380. return "anonymous", "app"
  381. def _check_app_message_rate(key: str) -> None:
  382. times = _app_message_times[key]
  383. cutoff = time.monotonic() - APP_MESSAGE_WINDOW_SECONDS
  384. while times and times[0] < cutoff:
  385. times.popleft()
  386. if len(times) >= APP_MESSAGE_LIMIT:
  387. raise HTTPException(status_code=429, detail="Too many messages; try again in a minute")
  388. times.append(time.monotonic())
  389. @router.post("/app-message", response_model=AppMessageResult)
  390. async def send_app_message(
  391. data: AppMessage,
  392. db: AsyncSession = Depends(get_db),
  393. caller: ScopedCaller = Depends(require_notification_send()),
  394. ):
  395. """Send a message through every enabled channel that has "Messages from
  396. connected apps" on. For other applications, e.g. Bambuddy Orders; an API
  397. key needs the "Send notifications" permission."""
  398. key, sender = _app_sender(caller)
  399. _check_app_message_rate(key)
  400. channels = await notification_service.on_app_message(
  401. db, sender=sender, title=data.title, message=data.message, url=data.url
  402. )
  403. return AppMessageResult(channels=channels)
  404. @router.get("/app-message/channels", response_model=list[AppMessageChannel])
  405. async def app_message_channels(
  406. db: AsyncSession = Depends(get_db),
  407. _: ScopedCaller = Depends(require_notification_send()),
  408. ):
  409. """The enabled channels that deliver app messages: names and types only,
  410. so an app can tell its user where its messages will arrive."""
  411. rows = await db.execute(
  412. select(NotificationProvider)
  413. .where(NotificationProvider.enabled.is_(True), NotificationProvider.on_app_message.is_(True))
  414. .order_by(NotificationProvider.name)
  415. )
  416. return [AppMessageChannel(name=p.name, provider_type=p.provider_type) for p in rows.scalars()]
  417. @router.get("/{provider_id}", response_model=NotificationProviderResponse)
  418. async def get_notification_provider(
  419. provider_id: int,
  420. db: AsyncSession = Depends(get_db),
  421. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  422. ):
  423. """Get a specific notification provider."""
  424. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  425. provider = result.scalar_one_or_none()
  426. if not provider:
  427. raise HTTPException(status_code=404, detail="Notification provider not found")
  428. return _provider_to_dict(provider)
  429. @router.patch("/{provider_id}", response_model=NotificationProviderResponse)
  430. async def update_notification_provider(
  431. provider_id: int,
  432. update_data: NotificationProviderUpdate,
  433. db: AsyncSession = Depends(get_db),
  434. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  435. ):
  436. """Update a notification provider."""
  437. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  438. provider = result.scalar_one_or_none()
  439. if not provider:
  440. raise HTTPException(status_code=404, detail="Notification provider not found")
  441. # Update only provided fields
  442. update_dict = update_data.model_dump(exclude_unset=True)
  443. for key, value in update_dict.items():
  444. if key == "config" and value is not None:
  445. setattr(provider, key, json.dumps(value))
  446. elif key == "provider_type" and value is not None:
  447. setattr(provider, key, value.value)
  448. else:
  449. setattr(provider, key, value)
  450. await db.commit()
  451. await db.refresh(provider)
  452. logger.info("Updated notification provider: %s", provider.name)
  453. await _resync_reaction_poller()
  454. return _provider_to_dict(provider)
  455. @router.delete("/{provider_id}")
  456. async def delete_notification_provider(
  457. provider_id: int,
  458. db: AsyncSession = Depends(get_db),
  459. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_DELETE),
  460. ):
  461. """Delete a notification provider."""
  462. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  463. provider = result.scalar_one_or_none()
  464. if not provider:
  465. raise HTTPException(status_code=404, detail="Notification provider not found")
  466. name = provider.name
  467. await db.delete(provider)
  468. await db.commit()
  469. logger.info("Deleted notification provider: %s", name)
  470. await _resync_reaction_poller()
  471. return {"message": f"Notification provider '{name}' deleted"}
  472. @router.post("/{provider_id}/test", response_model=NotificationTestResponse)
  473. async def test_notification_provider(
  474. provider_id: int,
  475. db: AsyncSession = Depends(get_db),
  476. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  477. ):
  478. """Send a test notification using an existing provider."""
  479. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  480. provider = result.scalar_one_or_none()
  481. if not provider:
  482. raise HTTPException(status_code=404, detail="Notification provider not found")
  483. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  484. success, message = await notification_service.send_test_notification(provider.provider_type, config, db)
  485. # Update provider status
  486. if success:
  487. provider.last_success = datetime.now(timezone.utc)
  488. else:
  489. provider.last_error = message
  490. provider.last_error_at = datetime.now(timezone.utc)
  491. await db.commit()
  492. return NotificationTestResponse(success=success, message=message)