user_notifications.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. """API routes for user email notification preferences."""
  2. import logging
  3. from fastapi import APIRouter, Depends, HTTPException, status
  4. from sqlalchemy import select
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  7. from backend.app.core.database import get_db
  8. from backend.app.core.permissions import Permission
  9. from backend.app.models.user import User
  10. from backend.app.models.user_email_pref import UserEmailPreference
  11. from backend.app.schemas.user_notifications import UserEmailPreferenceResponse, UserEmailPreferenceUpdate
  12. logger = logging.getLogger(__name__)
  13. router = APIRouter(prefix="/user-notifications", tags=["user-notifications"])
  14. @router.get("/preferences", response_model=UserEmailPreferenceResponse)
  15. async def get_user_email_preferences(
  16. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_USER_EMAIL),
  17. db: AsyncSession = Depends(get_db),
  18. ):
  19. """Get the current user's email notification preferences.
  20. Returns defaults (all enabled) if no preferences are saved yet.
  21. """
  22. if current_user is None:
  23. # Auth is disabled; no user context available, return defaults
  24. return UserEmailPreferenceResponse(
  25. notify_print_start=True,
  26. notify_print_complete=True,
  27. notify_print_failed=True,
  28. notify_print_stopped=True,
  29. )
  30. result = await db.execute(select(UserEmailPreference).where(UserEmailPreference.user_id == current_user.id))
  31. pref = result.scalar_one_or_none()
  32. if pref is None:
  33. # Return defaults
  34. return UserEmailPreferenceResponse(
  35. notify_print_start=True,
  36. notify_print_complete=True,
  37. notify_print_failed=True,
  38. notify_print_stopped=True,
  39. )
  40. return pref
  41. @router.put("/preferences", response_model=UserEmailPreferenceResponse)
  42. async def update_user_email_preferences(
  43. data: UserEmailPreferenceUpdate,
  44. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_USER_EMAIL),
  45. db: AsyncSession = Depends(get_db),
  46. ):
  47. """Update the current user's email notification preferences."""
  48. if current_user is None:
  49. raise HTTPException(
  50. status_code=status.HTTP_400_BAD_REQUEST,
  51. detail="Authentication must be enabled to save user notification preferences",
  52. )
  53. if not current_user.email:
  54. raise HTTPException(
  55. status_code=status.HTTP_400_BAD_REQUEST,
  56. detail="User must have an email address to receive notifications",
  57. )
  58. result = await db.execute(select(UserEmailPreference).where(UserEmailPreference.user_id == current_user.id))
  59. pref = result.scalar_one_or_none()
  60. if pref is None:
  61. pref = UserEmailPreference(
  62. user_id=current_user.id,
  63. notify_print_start=data.notify_print_start,
  64. notify_print_complete=data.notify_print_complete,
  65. notify_print_failed=data.notify_print_failed,
  66. notify_print_stopped=data.notify_print_stopped,
  67. )
  68. db.add(pref)
  69. else:
  70. pref.notify_print_start = data.notify_print_start
  71. pref.notify_print_complete = data.notify_print_complete
  72. pref.notify_print_failed = data.notify_print_failed
  73. pref.notify_print_stopped = data.notify_print_stopped
  74. await db.commit()
  75. await db.refresh(pref)
  76. logger.info(
  77. "Updated email notification preferences for user %s: start=%s, complete=%s, failed=%s, stopped=%s",
  78. current_user.username,
  79. pref.notify_print_start,
  80. pref.notify_print_complete,
  81. pref.notify_print_failed,
  82. pref.notify_print_stopped,
  83. )
  84. return pref