feat: enhance CSV reports with multi-currency columns and country
This commit is contained in:
parent
a4d37fcf1a
commit
f677bc69b0
|
|
@ -46,17 +46,23 @@ class AdminReportService:
|
|||
for uid, rname in ur_rows:
|
||||
user_roles_map.setdefault(uid, []).append(rname)
|
||||
|
||||
# Preload spend and orders count
|
||||
# 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)
|
||||
.group_by(PaymentTransaction.user_id, PaymentTransaction.currency)
|
||||
)).all()
|
||||
tx_summary = {uid: (count, float(total)) for uid, count, total in tx_summary_rows}
|
||||
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(
|
||||
|
|
@ -78,14 +84,20 @@ class AdminReportService:
|
|||
"Account Type",
|
||||
"Status",
|
||||
"Total Orders",
|
||||
"Lifetime Spend",
|
||||
"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, total_spend = tx_summary.get(u.id, (0, 0.0))
|
||||
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 ""
|
||||
|
|
@ -99,7 +111,9 @@ class AdminReportService:
|
|||
user_type,
|
||||
status_label,
|
||||
orders_count,
|
||||
f"{total_spend:.2f}",
|
||||
f"{spend_inr:.2f}",
|
||||
f"{spend_usd:.2f}",
|
||||
f"{spend_eur:.2f}",
|
||||
active_subs,
|
||||
reg_date,
|
||||
])
|
||||
|
|
@ -183,8 +197,10 @@ class AdminReportService:
|
|||
"Customer Name",
|
||||
"Customer Email",
|
||||
"Phone Number",
|
||||
"Customer Country",
|
||||
"Plan Code",
|
||||
"Plan Name",
|
||||
"Plan Currency",
|
||||
"Billing Cycle",
|
||||
"Status",
|
||||
"Days Remaining",
|
||||
|
|
@ -202,6 +218,17 @@ class AdminReportService:
|
|||
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
|
||||
|
|
@ -220,8 +247,10 @@ class AdminReportService:
|
|||
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,
|
||||
|
|
@ -250,10 +279,16 @@ class AdminReportService:
|
|||
"Coupon Code",
|
||||
"Category",
|
||||
"Description",
|
||||
"Discount Value",
|
||||
"Discount Type",
|
||||
"Max Cap",
|
||||
"Min Purchase",
|
||||
"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",
|
||||
|
|
@ -262,10 +297,49 @@ class AdminReportService:
|
|||
"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"
|
||||
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"
|
||||
|
||||
|
|
@ -291,10 +365,16 @@ class AdminReportService:
|
|||
c.code,
|
||||
(c.coupon_category or "general").title(),
|
||||
c.description or "",
|
||||
disc_val,
|
||||
(c.discount_type or "").capitalize(),
|
||||
max_cap,
|
||||
min_spend,
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,159 @@
|
|||
from __future__ import annotations
|
||||
import csv
|
||||
import io
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
|
||||
from app.db.enums import PaymentStatus, SubscriptionStatus
|
||||
from app.db.models import AppUser, AccessPlan, Coupon, PaymentTransaction, UserSubscription
|
||||
from app.features.admin.services.report_service import AdminReportService
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_export_report_csv_customers_multi_currency() -> None:
|
||||
uid = uuid4()
|
||||
mock_user = MagicMock(spec=AppUser)
|
||||
mock_user.id = uid
|
||||
mock_user.display_name = "Jane Doe"
|
||||
mock_user.email = "jane@example.com"
|
||||
mock_user.phone_number = "+4912345678"
|
||||
mock_user.country = "Germany"
|
||||
mock_user.is_active = True
|
||||
mock_user.created_at = datetime(2026, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
|
||||
|
||||
mock_session = AsyncMock()
|
||||
# 1. select users
|
||||
res_users = MagicMock()
|
||||
res_users.scalars.return_value.all.return_value = [mock_user]
|
||||
|
||||
# 2. select user_roles
|
||||
res_roles = MagicMock()
|
||||
res_roles.all.return_value = []
|
||||
|
||||
# 3. select tx_summary_rows (user_id, currency, count, sum)
|
||||
res_tx = MagicMock()
|
||||
res_tx.all.return_value = [
|
||||
(uid, "EUR", 2, Decimal("40.00")),
|
||||
(uid, "INR", 1, Decimal("500.00")),
|
||||
]
|
||||
|
||||
# 4. select sub_count_rows
|
||||
res_sub = MagicMock()
|
||||
res_sub.all.return_value = [(uid, 1)]
|
||||
|
||||
mock_session.execute.side_effect = [res_users, res_roles, res_tx, res_sub]
|
||||
|
||||
svc = AdminReportService(mock_session)
|
||||
response = await svc.export_report_csv("customers", None, None)
|
||||
|
||||
# Read streamed content
|
||||
chunks = [chunk async for chunk in response.body_iterator]
|
||||
csv_text = b"".join(chunks).decode("utf-8")
|
||||
reader = list(csv.reader(io.StringIO(csv_text)))
|
||||
|
||||
headers = reader[0]
|
||||
assert "Lifetime Spend (INR)" in headers
|
||||
assert "Lifetime Spend (USD)" in headers
|
||||
assert "Lifetime Spend (EUR)" in headers
|
||||
|
||||
row = reader[1]
|
||||
assert row[1] == "Jane Doe"
|
||||
assert row[8] == "500.00" # INR
|
||||
assert row[9] == "0.00" # USD
|
||||
assert row[10] == "40.00" # EUR
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_export_report_csv_subscriptions_multi_currency() -> None:
|
||||
mock_sub = MagicMock(spec=UserSubscription)
|
||||
mock_sub.id = uuid4()
|
||||
mock_sub.status = SubscriptionStatus.ACTIVE
|
||||
mock_sub.started_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
mock_sub.expires_at = None
|
||||
mock_sub.payment_reference = "PAY_REF_123"
|
||||
|
||||
mock_plan = MagicMock(spec=AccessPlan)
|
||||
mock_plan.code = "LIFETIME_ALL_EUR"
|
||||
mock_plan.name = "Lifetime All EUR"
|
||||
mock_plan.currency = "EUR"
|
||||
mock_plan.billing_period = None
|
||||
|
||||
mock_user = MagicMock(spec=AppUser)
|
||||
mock_user.display_name = "Hans Muller"
|
||||
mock_user.email = "hans@example.de"
|
||||
mock_user.phone_number = "+4912345"
|
||||
mock_user.country = "Germany"
|
||||
|
||||
mock_session = AsyncMock()
|
||||
res_subs = MagicMock()
|
||||
res_subs.all.return_value = [(mock_sub, mock_plan, mock_user)]
|
||||
mock_session.execute.return_value = res_subs
|
||||
|
||||
svc = AdminReportService(mock_session)
|
||||
response = await svc.export_report_csv("subscriptions", None, None)
|
||||
|
||||
chunks = [chunk async for chunk in response.body_iterator]
|
||||
csv_text = b"".join(chunks).decode("utf-8")
|
||||
reader = list(csv.reader(io.StringIO(csv_text)))
|
||||
|
||||
headers = reader[0]
|
||||
assert "Customer Country" in headers
|
||||
assert "Plan Currency" in headers
|
||||
|
||||
row = reader[1]
|
||||
assert row[4] == "Germany"
|
||||
assert row[7] == "EUR"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_export_report_csv_coupons_multi_currency() -> None:
|
||||
mock_coupon = MagicMock(spec=Coupon)
|
||||
mock_coupon.id = uuid4()
|
||||
mock_coupon.code = "EUR50"
|
||||
mock_coupon.coupon_category = "seasonal"
|
||||
mock_coupon.description = "Winter sale"
|
||||
mock_coupon.discount_type = "flat"
|
||||
mock_coupon.value = Decimal("500.00")
|
||||
mock_coupon.max_discount_limit = Decimal("0.00")
|
||||
mock_coupon.min_purchase_amount = Decimal("1000.00")
|
||||
mock_coupon.usage_count = 5
|
||||
mock_coupon.usage_limit = 100
|
||||
mock_coupon.is_active = True
|
||||
mock_coupon.start_date = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
mock_coupon.end_date = datetime(2026, 12, 31, tzinfo=timezone.utc)
|
||||
mock_coupon.metadata_json = {
|
||||
"currency_values": {"INR": 500.0, "USD": 6.0, "EUR": 5.5},
|
||||
"currency_min_spends": {"INR": 1000.0, "USD": 12.0, "EUR": 11.0},
|
||||
}
|
||||
|
||||
mock_session = AsyncMock()
|
||||
res_coupons = MagicMock()
|
||||
res_coupons.scalars.return_value.all.return_value = [mock_coupon]
|
||||
|
||||
res_redemptions = MagicMock()
|
||||
res_redemptions.all.return_value = [(mock_coupon.id, 5)]
|
||||
|
||||
mock_session.execute.side_effect = [res_coupons, res_redemptions]
|
||||
|
||||
svc = AdminReportService(mock_session)
|
||||
response = await svc.export_report_csv("coupons", None, None)
|
||||
|
||||
chunks = [chunk async for chunk in response.body_iterator]
|
||||
csv_text = b"".join(chunks).decode("utf-8")
|
||||
reader = list(csv.reader(io.StringIO(csv_text)))
|
||||
|
||||
headers = reader[0]
|
||||
assert "Discount (INR)" in headers
|
||||
assert "Discount (USD)" in headers
|
||||
assert "Discount (EUR)" in headers
|
||||
assert "Min Purchase (EUR)" in headers
|
||||
|
||||
row = reader[1]
|
||||
assert row[0] == "EUR50"
|
||||
assert row[4] == "₹500.00"
|
||||
assert row[5] == "$6.00"
|
||||
assert row[6] == "€5.50"
|
||||
assert row[12] == "€11.00"
|
||||
Loading…
Reference in New Issue