Spaces:
Running

axeronis commited on
Commit
1f2ca78
·
1 Parent(s): 896afb9

feat: add admin email broadcast and test endpoints

Browse files
Files changed (1) hide show
  1. backend/app/api/admin.py +109 -0
backend/app/api/admin.py CHANGED
@@ -753,4 +753,113 @@ async def make_user_partner(
753
  }
754
 
755
 
 
 
 
 
 
 
 
 
 
 
756
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753
  }
754
 
755
 
756
+ # ============================================================================
757
+ # Email Broadcast
758
+ # ============================================================================
759
+
760
+ class BroadcastEmailRequest(BaseModel):
761
+ subject: str
762
+ html_body: str
763
+ text_body: Optional[str] = None
764
+ target: str = "all" # "all", "active", "trial", "paid"
765
+
766
 
767
+ @router.post("/broadcast-email")
768
+ async def broadcast_email(
769
+ body: BroadcastEmailRequest,
770
+ current_user: User = Depends(get_admin_user),
771
+ session: AsyncSession = Depends(get_async_session)
772
+ ):
773
+ """
774
+ Send email to all users or filtered subset.
775
+ Target options: all, active, trial, paid
776
+ """
777
+ from app.services.email import get_email_service
778
+
779
+ # Build query based on target
780
+ stmt = select(User).where(User.is_verified == True)
781
+
782
+ if body.target == "active":
783
+ # Users with active tenants
784
+ stmt = stmt.join(Tenant, User.tenant_id == Tenant.id).where(
785
+ Tenant.subscription_status == "active"
786
+ )
787
+ elif body.target == "trial":
788
+ stmt = stmt.join(Tenant, User.tenant_id == Tenant.id).where(
789
+ Tenant.subscription_plan == "trial"
790
+ )
791
+ elif body.target == "paid":
792
+ stmt = stmt.join(Tenant, User.tenant_id == Tenant.id).where(
793
+ Tenant.subscription_plan.in_(["start", "growth", "enterprise"])
794
+ )
795
+
796
+ result = await session.execute(stmt)
797
+ users = result.scalars().all()
798
+
799
+ if not users:
800
+ return {"status": "warning", "message": "No users found for target", "sent": 0}
801
+
802
+ email_service = get_email_service()
803
+ sent_count = 0
804
+ failed_count = 0
805
+
806
+ for user in users:
807
+ try:
808
+ success = await email_service.send_email(
809
+ to=[user.email],
810
+ subject=body.subject,
811
+ html_body=body.html_body,
812
+ text_body=body.text_body
813
+ )
814
+ if success:
815
+ sent_count += 1
816
+ else:
817
+ failed_count += 1
818
+ except Exception as e:
819
+ logger.error(f"Failed to send broadcast to {user.email}: {e}")
820
+ failed_count += 1
821
+
822
+ logger.info(f"📧 Broadcast complete: {sent_count} sent, {failed_count} failed")
823
+
824
+ return {
825
+ "status": "success",
826
+ "message": f"Broadcast sent to {sent_count} users",
827
+ "sent": sent_count,
828
+ "failed": failed_count,
829
+ "total_targeted": len(users)
830
+ }
831
+
832
+
833
+ @router.post("/test-email")
834
+ async def test_email(
835
+ current_user: User = Depends(get_admin_user)
836
+ ):
837
+ """Send test email to admin."""
838
+ from app.services.email import get_email_service
839
+ from app.core.config import settings
840
+
841
+ email_service = get_email_service()
842
+
843
+ success = await email_service.send_email(
844
+ to=[current_user.email],
845
+ subject=f"🧪 Test Email - {settings.APP_NAME}",
846
+ html_body=f"""
847
+ <html>
848
+ <body style="font-family: Arial, sans-serif; padding: 20px;">
849
+ <h2>✅ Email Service Working!</h2>
850
+ <p>This is a test email from {settings.APP_NAME}.</p>
851
+ <p>Sent at: {datetime.utcnow().isoformat()}</p>
852
+ <hr>
853
+ <p style="color: #666; font-size: 12px;">
854
+ Email Service: Resend API / Brevo API / SMTP
855
+ </p>
856
+ </body>
857
+ </html>
858
+ """,
859
+ text_body=f"Test email from {settings.APP_NAME}. Sent at: {datetime.utcnow().isoformat()}"
860
+ )
861
+
862
+ if success:
863
+ return {"status": "success", "message": f"Test email sent to {current_user.email}"}
864
+ else:
865
+ return {"status": "error", "message": "Failed to send test email"}