283 lines
12 KiB
Python
283 lines
12 KiB
Python
from __future__ import annotations
|
|
from datetime import datetime, timezone
|
|
from uuid import UUID
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy.orm import selectinload
|
|
from app.db.enums import PaymentStatus, SubscriptionStatus
|
|
from app.db.models import (
|
|
AccessPlan,
|
|
AccessPlanModule,
|
|
AppUser,
|
|
Invoice,
|
|
Module,
|
|
PaymentTransaction,
|
|
Role,
|
|
UserRole,
|
|
UserSubscription,
|
|
)
|
|
from ..schema import AdminCreateSuperAdminRequest, AdminPromoteUserRequest, AdminUserListResponse
|
|
from app.features.auth.security import hash_password, validate_password_strength
|
|
from app.features.payments import get_razorpay_service
|
|
|
|
|
|
class AdminCustomerService:
|
|
def __init__(self, session: AsyncSession) -> None:
|
|
self.session = session
|
|
|
|
async def list_users(self, super_admin_only: bool) -> list[AdminUserListResponse]:
|
|
users = (await self.session.execute(select(AppUser).order_by(AppUser.email))).scalars().all()
|
|
out: list[AdminUserListResponse] = []
|
|
for user in users:
|
|
roles = list((await self.session.execute(
|
|
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
|
|
)).scalars().all())
|
|
if super_admin_only != ("super_admin" in roles):
|
|
continue
|
|
subs = (await self.session.execute(
|
|
select(UserSubscription, AccessPlan)
|
|
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
|
.where(UserSubscription.user_id == user.id, UserSubscription.status != SubscriptionStatus.PENDING)
|
|
.order_by(UserSubscription.started_at.desc())
|
|
)).all()
|
|
out.append(
|
|
AdminUserListResponse(
|
|
id=user.id,
|
|
email=user.email,
|
|
display_name=user.display_name,
|
|
phone_number=user.phone_number,
|
|
country=user.country,
|
|
is_active=user.is_active,
|
|
roles=roles,
|
|
external_ref=user.external_ref,
|
|
subscriptions=[
|
|
{
|
|
"id": str(s.id),
|
|
"plan_code": p.code if p else "UNKNOWN",
|
|
"plan_name": p.name if p else "Unknown Access Plan",
|
|
"status": getattr(s.status, "value", s.status),
|
|
"started_at": s.started_at.isoformat() if s.started_at else None,
|
|
"expires_at": s.expires_at.isoformat() if s.expires_at else None,
|
|
"payment_reference": s.payment_reference,
|
|
}
|
|
for s, p in subs
|
|
],
|
|
created_at=user.created_at.isoformat() if user.created_at else None,
|
|
)
|
|
)
|
|
return out
|
|
|
|
async def promote(self, request: AdminPromoteUserRequest, admin: AppUser) -> dict:
|
|
user = (await self.session.execute(
|
|
select(AppUser).where(AppUser.email == str(request.email).lower())
|
|
)).scalar_one_or_none()
|
|
if not user:
|
|
raise LookupError("The specified user account could not be found.")
|
|
role = (await self.session.execute(
|
|
select(Role).where(Role.role_name == "super_admin")
|
|
)).scalar_one_or_none()
|
|
if not role:
|
|
raise RuntimeError("The super_admin system role was not found in the database.")
|
|
exists = (await self.session.execute(
|
|
select(UserRole.user_id).where(UserRole.user_id == user.id, UserRole.role_id == role.id)
|
|
)).scalar_one_or_none()
|
|
if exists:
|
|
return {"status": "already_admin", "message": f"{request.email} is already a Super Admin."}
|
|
self.session.add(UserRole(user_id=user.id, role_id=role.id, assigned_by=admin.id))
|
|
await self._ensure_rzp_customer(user)
|
|
await self.session.commit()
|
|
return {"status": "success", "message": f"Successfully promoted {request.email} to Super Admin."}
|
|
|
|
async def create_super_admin(self, request: AdminCreateSuperAdminRequest, admin: AppUser) -> dict:
|
|
email = str(request.email).lower()
|
|
if (await self.session.execute(select(AppUser.id).where(AppUser.email == email))).scalar_one_or_none():
|
|
raise ValueError("An account with this email address is already registered.")
|
|
validate_password_strength(request.password)
|
|
user = AppUser(
|
|
email=email,
|
|
password_hash=hash_password(request.password),
|
|
display_name=request.display_name or email.split("@")[0].title(),
|
|
phone_number=request.phone_number,
|
|
country="India",
|
|
preferred_language="en",
|
|
is_active=True,
|
|
)
|
|
self.session.add(user)
|
|
await self.session.flush()
|
|
roles = (await self.session.execute(
|
|
select(Role).where(Role.role_name.in_(["practitioner", "super_admin"]))
|
|
)).scalars().all()
|
|
for role in roles:
|
|
self.session.add(UserRole(user_id=user.id, role_id=role.id, assigned_by=admin.id))
|
|
await self._ensure_rzp_customer(user)
|
|
await self.session.commit()
|
|
return {"status": "success", "message": f"Successfully created new Super Admin account: {email}"}
|
|
|
|
async def get_customer_detail(self, user_id: str) -> dict:
|
|
try:
|
|
uid = UUID(user_id)
|
|
except ValueError:
|
|
raise ValueError("Invalid customer UUID format.")
|
|
|
|
user = (await self.session.execute(
|
|
select(AppUser)
|
|
.options(
|
|
selectinload(AppUser.billing_profiles),
|
|
)
|
|
.where(AppUser.id == uid)
|
|
)).scalar_one_or_none()
|
|
if not user:
|
|
raise LookupError("Customer not found.")
|
|
|
|
roles = list((await self.session.execute(
|
|
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == uid)
|
|
)).scalars().all())
|
|
|
|
now = datetime.now(timezone.utc)
|
|
sub_rows = (await self.session.execute(
|
|
select(UserSubscription, AccessPlan)
|
|
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
|
.where(UserSubscription.user_id == uid)
|
|
.order_by(UserSubscription.started_at.desc())
|
|
)).all()
|
|
|
|
subs_data: list[dict] = []
|
|
for s, plan in sub_rows:
|
|
modules: list[dict] = []
|
|
if plan:
|
|
mod_rows = (await self.session.execute(
|
|
select(Module)
|
|
.join(AccessPlanModule, AccessPlanModule.module_id == Module.id)
|
|
.where(AccessPlanModule.plan_id == plan.id)
|
|
)).scalars().all()
|
|
modules = [{"id": str(m.id), "name": m.name, "code": m.code or "", "slug": m.slug} for m in mod_rows]
|
|
|
|
rem_days = None
|
|
is_expired = False
|
|
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
|
|
rem_days = delta
|
|
is_expired = delta < 0
|
|
|
|
p_name = plan.name if plan else "Custom Plan"
|
|
p_code = plan.code if plan else "CUSTOM"
|
|
subs_data.append({
|
|
"id": str(s.id),
|
|
"status": getattr(s.status, "value", s.status),
|
|
"plan_name": p_name,
|
|
"plan_code": p_code,
|
|
"started_at": s.started_at.isoformat() if s.started_at else None,
|
|
"expires_at": s.expires_at.isoformat() if s.expires_at else None,
|
|
"remaining_days": rem_days,
|
|
"is_expired": is_expired,
|
|
"auto_renew": False,
|
|
"plan": {
|
|
"id": str(plan.id) if plan else None,
|
|
"code": p_code,
|
|
"name": p_name,
|
|
"billing_period": getattr(plan.billing_period, "value", plan.billing_period) if plan else "lifetime",
|
|
"modules_count": len(modules),
|
|
"modules": modules,
|
|
},
|
|
})
|
|
|
|
tx_rows = (await self.session.execute(
|
|
select(PaymentTransaction, Invoice)
|
|
.join(Invoice, Invoice.payment_transaction_id == PaymentTransaction.id, isouter=True)
|
|
.where(PaymentTransaction.user_id == uid)
|
|
.order_by(PaymentTransaction.created_at.desc())
|
|
)).all()
|
|
|
|
txs_data: list[dict] = []
|
|
total_spent = 0.0
|
|
spent_by_curr: dict[str, float] = {}
|
|
for t, inv in tx_rows:
|
|
amt = float(t.amount)
|
|
if t.status == PaymentStatus.SUCCESS:
|
|
total_spent += amt
|
|
c = t.currency or "INR"
|
|
spent_by_curr[c] = spent_by_curr.get(c, 0.0) + amt
|
|
|
|
txs_data.append({
|
|
"id": str(t.id),
|
|
"gateway_name": t.gateway_name,
|
|
"gateway_transaction_id": t.gateway_transaction_id,
|
|
"status": getattr(t.status, "value", t.status),
|
|
"amount": amt,
|
|
"currency": t.currency,
|
|
"invoice_number": inv.invoice_number if inv else None,
|
|
"created_at": t.created_at.isoformat() if t.created_at else None,
|
|
})
|
|
|
|
billing_data = [
|
|
{
|
|
"id": str(b.id),
|
|
"label": b.label,
|
|
"billing_name": b.billing_name,
|
|
"billing_email": b.billing_email,
|
|
"billing_phone": b.billing_phone,
|
|
"address_line1": b.address_line1,
|
|
"address_line2": b.address_line2,
|
|
"city": b.city,
|
|
"state": b.state,
|
|
"postal_code": b.postal_code,
|
|
"country": b.country,
|
|
"is_default": b.is_default,
|
|
}
|
|
for b in user.billing_profiles
|
|
]
|
|
|
|
primary_curr = "INR" if (spent_by_curr.get("INR", 0) >= spent_by_curr.get("USD", 0)) else "USD"
|
|
|
|
return {
|
|
"id": str(user.id),
|
|
"email": user.email,
|
|
"display_name": user.display_name,
|
|
"phone_number": user.phone_number,
|
|
"country": user.country,
|
|
"is_active": user.is_active,
|
|
"roles": roles,
|
|
"external_ref": user.external_ref,
|
|
"created_at": user.created_at.isoformat() if user.created_at else None,
|
|
"total_spent": total_spent,
|
|
"currency": primary_curr,
|
|
"total_orders": len(txs_data),
|
|
"subscriptions": subs_data,
|
|
"transactions": txs_data,
|
|
"billing_profiles": billing_data,
|
|
}
|
|
|
|
async def update_customer_status(self, user_id: str, is_active: bool, admin: AppUser) -> dict:
|
|
try:
|
|
uid = UUID(user_id)
|
|
except ValueError:
|
|
raise ValueError("Invalid customer UUID.")
|
|
if admin.id == uid and not is_active:
|
|
raise ValueError("You cannot suspend your own administrative account.")
|
|
|
|
user = (await self.session.execute(select(AppUser).where(AppUser.id == uid))).scalar_one_or_none()
|
|
if not user:
|
|
raise LookupError("Customer not found.")
|
|
|
|
user.is_active = is_active
|
|
await self.session.commit()
|
|
return {
|
|
"status": "success",
|
|
"user_id": str(user.id),
|
|
"is_active": user.is_active,
|
|
"message": f"Customer account '{user.email}' has been {'activated' if user.is_active else 'suspended'}.",
|
|
}
|
|
|
|
async def _ensure_rzp_customer(self, user: AppUser) -> None:
|
|
if user.external_ref:
|
|
return
|
|
try:
|
|
user.external_ref = get_razorpay_service().create_customer(
|
|
name=user.display_name or user.email,
|
|
email=user.email,
|
|
phone=user.phone_number,
|
|
).get("id")
|
|
except Exception:
|
|
pass
|