sendio/backend/app/api/stats.py
2026-01-13 05:17:57 +02:00

80 lines
2.5 KiB
Python

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy import func
from app.db.base import get_db
from app.core.deps import get_current_user
from app.models.user import User
from app.models.contact import Contact
from app.models.campaign import Campaign, CampaignRecipient
from app.models.send_log import SendLog
from app.models.list import List as ContactList
router = APIRouter()
@router.get("")
def get_stats(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""Get dashboard statistics"""
# Count contacts
total_contacts = db.query(func.count(Contact.id)).filter(
Contact.user_id == current_user.id
).scalar()
opted_in_contacts = db.query(func.count(Contact.id)).filter(
Contact.user_id == current_user.id,
Contact.opted_in == True
).scalar()
# Count lists
total_lists = db.query(func.count(ContactList.id)).filter(
ContactList.user_id == current_user.id
).scalar()
# Count campaigns
total_campaigns = db.query(func.count(Campaign.id)).filter(
Campaign.user_id == current_user.id
).scalar()
# Count messages sent
total_sent = db.query(func.count(SendLog.id)).filter(
SendLog.user_id == current_user.id,
SendLog.status == "sent"
).scalar()
# Recent campaigns
recent_campaigns = db.query(Campaign).filter(
Campaign.user_id == current_user.id
).order_by(Campaign.created_at.desc()).limit(5).all()
recent_campaigns_data = []
for campaign in recent_campaigns:
total_recipients = db.query(func.count(CampaignRecipient.id)).filter(
CampaignRecipient.campaign_id == campaign.id
).scalar()
sent_count = db.query(func.count(CampaignRecipient.id)).filter(
CampaignRecipient.campaign_id == campaign.id,
CampaignRecipient.status.in_(["sent", "delivered", "read"])
).scalar()
recent_campaigns_data.append({
"id": campaign.id,
"name": campaign.name,
"status": campaign.status,
"total_recipients": total_recipients,
"sent_count": sent_count,
"created_at": campaign.created_at
})
return {
"total_contacts": total_contacts,
"opted_in_contacts": opted_in_contacts,
"total_lists": total_lists,
"total_campaigns": total_campaigns,
"total_sent": total_sent,
"recent_campaigns": recent_campaigns_data
}