396 lines
17 KiB
Python
396 lines
17 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 by currency
|
|
tx_summary_rows = (await self.session.execute(
|
|
select(
|
|
PaymentTransaction.user_id,
|
|
PaymentTransaction.currency,
|
|
func.count(PaymentTransaction.id),
|
|
func.coalesce(func.sum(PaymentTransaction.amount), 0)
|
|
)
|
|
.where(PaymentTransaction.status == PaymentStatus.SUCCESS)
|
|
.group_by(PaymentTransaction.user_id, PaymentTransaction.currency)
|
|
)).all()
|
|
tx_orders: dict[any, int] = {}
|
|
tx_spend: dict[any, dict[str, float]] = {}
|
|
for uid, curr, count, total in tx_summary_rows:
|
|
tx_orders[uid] = tx_orders.get(uid, 0) + count
|
|
c_up = (curr or "INR").upper()
|
|
tx_spend.setdefault(uid, {})[c_up] = tx_spend.get(uid, {}).get(c_up, 0.0) + float(total)
|
|
|
|
# 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 (INR)",
|
|
"Lifetime Spend (USD)",
|
|
"Lifetime Spend (EUR)",
|
|
"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 = tx_orders.get(u.id, 0)
|
|
u_spend = tx_spend.get(u.id, {})
|
|
spend_inr = u_spend.get("INR", 0.0)
|
|
spend_usd = u_spend.get("USD", 0.0)
|
|
spend_eur = u_spend.get("EUR", 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"{spend_inr:.2f}",
|
|
f"{spend_usd:.2f}",
|
|
f"{spend_eur:.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",
|
|
"Customer Country",
|
|
"Plan Code",
|
|
"Plan Name",
|
|
"Plan Currency",
|
|
"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"
|
|
|
|
plan_curr = "INR"
|
|
if p:
|
|
if getattr(p, "currency", None):
|
|
plan_curr = str(p.currency).upper()
|
|
elif p.code:
|
|
code_up = p.code.upper()
|
|
if code_up.endswith("_EUR"):
|
|
plan_curr = "EUR"
|
|
elif code_up.endswith("_USD"):
|
|
plan_curr = "USD"
|
|
|
|
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 "",
|
|
u.country if u else "",
|
|
p.code if p else "",
|
|
p.name if p else "",
|
|
plan_curr,
|
|
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 Type",
|
|
"Discount (INR)",
|
|
"Discount (USD)",
|
|
"Discount (EUR)",
|
|
"Max Cap (INR)",
|
|
"Max Cap (USD)",
|
|
"Max Cap (EUR)",
|
|
"Min Purchase (INR)",
|
|
"Min Purchase (USD)",
|
|
"Min Purchase (EUR)",
|
|
"Usage Count",
|
|
"Usage Limit",
|
|
"Remaining Uses",
|
|
"Schedule Status",
|
|
"Start Date",
|
|
"End Date",
|
|
])
|
|
for c in coupons:
|
|
metadata = getattr(c, "metadata_json", {}) if hasattr(c, "metadata_json") else {}
|
|
if not isinstance(metadata, dict):
|
|
metadata = {}
|
|
c_values = metadata.get("currency_values") or {}
|
|
c_caps = metadata.get("currency_caps") or {}
|
|
c_mins = metadata.get("currency_min_spends") or {}
|
|
|
|
val_base = float(c.value) if c.value is not None else 0.0
|
|
is_pct = c.discount_type in {"percentage", "percent"}
|
|
|
|
if is_pct:
|
|
disc_inr = f"{val_base:.2f}%"
|
|
disc_usd = f"{val_base:.2f}%"
|
|
disc_eur = f"{val_base:.2f}%"
|
|
|
|
cap_inr_num = float(c_caps.get("INR", c.max_discount_limit or 0.0))
|
|
cap_usd_num = float(c_caps.get("USD", 0.0)) if "USD" in c_caps and c_caps["USD"] is not None else None
|
|
cap_eur_num = float(c_caps.get("EUR", 0.0)) if "EUR" in c_caps and c_caps["EUR"] is not None else None
|
|
|
|
cap_inr = f"₹{cap_inr_num:.2f}" if cap_inr_num > 0 else "None"
|
|
cap_usd = f"${cap_usd_num:.2f}" if cap_usd_num and cap_usd_num > 0 else "None"
|
|
cap_eur = f"€{cap_eur_num:.2f}" if cap_eur_num and cap_eur_num > 0 else "None"
|
|
else:
|
|
v_inr = float(c_values.get("INR", val_base))
|
|
v_usd = float(c_values["USD"]) if "USD" in c_values and c_values["USD"] is not None else None
|
|
v_eur = float(c_values["EUR"]) if "EUR" in c_values and c_values["EUR"] is not None else None
|
|
|
|
disc_inr = f"₹{v_inr:.2f}"
|
|
disc_usd = f"${v_usd:.2f}" if v_usd is not None else "—"
|
|
disc_eur = f"€{v_eur:.2f}" if v_eur is not None else "—"
|
|
|
|
cap_inr = "N/A (Flat)"
|
|
cap_usd = "N/A (Flat)"
|
|
cap_eur = "N/A (Flat)"
|
|
|
|
min_inr_num = float(c_mins.get("INR", c.min_purchase_amount or 0.0))
|
|
min_usd_num = float(c_mins.get("USD", 0.0)) if "USD" in c_mins and c_mins["USD"] is not None else None
|
|
min_eur_num = float(c_mins.get("EUR", 0.0)) if "EUR" in c_mins and c_mins["EUR"] is not None else None
|
|
|
|
min_inr = f"₹{min_inr_num:.2f}" if min_inr_num > 0 else "0.00"
|
|
min_usd = f"${min_usd_num:.2f}" if min_usd_num and min_usd_num > 0 else "0.00"
|
|
min_eur = f"€{min_eur_num:.2f}" if min_eur_num and min_eur_num > 0 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 = "Fully Redeemed"
|
|
|
|
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 "",
|
|
(c.discount_type or "").capitalize(),
|
|
disc_inr,
|
|
disc_usd,
|
|
disc_eur,
|
|
cap_inr,
|
|
cap_usd,
|
|
cap_eur,
|
|
min_inr,
|
|
min_usd,
|
|
min_eur,
|
|
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}"'}
|
|
)
|