acupedia-api/app/features/admin/services/report_service.py

316 lines
13 KiB
Python

from __future__ import annotations
import csv
import io
from datetime import datetime, timezone
from fastapi.responses import StreamingResponse
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import PaymentStatus, SubscriptionStatus
from app.db.models import (
AccessPlan,
AppUser,
Coupon,
CouponRedemption,
Invoice,
PaymentTransaction,
Role,
UserRole,
UserSubscription,
)
class AdminReportService:
def __init__(self, session: AsyncSession) -> None:
self.session = session
async def export_report_csv(self, report_type: str, start_date: str | None, end_date: str | None) -> StreamingResponse:
s_dt = datetime.strptime(start_date, "%Y-%m-%d").replace(tzinfo=timezone.utc) if start_date else None
e_dt = datetime.strptime(end_date, "%Y-%m-%d").replace(hour=23, minute=59, second=59, tzinfo=timezone.utc) if end_date else None
output = io.StringIO()
writer = csv.writer(output)
if report_type == "customers":
q = select(AppUser).order_by(AppUser.created_at.desc())
if s_dt:
q = q.where(AppUser.created_at >= s_dt)
if e_dt:
q = q.where(AppUser.created_at <= e_dt)
users = (await self.session.execute(q)).scalars().all()
# Preload user roles
user_roles_map: dict[any, list[str]] = {}
ur_rows = (await self.session.execute(
select(UserRole.user_id, Role.role_name).join(Role, Role.id == UserRole.role_id)
)).all()
for uid, rname in ur_rows:
user_roles_map.setdefault(uid, []).append(rname)
# Preload spend and orders count
tx_summary_rows = (await self.session.execute(
select(
PaymentTransaction.user_id,
func.count(PaymentTransaction.id),
func.coalesce(func.sum(PaymentTransaction.amount), 0)
)
.where(PaymentTransaction.status == PaymentStatus.SUCCESS)
.group_by(PaymentTransaction.user_id)
)).all()
tx_summary = {uid: (count, float(total)) for uid, count, total in tx_summary_rows}
# Preload active subscriptions count
sub_count_rows = (await self.session.execute(
select(
UserSubscription.user_id,
func.count(UserSubscription.id)
)
.where(UserSubscription.status == SubscriptionStatus.ACTIVE)
.group_by(UserSubscription.user_id)
)).all()
sub_count_map = {uid: count for uid, count in sub_count_rows}
writer.writerow([
"Customer ID",
"Full Name",
"Email Address",
"Phone Number",
"Country",
"Account Type",
"Status",
"Total Orders",
"Lifetime Spend",
"Active Subscriptions",
"Registration Date",
])
for u in users:
user_roles = user_roles_map.get(u.id, [])
user_type = "Admin" if any("admin" in str(r).lower() for r in user_roles) else "Practitioner"
orders_count, total_spend = tx_summary.get(u.id, (0, 0.0))
active_subs = sub_count_map.get(u.id, 0)
status_label = "Active" if u.is_active else "Suspended"
reg_date = u.created_at.strftime("%Y-%m-%d %H:%M:%S") if u.created_at else ""
writer.writerow([
str(u.id),
u.display_name or "",
u.email,
u.phone_number or "",
u.country or "",
user_type,
status_label,
orders_count,
f"{total_spend:.2f}",
active_subs,
reg_date,
])
elif report_type == "payments":
q = (
select(PaymentTransaction, Invoice, AppUser, UserSubscription, AccessPlan, Coupon)
.join(Invoice, Invoice.payment_transaction_id == PaymentTransaction.id, isouter=True)
.join(AppUser, AppUser.id == PaymentTransaction.user_id, isouter=True)
.join(UserSubscription, UserSubscription.id == PaymentTransaction.subscription_id, isouter=True)
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
.join(Coupon, Coupon.id == Invoice.applied_coupon_id, isouter=True)
.order_by(PaymentTransaction.created_at.desc())
)
if s_dt:
q = q.where(PaymentTransaction.created_at >= s_dt)
if e_dt:
q = q.where(PaymentTransaction.created_at <= e_dt)
rows = (await self.session.execute(q)).all()
writer.writerow([
"Payment ID",
"Invoice Number",
"Customer Name",
"Customer Email",
"Phone Number",
"Country",
"Plan Code",
"Plan Name",
"Base Price",
"Discount Amount",
"Coupon Code",
"Net Paid",
"Currency",
"Status",
"Payment Date",
])
for t, inv, u, sub, plan, cpn in rows:
base_price = float(inv.base_amount) if inv and inv.base_amount is not None else float(t.amount)
discount_amt = float(inv.discount_amount) if inv and inv.discount_amount is not None else 0.0
coupon_code = cpn.code if cpn else (inv.applied_coupon.code if inv and getattr(inv, "applied_coupon", None) else "")
plan_code = plan.code if plan else ""
plan_name = plan.name if plan else ""
net_paid = float(t.amount)
pay_date = t.created_at.strftime("%Y-%m-%d %H:%M:%S") if t.created_at else ""
writer.writerow([
t.gateway_transaction_id or str(t.id),
inv.invoice_number if inv else "",
u.display_name if u else (inv.billing_name if inv else ""),
u.email if u else (inv.billing_email if inv else ""),
u.phone_number if u else "",
u.country if u else "",
plan_code,
plan_name,
f"{base_price:.2f}",
f"{discount_amt:.2f}",
coupon_code or "None",
f"{net_paid:.2f}",
t.currency,
getattr(t.status, "value", t.status),
pay_date,
])
elif report_type == "subscriptions":
now = datetime.now(timezone.utc)
q = (
select(UserSubscription, AccessPlan, AppUser)
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
.join(AppUser, AppUser.id == UserSubscription.user_id, isouter=True)
.order_by(UserSubscription.started_at.desc())
)
if s_dt:
q = q.where(UserSubscription.started_at >= s_dt)
if e_dt:
q = q.where(UserSubscription.started_at <= e_dt)
rows = (await self.session.execute(q)).all()
writer.writerow([
"Subscription ID",
"Customer Name",
"Customer Email",
"Phone Number",
"Plan Code",
"Plan Name",
"Billing Cycle",
"Status",
"Days Remaining",
"Auto Renew",
"Activation Date",
"Expiry Date",
"Payment Reference",
])
for s, p, u in rows:
billing_cycle = ""
if p and p.billing_period:
billing_cycle = getattr(p.billing_period, "value", str(p.billing_period)).capitalize()
elif hasattr(s, "billing_period") and s.billing_period:
billing_cycle = getattr(s.billing_period, "value", str(s.billing_period)).capitalize()
else:
billing_cycle = "Yearly"
days_remaining = "Lifetime"
if s.expires_at:
exp = s.expires_at.replace(tzinfo=timezone.utc) if s.expires_at.tzinfo is None else s.expires_at
delta = (exp - now).days
if delta >= 0:
days_remaining = f"{delta} days left"
else:
days_remaining = f"Expired ({abs(delta)} days ago)"
auto_renew = "Yes" if getattr(s, "auto_renew", False) else "No"
started = s.started_at.strftime("%Y-%m-%d %H:%M:%S") if s.started_at else ""
expires = s.expires_at.strftime("%Y-%m-%d %H:%M:%S") if s.expires_at else "Lifetime"
writer.writerow([
str(s.id),
u.display_name if u else "",
u.email if u else "",
u.phone_number if u else "",
p.code if p else "",
p.name if p else "",
billing_cycle,
getattr(s.status, "value", s.status),
days_remaining,
auto_renew,
started,
expires,
s.payment_reference or "",
])
elif report_type == "coupons":
now = datetime.now(timezone.utc)
q = select(Coupon).order_by(Coupon.created_at.desc())
if s_dt:
q = q.where(Coupon.created_at >= s_dt)
if e_dt:
q = q.where(Coupon.created_at <= e_dt)
coupons = (await self.session.execute(q)).scalars().all()
redemptions_q = await self.session.execute(
select(CouponRedemption.coupon_id, func.count(CouponRedemption.id))
.group_by(CouponRedemption.coupon_id)
)
redemption_counts = {cid: cnt for cid, cnt in redemptions_q.all()}
writer.writerow([
"Coupon Code",
"Category",
"Description",
"Discount Value",
"Discount Type",
"Max Cap",
"Min Purchase",
"Usage Count",
"Usage Limit",
"Remaining Uses",
"Schedule Status",
"Start Date",
"End Date",
])
for c in coupons:
val = float(c.value) if c.value is not None else 0.0
disc_val = f"{val:.2f}%" if c.discount_type == "percentage" else f"{val:.2f}"
max_cap = f"{float(c.max_discount_limit):.2f}" if c.max_discount_limit else "None"
min_spend = f"{float(c.min_purchase_amount):.2f}" if c.min_purchase_amount else "0.00"
usage_count = max(c.usage_count or 0, redemption_counts.get(c.id, 0))
usage_limit_str = str(c.usage_limit) if c.usage_limit else "Unlimited"
remaining_str = "Unlimited"
if c.usage_limit:
rem = max(0, c.usage_limit - usage_count)
remaining_str = f"{rem} left"
schedule_status = "Active"
if not c.is_active:
schedule_status = "Inactive"
elif c.start_date and c.start_date > now:
schedule_status = "Scheduled"
elif c.end_date and c.end_date < now:
schedule_status = "Expired"
elif c.usage_limit and usage_count >= c.usage_limit:
schedule_status = "Exhausted"
start_str = c.start_date.strftime("%Y-%m-%d") if c.start_date else "Immediate"
end_str = c.end_date.strftime("%Y-%m-%d") if c.end_date else "No Expiry"
writer.writerow([
c.code,
(c.coupon_category or "general").title(),
c.description or "",
disc_val,
(c.discount_type or "").capitalize(),
max_cap,
min_spend,
usage_count,
usage_limit_str,
remaining_str,
schedule_status,
start_str,
end_str,
])
else:
raise ValueError(f"Unknown report type: '{report_type}'. Supported: customers, payments, subscriptions, coupons.")
content = output.getvalue()
output.close()
filename = f"{report_type}_report_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}.csv"
return StreamingResponse(
io.BytesIO(content.encode("utf-8")),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{filename}"'}
)