Merge pull request 'feat(reports): update and enrich CSV export fields' (#25) from feat/enhanced-csv-reports into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-api/pulls/25
This commit is contained in:
commit
ebfe4ee389
|
|
@ -3,9 +3,19 @@ import csv
|
|||
import io
|
||||
from datetime import datetime, timezone
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.models import AccessPlan, AppUser, Coupon, Invoice, PaymentTransaction, UserSubscription
|
||||
from app.db.enums import PaymentStatus, SubscriptionStatus
|
||||
from app.db.models import (
|
||||
AccessPlan,
|
||||
AppUser,
|
||||
Coupon,
|
||||
Invoice,
|
||||
PaymentTransaction,
|
||||
Role,
|
||||
UserRole,
|
||||
UserSubscription,
|
||||
)
|
||||
|
||||
|
||||
class AdminReportService:
|
||||
|
|
@ -26,15 +36,81 @@ class AdminReportService:
|
|||
if e_dt:
|
||||
q = q.where(AppUser.created_at <= e_dt)
|
||||
users = (await self.session.execute(q)).scalars().all()
|
||||
writer.writerow(["ID", "Email", "Display Name", "Phone Number", "Country", "Active", "Created At"])
|
||||
|
||||
# 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:
|
||||
writer.writerow([str(u.id), u.email, u.display_name or "", u.phone_number or "", u.country, u.is_active, u.created_at.isoformat() if u.created_at else ""])
|
||||
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)
|
||||
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:
|
||||
|
|
@ -42,21 +118,53 @@ class AdminReportService:
|
|||
if e_dt:
|
||||
q = q.where(PaymentTransaction.created_at <= e_dt)
|
||||
rows = (await self.session.execute(q)).all()
|
||||
writer.writerow(["ID", "Gateway ID", "User Email", "User Name", "Amount", "Currency", "Status", "Invoice Number", "Created At"])
|
||||
for t, inv, u in rows:
|
||||
|
||||
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([
|
||||
str(t.id),
|
||||
t.gateway_transaction_id,
|
||||
u.email if u else "",
|
||||
u.display_name if u else "",
|
||||
float(t.amount),
|
||||
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),
|
||||
inv.invoice_number if inv else "",
|
||||
t.created_at.isoformat() if t.created_at else "",
|
||||
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)
|
||||
|
|
@ -68,42 +176,124 @@ class AdminReportService:
|
|||
if e_dt:
|
||||
q = q.where(UserSubscription.started_at <= e_dt)
|
||||
rows = (await self.session.execute(q)).all()
|
||||
writer.writerow(["ID", "User Email", "User Name", "Plan Code", "Plan Name", "Status", "Started At", "Expires At", "Payment Reference"])
|
||||
|
||||
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.email if u else "",
|
||||
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),
|
||||
s.started_at.isoformat() if s.started_at else "",
|
||||
s.expires_at.isoformat() if s.expires_at else "",
|
||||
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()
|
||||
writer.writerow(["ID", "Code", "Discount Type", "Category", "Value", "Max Limit", "Min Purchase", "Usage Limit", "Usage Count", "Active", "Start Date", "End Date"])
|
||||
|
||||
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 = c.usage_count or 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([
|
||||
str(c.id),
|
||||
c.code,
|
||||
c.discount_type,
|
||||
c.coupon_category,
|
||||
float(c.value),
|
||||
float(c.max_discount_limit or 0),
|
||||
float(c.min_purchase_amount or 0),
|
||||
c.usage_limit,
|
||||
c.usage_count,
|
||||
c.is_active,
|
||||
c.start_date.isoformat() if c.start_date else "",
|
||||
c.end_date.isoformat() if c.end_date else "",
|
||||
(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.")
|
||||
|
|
|
|||
Loading…
Reference in New Issue