added-updated-apis #1
|
|
@ -1,99 +1,524 @@
|
|||
from __future__ import annotations
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from fastapi.responses import HTMLResponse, StreamingResponse
|
||||
from app.db.models import AppUser
|
||||
from app.features.payments import get_razorpay_service
|
||||
from .deps import get_admin_service, get_current_admin
|
||||
from .schema import AdminCreateSuperAdminRequest, AdminPromoteUserRequest, AdminRefundRequest, AdminRefundResponse, AdminSyncResponse, AdminUserListResponse
|
||||
from .schema import (
|
||||
AdminCreateSuperAdminRequest,
|
||||
AdminPromoteUserRequest,
|
||||
AdminRefundRequest,
|
||||
AdminRefundResponse,
|
||||
AdminSyncResponse,
|
||||
AdminUserListResponse,
|
||||
CreateCouponRequest,
|
||||
CreatePlanRequest,
|
||||
CustomerStatusUpdateRequest,
|
||||
ModuleStatusUpdateRequest,
|
||||
ModuleUpdateRequest,
|
||||
PlanPricingUpdateRequest,
|
||||
PlanStatusUpdateRequest,
|
||||
UpdateCouponRequest,
|
||||
)
|
||||
from .service import AdminService
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["Administrative Portal"])
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# REFUND & SYNC
|
||||
# =============================================================================
|
||||
|
||||
@router.post("/refund", response_model=AdminRefundResponse)
|
||||
async def process_admin_refund(payload: AdminRefundRequest, admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
try: return await service.process_refund(payload, admin)
|
||||
except LookupError as exc: raise HTTPException(404, detail=str(exc)) from exc
|
||||
except ValueError as exc: raise HTTPException(400, detail=str(exc)) from exc
|
||||
except RuntimeError as exc: raise HTTPException(503, detail=str(exc)) from exc
|
||||
except Exception as exc: raise HTTPException(502, detail=f"Razorpay refunds gateway execution failed: {exc}") from exc
|
||||
async def process_admin_refund(
|
||||
payload: AdminRefundRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.process_refund(payload, admin)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(503, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(502, detail=f"Razorpay refunds gateway execution failed: {exc}") from exc
|
||||
|
||||
|
||||
@router.post("/force-sync", response_model=AdminSyncResponse)
|
||||
async def admin_force_sync_gateway(admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
try: return await service.force_sync()
|
||||
except RuntimeError as exc: raise HTTPException(503, detail=str(exc)) from exc
|
||||
async def admin_force_sync_gateway(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.force_sync()
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(503, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# RAZORPAY READOUTS
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/razorpay/customers")
|
||||
async def list_razorpay_customers(admin: AppUser = Depends(get_current_admin)):
|
||||
try:
|
||||
items = get_razorpay_service().client.customer.all({"count":100}).get("items", [])
|
||||
return {"status":"success","count":len(items),"customers":[{"id":c.get("id"),"name":c.get("name"),"email":c.get("email"),"contact":c.get("contact"),"created_at":c.get("created_at")} for c in items]}
|
||||
items = get_razorpay_service().client.customer.all({"count": 100}).get("items", [])
|
||||
return {
|
||||
"status": "success",
|
||||
"count": len(items),
|
||||
"customers": [
|
||||
{
|
||||
"id": c.get("id"),
|
||||
"name": c.get("name"),
|
||||
"email": c.get("email"),
|
||||
"contact": c.get("contact"),
|
||||
"created_at": c.get("created_at"),
|
||||
}
|
||||
for c in items
|
||||
],
|
||||
}
|
||||
except Exception as exc:
|
||||
return {"status":"error","count":0,"customers":[],"error":str(exc)}
|
||||
return {"status": "error", "count": 0, "customers": [], "error": str(exc)}
|
||||
|
||||
|
||||
@router.get("/razorpay/plans")
|
||||
async def list_razorpay_plans(admin: AppUser = Depends(get_current_admin)):
|
||||
try:
|
||||
items = get_razorpay_service().client.plan.all({"count":100}).get("items", [])
|
||||
return {"status":"success","count":len(items),"plans":[{"id":x.get("id"),"period":x.get("period"),"interval":x.get("interval"),"item_name":(x.get("item") or {}).get("name"),"item_amount":(x.get("item") or {}).get("amount"),"item_currency":(x.get("item") or {}).get("currency"),"created_at":x.get("created_at")} for x in items]}
|
||||
items = get_razorpay_service().client.plan.all({"count": 100}).get("items", [])
|
||||
return {
|
||||
"status": "success",
|
||||
"count": len(items),
|
||||
"plans": [
|
||||
{
|
||||
"id": x.get("id"),
|
||||
"period": x.get("period"),
|
||||
"interval": x.get("interval"),
|
||||
"item_name": (x.get("item") or {}).get("name"),
|
||||
"item_amount": (x.get("item") or {}).get("amount"),
|
||||
"item_currency": (x.get("item") or {}).get("currency"),
|
||||
"created_at": x.get("created_at"),
|
||||
}
|
||||
for x in items
|
||||
],
|
||||
}
|
||||
except Exception as exc:
|
||||
return {"status":"error","count":0,"plans":[],"error":str(exc)}
|
||||
return {"status": "error", "count": 0, "plans": [], "error": str(exc)}
|
||||
|
||||
|
||||
@router.get("/razorpay/subscriptions")
|
||||
async def list_razorpay_subscriptions(admin: AppUser = Depends(get_current_admin)):
|
||||
try:
|
||||
items = get_razorpay_service().client.subscription.all({"count":100}).get("items", [])
|
||||
return {"status":"success","count":len(items),"subscriptions":[{"id":x.get("id"),"plan_id":x.get("plan_id"),"customer_id":x.get("customer_id"),"status":x.get("status"),"total_count":x.get("total_count"),"paid_count":x.get("paid_count"),"current_start":x.get("current_start"),"current_end":x.get("current_end"),"created_at":x.get("created_at")} for x in items]}
|
||||
items = get_razorpay_service().client.subscription.all({"count": 100}).get("items", [])
|
||||
return {
|
||||
"status": "success",
|
||||
"count": len(items),
|
||||
"subscriptions": [
|
||||
{
|
||||
"id": x.get("id"),
|
||||
"plan_id": x.get("plan_id"),
|
||||
"customer_id": x.get("customer_id"),
|
||||
"status": x.get("status"),
|
||||
"total_count": x.get("total_count"),
|
||||
"paid_count": x.get("paid_count"),
|
||||
"current_start": x.get("current_start"),
|
||||
"current_end": x.get("current_end"),
|
||||
"created_at": x.get("created_at"),
|
||||
}
|
||||
for x in items
|
||||
],
|
||||
}
|
||||
except Exception as exc:
|
||||
return {"status":"error","count":0,"subscriptions":[],"error":str(exc)}
|
||||
return {"status": "error", "count": 0, "subscriptions": [], "error": str(exc)}
|
||||
|
||||
|
||||
@router.get("/razorpay/payments")
|
||||
async def list_razorpay_payments(admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
async def list_razorpay_payments(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
from sqlalchemy import select
|
||||
from app.db.models import Invoice, PaymentTransaction
|
||||
items = get_razorpay_service().client.payment.all({"count":100}).get("items", [])
|
||||
items = get_razorpay_service().client.payment.all({"count": 100}).get("items", [])
|
||||
ids = [x.get("id") for x in items if x.get("id")]
|
||||
invoice_map = {}
|
||||
if ids:
|
||||
rows = (await service.session.execute(select(PaymentTransaction.gateway_transaction_id, Invoice.invoice_number).join(Invoice, Invoice.payment_transaction_id == PaymentTransaction.id).where(PaymentTransaction.gateway_transaction_id.in_(ids)))).all()
|
||||
rows = (await service.session.execute(
|
||||
select(PaymentTransaction.gateway_transaction_id, Invoice.invoice_number)
|
||||
.join(Invoice, Invoice.payment_transaction_id == PaymentTransaction.id)
|
||||
.where(PaymentTransaction.gateway_transaction_id.in_(ids))
|
||||
)).all()
|
||||
invoice_map = {pid: inv for pid, inv in rows}
|
||||
return {"status":"success","count":len(items),"payments":[{"id":x.get("id"),"amount":x.get("amount"),"currency":x.get("currency"),"status":x.get("status"),"method":x.get("method"),"email":x.get("email"),"contact":x.get("contact"),"order_id":x.get("order_id"),"description":x.get("description"),"created_at":x.get("created_at"),"invoice_number":invoice_map.get(x.get("id"))} for x in items]}
|
||||
return {
|
||||
"status": "success",
|
||||
"count": len(items),
|
||||
"payments": [
|
||||
{
|
||||
"id": x.get("id"),
|
||||
"amount": x.get("amount"),
|
||||
"currency": x.get("currency"),
|
||||
"status": x.get("status"),
|
||||
"method": x.get("method"),
|
||||
"email": x.get("email"),
|
||||
"contact": x.get("contact"),
|
||||
"order_id": x.get("order_id"),
|
||||
"description": x.get("description"),
|
||||
"created_at": x.get("created_at"),
|
||||
"invoice_number": invoice_map.get(x.get("id")),
|
||||
}
|
||||
for x in items
|
||||
],
|
||||
}
|
||||
except Exception as exc:
|
||||
return {"status":"error","count":0,"payments":[],"error":str(exc)}
|
||||
return {"status": "error", "count": 0, "payments":[], "error": str(exc)}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# INVOICES
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/payments/{payment_id}/invoice")
|
||||
async def get_or_create_payment_invoice(payment_id: str, admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
async def get_or_create_payment_invoice(
|
||||
payment_id: str,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
url, _, _ = await service.get_or_create_invoice(payment_id)
|
||||
return {"short_url": url}
|
||||
except LookupError as exc: raise HTTPException(404, detail=str(exc)) from exc
|
||||
except Exception as exc: raise HTTPException(502, detail=f"Failed to generate invoice from Razorpay: {exc}") from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(502, detail=f"Failed to generate invoice: {exc}") from exc
|
||||
|
||||
|
||||
@router.get("/payments/{payment_id}/invoice/view", response_class=HTMLResponse)
|
||||
async def view_payment_invoice_html(
|
||||
payment_id: str,
|
||||
token: str | None = Query(None),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.render_invoice_html(payment_id)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(500, detail=f"Failed to render HTML invoice: {exc}") from exc
|
||||
|
||||
|
||||
@router.post("/payments/{payment_id}/share-invoice")
|
||||
async def share_payment_invoice(payment_id: str, admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
try: return await service.share_invoice(payment_id)
|
||||
except LookupError as exc: raise HTTPException(404, detail=str(exc)) from exc
|
||||
except RuntimeError as exc: raise HTTPException(500, detail=str(exc)) from exc
|
||||
async def share_payment_invoice(
|
||||
payment_id: str,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.share_invoice(payment_id)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(500, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# USERS & SUBSCRIPTIONS
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/super-admins", response_model=list[AdminUserListResponse])
|
||||
async def list_super_admins(admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
async def list_super_admins(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
return await service.list_users(True)
|
||||
|
||||
|
||||
@router.get("/practitioners", response_model=list[AdminUserListResponse])
|
||||
async def list_practitioners(admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
async def list_practitioners(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
return await service.list_users(False)
|
||||
|
||||
|
||||
@router.get("/users-subscriptions")
|
||||
async def get_all_users_subscriptions(admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
async def get_all_users_subscriptions(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
return await service.subscriptions()
|
||||
|
||||
|
||||
@router.post("/promote-user")
|
||||
async def promote_user_to_admin(payload: AdminPromoteUserRequest, admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
try: return await service.promote(payload, admin)
|
||||
except LookupError as exc: raise HTTPException(404, detail=str(exc)) from exc
|
||||
except RuntimeError as exc: raise HTTPException(500, detail=str(exc)) from exc
|
||||
async def promote_user_to_admin(
|
||||
payload: AdminPromoteUserRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.promote(payload, admin)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(500, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/create-super-admin", status_code=status.HTTP_201_CREATED)
|
||||
async def create_super_admin(payload: AdminCreateSuperAdminRequest, admin: AppUser = Depends(get_current_admin), service: AdminService = Depends(get_admin_service)):
|
||||
try: return await service.create_super_admin(payload, admin)
|
||||
except ValueError as exc: raise HTTPException(400, detail=str(exc)) from exc
|
||||
except RuntimeError as exc: raise HTTPException(500, detail=str(exc)) from exc
|
||||
async def create_super_admin(
|
||||
payload: AdminCreateSuperAdminRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.create_super_admin(payload, admin)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(500, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# CUSTOMER 360 & DRAWER
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/customers/{user_id}/detail")
|
||||
async def get_customer_detail(
|
||||
user_id: str,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.get_customer_detail(user_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.patch("/customers/{user_id}/status")
|
||||
async def update_customer_status(
|
||||
user_id: str,
|
||||
payload: CustomerStatusUpdateRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.update_customer_status(user_id, payload.is_active, admin)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# CLINICAL MODULES MANAGEMENT
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/modules")
|
||||
async def get_admin_modules(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
return await service.list_modules()
|
||||
|
||||
|
||||
@router.patch("/modules/{module_id}/status")
|
||||
async def update_module_status(
|
||||
module_id: str,
|
||||
payload: ModuleStatusUpdateRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.update_module_status(module_id, payload)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.put("/modules/{module_id}")
|
||||
async def update_module_details(
|
||||
module_id: str,
|
||||
payload: ModuleUpdateRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.update_module(module_id, payload)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ACCESS PLANS & PRICING
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/plans")
|
||||
async def get_admin_plans(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
return await service.list_plans()
|
||||
|
||||
|
||||
@router.post("/plans")
|
||||
async def create_admin_plan(
|
||||
payload: CreatePlanRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.create_plan(payload, admin)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.put("/plans/{plan_code}/pricing")
|
||||
async def update_plan_pricing(
|
||||
plan_code: str,
|
||||
payload: PlanPricingUpdateRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.update_plan_pricing(plan_code, payload)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.patch("/plans/{plan_code}/status")
|
||||
async def update_plan_status(
|
||||
plan_code: str,
|
||||
payload: PlanStatusUpdateRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.toggle_plan_status(plan_code, payload.is_active)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# COUPONS & PROMOTIONS
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/coupons")
|
||||
async def get_admin_coupons(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
return await service.list_coupons()
|
||||
|
||||
|
||||
@router.post("/coupons")
|
||||
async def create_coupon(
|
||||
payload: CreateCouponRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.create_coupon(payload, admin)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.put("/coupons/{coupon_id}")
|
||||
async def update_coupon(
|
||||
coupon_id: str,
|
||||
payload: UpdateCouponRequest,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.update_coupon(coupon_id, payload)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.patch("/coupons/{coupon_id}/status")
|
||||
async def toggle_coupon_status(
|
||||
coupon_id: str,
|
||||
payload: dict,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
is_active = payload.get("is_active", True)
|
||||
return await service.toggle_coupon_status(coupon_id, is_active)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.delete("/coupons/{coupon_id}")
|
||||
async def delete_coupon(
|
||||
coupon_id: str,
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.delete_coupon(coupon_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except LookupError as exc:
|
||||
raise HTTPException(404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# DATABASE & BACKUPS
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/database/info")
|
||||
async def get_database_info(
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.get_database_info()
|
||||
except Exception as exc:
|
||||
raise HTTPException(500, detail=f"Failed to query database telemetry: {exc}") from exc
|
||||
|
||||
|
||||
@router.get("/database/backup")
|
||||
async def download_database_backup(
|
||||
scope: str = Query("full", pattern="^(full|content)$"),
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.download_database_backup(scope)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(500, detail=f"Failed to create database backup: {exc}") from exc
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# REPORTS CSV EXPORTS
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/reports/{report_type}/export")
|
||||
async def export_report_csv(
|
||||
report_type: str,
|
||||
start_date: str | None = Query(None),
|
||||
end_date: str | None = Query(None),
|
||||
admin: AppUser = Depends(get_current_admin),
|
||||
service: AdminService = Depends(get_admin_service),
|
||||
):
|
||||
try:
|
||||
return await service.export_report_csv(report_type, start_date, end_date)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(500, detail=f"Report export generation failed: {exc}") from exc
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ async def get_current_admin(user: AppUser = Depends(get_current_user), session:
|
|||
roles = (await session.execute(
|
||||
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
|
||||
)).scalars().all()
|
||||
if not ({"super_admin", "finance_admin"} & set(roles)):
|
||||
if not ({"super_admin", "admin", "finance_admin"} & set(roles)):
|
||||
raise HTTPException(403, detail="Forbidden: Administrative privileges required.")
|
||||
return user
|
||||
|
||||
|
|
|
|||
|
|
@ -41,3 +41,78 @@ class AdminUserListResponse(BaseModel):
|
|||
roles: list[str]
|
||||
external_ref: str | None = None
|
||||
subscriptions: list[dict] = Field(default_factory=list)
|
||||
created_at: str | None = None
|
||||
|
||||
class ModuleStatusUpdateRequest(BaseModel):
|
||||
is_active: bool
|
||||
status: str | None = None
|
||||
|
||||
class ModuleUpdateRequest(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
category: str | None = None
|
||||
icon: str | None = None
|
||||
color: str | None = None
|
||||
|
||||
class CreatePlanRequest(BaseModel):
|
||||
code: str
|
||||
name: str
|
||||
description: str | None = None
|
||||
plan_type: str = "bundle"
|
||||
billing_period: str = "yearly"
|
||||
price_inr: float
|
||||
price_usd: float
|
||||
module_ids: list[str] = Field(default_factory=list)
|
||||
is_featured: bool = False
|
||||
badge_text: str | None = None
|
||||
heading: str | None = None
|
||||
subtitle: str | None = None
|
||||
|
||||
class PlanPricingUpdateRequest(BaseModel):
|
||||
price_inr: float | None = None
|
||||
price_usd: float | None = None
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
badge_text: str | None = None
|
||||
heading: str | None = None
|
||||
subtitle: str | None = None
|
||||
|
||||
class PlanStatusUpdateRequest(BaseModel):
|
||||
is_active: bool
|
||||
|
||||
class CreateCouponRequest(BaseModel):
|
||||
code: str
|
||||
discount_type: str
|
||||
coupon_category: str = "general"
|
||||
value: float
|
||||
max_discount_limit: float = 0.0
|
||||
start_date: str | None = None
|
||||
end_date: str | None = None
|
||||
usage_limit: int = 0
|
||||
min_purchase_amount: float = 0.0
|
||||
is_first_purchase_only: bool = False
|
||||
applicable_plan_ids: list[str] | None = None
|
||||
applicable_module_ids: list[str] | None = None
|
||||
is_active: bool = True
|
||||
description: str | None = None
|
||||
|
||||
class UpdateCouponRequest(BaseModel):
|
||||
discount_type: str | None = None
|
||||
coupon_category: str | None = None
|
||||
value: float | None = None
|
||||
max_discount_limit: float | None = None
|
||||
start_date: str | None = None
|
||||
end_date: str | None = None
|
||||
usage_limit: int | None = None
|
||||
min_purchase_amount: float | None = None
|
||||
is_first_purchase_only: bool | None = None
|
||||
applicable_plan_ids: list[str] | None = None
|
||||
applicable_module_ids: list[str] | None = None
|
||||
is_active: bool | None = None
|
||||
description: str | None = None
|
||||
|
||||
class CouponStatusToggleRequest(BaseModel):
|
||||
is_active: bool
|
||||
|
||||
class CustomerStatusUpdateRequest(BaseModel):
|
||||
is_active: bool
|
||||
|
|
|
|||
|
|
@ -1,145 +1,22 @@
|
|||
from __future__ import annotations
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal
|
||||
from uuid import UUID
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.enums import BillingPeriod, EntitlementStatus, PaymentStatus, SubscriptionStatus
|
||||
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Invoice, PaymentTransaction, RefundDecision, Role, UserBillingProfile, UserEntitlement, UserRole, UserSubscription
|
||||
from app.features.auth.security import hash_password, validate_password_strength
|
||||
from app.features.email import send_invoice_email
|
||||
from app.features.payments import get_razorpay_service
|
||||
from .schema import AdminCreateSuperAdminRequest, AdminPromoteUserRequest, AdminRefundRequest, AdminRefundResponse, AdminSyncResponse, AdminUserListResponse
|
||||
from .services import (
|
||||
AdminService,
|
||||
AdminModuleService,
|
||||
AdminPlanService,
|
||||
AdminCouponService,
|
||||
AdminCustomerService,
|
||||
AdminPaymentService,
|
||||
AdminDatabaseService,
|
||||
AdminReportService,
|
||||
)
|
||||
|
||||
class AdminService:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self.session = session
|
||||
|
||||
async def process_refund(self, request: AdminRefundRequest, admin: AppUser) -> AdminRefundResponse:
|
||||
tx = (await self.session.execute(select(PaymentTransaction).where(PaymentTransaction.id == request.payment_transaction_id, PaymentTransaction.status == PaymentStatus.SUCCESS))).scalar_one_or_none()
|
||||
if not tx: raise LookupError("The specified successful payment transaction could not be located.")
|
||||
if request.refund_amount > tx.amount: raise ValueError("Refund amount cannot exceed the captured payment amount.")
|
||||
existing = (await self.session.execute(select(RefundDecision.id).where(RefundDecision.payment_transaction_id == tx.id).limit(1))).scalar_one_or_none()
|
||||
if existing: raise ValueError("A refund has already been registered or calculated for this transaction.")
|
||||
sub = (await self.session.execute(select(UserSubscription).where(UserSubscription.id == tx.subscription_id))).scalar_one()
|
||||
rzp = get_razorpay_service()
|
||||
refund = rzp.create_refund(payment_id=tx.gateway_transaction_id, amount=request.refund_amount, currency=tx.currency, notes={"support_ticket":request.support_ticket_reference,"admin_id":str(admin.id),"reason":request.reason_detail or "Customer request"})
|
||||
now = datetime.now(timezone.utc)
|
||||
start = sub.started_at
|
||||
if start.tzinfo is None: start = start.replace(tzinfo=timezone.utc)
|
||||
active_months = max(1, (now - start).days // 30)
|
||||
reduction = (Decimal("1") - (request.refund_amount / Decimal(tx.amount))) * Decimal("100")
|
||||
decision = RefundDecision(payment_transaction_id=tx.id, original_paid_amount=tx.amount, original_currency=tx.currency, calculated_reduction_percent=reduction, refund_amount=request.refund_amount, active_duration_months=active_months, support_ticket_reference=request.support_ticket_reference, reason_detail=request.reason_detail, status="approved", approved_by_admin_id=admin.id, decided_at=now)
|
||||
self.session.add(decision)
|
||||
tx.status = PaymentStatus.REVERSED
|
||||
sub.status = SubscriptionStatus.REFUNDED
|
||||
sub.cancelled_at = now
|
||||
sub.cancellation_reason = "refund_processed"
|
||||
sub.cancelled_by = admin.id
|
||||
ents = (await self.session.execute(select(UserEntitlement).where(UserEntitlement.source_subscription_id == sub.id, UserEntitlement.status == EntitlementStatus.ACTIVE))).scalars().all()
|
||||
for ent in ents:
|
||||
ent.status = EntitlementStatus.REVOKED; ent.revoked_at = now; ent.revoked_by = admin.id; ent.revoke_reason = "refund_processed"
|
||||
await self.session.commit(); await self.session.refresh(decision)
|
||||
return AdminRefundResponse(status="refunded", refund_decision_id=decision.id, gateway_refund_id=refund["id"], refunded_amount=request.refund_amount, currency=tx.currency)
|
||||
|
||||
async def force_sync(self) -> AdminSyncResponse:
|
||||
rzp = get_razorpay_service(); log: list[str] = []; count = 0
|
||||
payments = rzp.client.payment.all({"count": 100}).get("items", [])
|
||||
for payment in payments:
|
||||
if payment.get("status") != "captured" or not payment.get("id"): continue
|
||||
pid = payment["id"]
|
||||
if (await self.session.execute(select(PaymentTransaction.id).where(PaymentTransaction.gateway_transaction_id == pid))).scalar_one_or_none(): continue
|
||||
order_id = payment.get("order_id")
|
||||
if not order_id: log.append(f"Skipped {pid}: no Razorpay order_id"); continue
|
||||
sub = (await self.session.execute(select(UserSubscription).where(UserSubscription.payment_reference == order_id).limit(1))).scalar_one_or_none()
|
||||
if not sub: log.append(f"Skipped {pid}: no matching local subscription for {order_id}"); continue
|
||||
await self._reconcile_payment(payment, sub); count += 1; log.append(f"Reconciled {pid} → subscription {sub.id}")
|
||||
if not log: log.append("All records are already synchronized. No changes needed.")
|
||||
await self.session.commit()
|
||||
return AdminSyncResponse(status="completed", message=f"Sync complete. {count} record(s) processed.", records_processed=count, sync_log=log)
|
||||
|
||||
async def _reconcile_payment(self, payment: dict, sub: UserSubscription) -> None:
|
||||
now = datetime.now(timezone.utc)
|
||||
plan = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == sub.plan_id))).scalar_one_or_none()
|
||||
if sub.status == SubscriptionStatus.PENDING:
|
||||
sub.status = SubscriptionStatus.ACTIVE; sub.started_at = now; sub.expires_at = now + timedelta(days=3650 if plan and plan.billing_period == BillingPeriod.LIFETIME else 365)
|
||||
amount = Decimal(str(payment.get("amount",0))) / 100; curr = str(payment.get("currency","INR")).upper()
|
||||
tx = PaymentTransaction(user_id=sub.user_id, subscription_id=sub.id, gateway_name="razorpay", gateway_transaction_id=payment["id"], status=PaymentStatus.SUCCESS, amount=amount, currency=curr)
|
||||
self.session.add(tx); await self.session.flush()
|
||||
meta = sub.metadata_json or {}; taxable=Decimal(str(meta.get("taxable_amount",0))); gst=Decimal(str(meta.get("gst_amount",0))); base=Decimal(str(meta.get("base_subtotal",amount))); discount=Decimal(str(meta.get("total_discounts",0)))
|
||||
user = (await self.session.execute(select(AppUser).where(AppUser.id == sub.user_id))).scalar_one()
|
||||
self.session.add(Invoice(payment_transaction_id=tx.id, invoice_number=f"INV-{now.strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}", billing_name=user.display_name or user.email, billing_email=user.email, billing_address="Synced from Razorpay", base_amount=base, discount_amount=discount, taxable_amount=taxable, gst_amount=gst, total_amount=amount, currency_code=curr, exchange_rate_to_inr=Decimal("1"), total_amount_inr=amount if curr=="INR" else None))
|
||||
module_ids=(await self.session.execute(select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id==sub.plan_id))).scalars().all()
|
||||
for module_id in module_ids:
|
||||
active=(await self.session.execute(select(UserEntitlement.id).where(UserEntitlement.user_id==sub.user_id,UserEntitlement.module_id==module_id,UserEntitlement.status==EntitlementStatus.ACTIVE).limit(1))).scalar_one_or_none()
|
||||
if active is None: self.session.add(UserEntitlement(user_id=sub.user_id,module_id=module_id,source_subscription_id=sub.id,source_plan_id=sub.plan_id,status=EntitlementStatus.ACTIVE,granted_at=now,grant_reason="force_sync_reconciliation",expires_at=sub.expires_at))
|
||||
|
||||
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=[]
|
||||
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]))
|
||||
return out
|
||||
|
||||
async def subscriptions(self) -> list[dict]:
|
||||
rows=(await self.session.execute(select(UserSubscription,AppUser,AccessPlan).join(AppUser,AppUser.id==UserSubscription.user_id).join(AccessPlan,AccessPlan.id==UserSubscription.plan_id,isouter=True).where(UserSubscription.status!=SubscriptionStatus.PENDING).order_by(UserSubscription.started_at.desc()))).all(); now=datetime.now(timezone.utc); result=[]
|
||||
for sub,user,plan in rows:
|
||||
exp=sub.expires_at; days=max(0,(exp-now).days) if exp and sub.status==SubscriptionStatus.ACTIVE else 0
|
||||
result.append({"id":str(sub.id),"user_email":user.email,"user_name":user.display_name or user.email.split('@')[0].title(),"user_phone":user.phone_number,"user_external_ref":user.external_ref,"plan_code":plan.code if plan else "UNKNOWN","plan_name":plan.name if plan else "Unknown Access Plan","status":getattr(sub.status,"value",sub.status),"started_at":sub.started_at.isoformat() if sub.started_at else None,"expires_at":exp.isoformat() if exp else None,"days_left":days,"payment_reference":sub.payment_reference})
|
||||
return result
|
||||
|
||||
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 _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
|
||||
|
||||
async def get_or_create_invoice(self,payment_id:str)->tuple[str|None,str,str]:
|
||||
tx=(await self.session.execute(select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id==payment_id))).scalar_one_or_none()
|
||||
if not tx: raise LookupError("Payment transaction not found.")
|
||||
invoice=(await self.session.execute(select(Invoice).where(Invoice.payment_transaction_id==tx.id))).scalar_one_or_none(); rzp=get_razorpay_service(); user=(await self.session.execute(select(AppUser).where(AppUser.id==tx.user_id))).scalar_one()
|
||||
if invoice and invoice.invoice_number.startswith("inv_"):
|
||||
remote=rzp.client.invoice.fetch(invoice.invoice_number); url=remote.get("short_url")
|
||||
if not url and remote.get("status")=="draft": url=rzp.client.invoice.issue(invoice.invoice_number).get("short_url")
|
||||
if url: return url,invoice.invoice_number,user.email
|
||||
profile=(await self.session.execute(select(UserBillingProfile).where(UserBillingProfile.user_id==user.id,UserBillingProfile.is_default.is_(True)))).scalar_one_or_none()
|
||||
payment=rzp.fetch_payment(payment_id); customer={"name":profile.billing_name if profile else (user.display_name or user.email),"email":payment.get("email") or user.email}
|
||||
contact=payment.get("contact") or (profile.billing_phone if profile else user.phone_number)
|
||||
if contact: customer["contact"]=contact
|
||||
remote=rzp.client.invoice.create(data={"type":"invoice","customer":customer,"line_items":[{"name":payment.get("description") or "Access Plan Subscription","amount":payment.get("amount"),"currency":payment.get("currency","INR"),"quantity":1}],"email_notify":False,"sms_notify":False,"notes":{"payment_id":payment_id}}); inv_id=remote.get("id"); url=remote.get("short_url")
|
||||
if remote.get("status")=="draft": url=rzp.client.invoice.issue(inv_id).get("short_url") or url
|
||||
if invoice: invoice.invoice_number=inv_id
|
||||
else:
|
||||
amount=Decimal(str(payment.get("amount",0)))/100; curr=str(payment.get("currency","INR")).upper(); taxable=(amount/Decimal("1.0236")*Decimal("0.02")).quantize(Decimal("0.01")) if curr=="INR" else (amount/Decimal("1.03")*Decimal("0.03")).quantize(Decimal("0.01")); gst=(taxable*Decimal("0.18")).quantize(Decimal("0.01")) if curr=="INR" else Decimal("0"); base=amount-taxable-gst
|
||||
self.session.add(Invoice(payment_transaction_id=tx.id,invoice_number=inv_id,billing_name=customer["name"],billing_email=customer["email"],billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}" if profile else "Not Configured",base_amount=base,discount_amount=Decimal("0"),taxable_amount=taxable,gst_amount=gst,total_amount=amount,currency_code=curr,exchange_rate_to_inr=Decimal("1"),total_amount_inr=amount if curr=="INR" else None))
|
||||
await self.session.commit(); return url,inv_id,customer["email"]
|
||||
|
||||
async def share_invoice(self,payment_id:str)->dict:
|
||||
url,num,email=await self.get_or_create_invoice(payment_id)
|
||||
if not url: raise RuntimeError("Razorpay invoice does not have a download URL.")
|
||||
if not send_invoice_email(to=email,invoice_number=num,invoice_url=url): raise RuntimeError("Failed to send invoice email. Please check SMTP / Mailhog configuration.")
|
||||
return {"status":"success","message":f"Invoice shared successfully with {email}."}
|
||||
__all__ = [
|
||||
"AdminService",
|
||||
"AdminModuleService",
|
||||
"AdminPlanService",
|
||||
"AdminCouponService",
|
||||
"AdminCustomerService",
|
||||
"AdminPaymentService",
|
||||
"AdminDatabaseService",
|
||||
"AdminReportService",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,147 @@
|
|||
from __future__ import annotations
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from fastapi.responses import HTMLResponse, StreamingResponse
|
||||
from app.db.models import AppUser
|
||||
from ..schema import (
|
||||
AdminCreateSuperAdminRequest,
|
||||
AdminPromoteUserRequest,
|
||||
AdminRefundRequest,
|
||||
AdminRefundResponse,
|
||||
AdminSyncResponse,
|
||||
AdminUserListResponse,
|
||||
CreateCouponRequest,
|
||||
CreatePlanRequest,
|
||||
CustomerStatusUpdateRequest,
|
||||
ModuleStatusUpdateRequest,
|
||||
ModuleUpdateRequest,
|
||||
PlanPricingUpdateRequest,
|
||||
PlanStatusUpdateRequest,
|
||||
UpdateCouponRequest,
|
||||
)
|
||||
|
||||
from .module_service import AdminModuleService
|
||||
from .plan_service import AdminPlanService
|
||||
from .coupon_service import AdminCouponService
|
||||
from .customer_service import AdminCustomerService
|
||||
from .payment_service import AdminPaymentService
|
||||
from .database_service import AdminDatabaseService
|
||||
from .report_service import AdminReportService
|
||||
|
||||
__all__ = [
|
||||
"AdminModuleService",
|
||||
"AdminPlanService",
|
||||
"AdminCouponService",
|
||||
"AdminCustomerService",
|
||||
"AdminPaymentService",
|
||||
"AdminDatabaseService",
|
||||
"AdminReportService",
|
||||
"AdminService",
|
||||
]
|
||||
|
||||
|
||||
class AdminService:
|
||||
"""
|
||||
Unified Admin Service Facade aggregating specialized domain services:
|
||||
- modules: AdminModuleService
|
||||
- plans: AdminPlanService
|
||||
- coupons: AdminCouponService
|
||||
- customers: AdminCustomerService
|
||||
- payments: AdminPaymentService
|
||||
- database: AdminDatabaseService
|
||||
- reports: AdminReportService
|
||||
"""
|
||||
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self.session = session
|
||||
self.modules = AdminModuleService(session)
|
||||
self.plans = AdminPlanService(session)
|
||||
self.coupons = AdminCouponService(session)
|
||||
self.customers = AdminCustomerService(session)
|
||||
self.payments = AdminPaymentService(session)
|
||||
self.database = AdminDatabaseService(session)
|
||||
self.reports = AdminReportService(session)
|
||||
|
||||
# ── Modules Facade ──
|
||||
async def list_modules(self) -> list[dict]:
|
||||
return await self.modules.list_modules()
|
||||
|
||||
async def update_module_status(self, module_id: str, payload: ModuleStatusUpdateRequest) -> dict:
|
||||
return await self.modules.update_status(module_id, payload)
|
||||
|
||||
async def update_module(self, module_id: str, payload: ModuleUpdateRequest) -> dict:
|
||||
return await self.modules.update_details(module_id, payload)
|
||||
|
||||
# ── Plans Facade ──
|
||||
async def list_plans(self) -> list[dict]:
|
||||
return await self.plans.list_plans()
|
||||
|
||||
async def create_plan(self, payload: CreatePlanRequest, admin: AppUser) -> dict:
|
||||
return await self.plans.create_plan(payload, admin)
|
||||
|
||||
async def update_plan_pricing(self, plan_code: str, payload: PlanPricingUpdateRequest) -> dict:
|
||||
return await self.plans.update_pricing(plan_code, payload)
|
||||
|
||||
async def toggle_plan_status(self, plan_code: str, is_active: bool) -> dict:
|
||||
return await self.plans.toggle_status(plan_code, is_active)
|
||||
|
||||
# ── Coupons Facade ──
|
||||
async def list_coupons(self) -> list[dict]:
|
||||
return await self.coupons.list_coupons()
|
||||
|
||||
async def create_coupon(self, payload: CreateCouponRequest, admin: AppUser) -> dict:
|
||||
return await self.coupons.create_coupon(payload, admin)
|
||||
|
||||
async def update_coupon(self, coupon_id: str, payload: UpdateCouponRequest) -> dict:
|
||||
return await self.coupons.update_coupon(coupon_id, payload)
|
||||
|
||||
async def toggle_coupon_status(self, coupon_id: str, is_active: bool) -> dict:
|
||||
return await self.coupons.toggle_status(coupon_id, is_active)
|
||||
|
||||
async def delete_coupon(self, coupon_id: str) -> dict:
|
||||
return await self.coupons.delete_coupon(coupon_id)
|
||||
|
||||
# ── Customer & Users Facade ──
|
||||
async def list_users(self, super_admin_only: bool) -> list[AdminUserListResponse]:
|
||||
return await self.customers.list_users(super_admin_only)
|
||||
|
||||
async def promote(self, request: AdminPromoteUserRequest, admin: AppUser) -> dict:
|
||||
return await self.customers.promote(request, admin)
|
||||
|
||||
async def create_super_admin(self, request: AdminCreateSuperAdminRequest, admin: AppUser) -> dict:
|
||||
return await self.customers.create_super_admin(request, admin)
|
||||
|
||||
async def get_customer_detail(self, user_id: str) -> dict:
|
||||
return await self.customers.get_customer_detail(user_id)
|
||||
|
||||
async def update_customer_status(self, user_id: str, is_active: bool, admin: AppUser) -> dict:
|
||||
return await self.customers.update_customer_status(user_id, is_active, admin)
|
||||
|
||||
# ── Payments & Invoicing Facade ──
|
||||
async def process_refund(self, request: AdminRefundRequest, admin: AppUser) -> AdminRefundResponse:
|
||||
return await self.payments.process_refund(request, admin)
|
||||
|
||||
async def force_sync(self) -> AdminSyncResponse:
|
||||
return await self.payments.force_sync()
|
||||
|
||||
async def subscriptions(self) -> list[dict]:
|
||||
return await self.payments.subscriptions()
|
||||
|
||||
async def get_or_create_invoice(self, payment_id: str) -> tuple[str | None, str, str]:
|
||||
return await self.payments.get_or_create_invoice(payment_id)
|
||||
|
||||
async def share_invoice(self, payment_id: str) -> dict:
|
||||
return await self.payments.share_invoice(payment_id)
|
||||
|
||||
async def render_invoice_html(self, payment_id: str) -> HTMLResponse:
|
||||
return await self.payments.render_invoice_html(payment_id)
|
||||
|
||||
# ── Database & Telemetry Facade ──
|
||||
async def get_database_info(self) -> dict:
|
||||
return await self.database.get_database_info()
|
||||
|
||||
async def download_database_backup(self, scope: str = "full") -> StreamingResponse:
|
||||
return await self.database.download_database_backup(scope)
|
||||
|
||||
# ── Reports Facade ──
|
||||
async def export_report_csv(self, report_type: str, start_date: str | None, end_date: str | None) -> StreamingResponse:
|
||||
return await self.reports.export_report_csv(report_type, start_date, end_date)
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
from __future__ import annotations
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal
|
||||
from uuid import UUID
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.models import AccessPlan, AppUser, Coupon, Module
|
||||
from ..schema import CreateCouponRequest, UpdateCouponRequest
|
||||
|
||||
|
||||
class AdminCouponService:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self.session = session
|
||||
|
||||
async def list_coupons(self) -> list[dict]:
|
||||
coupons = (await self.session.execute(
|
||||
select(Coupon).order_by(Coupon.created_at.desc())
|
||||
)).scalars().all()
|
||||
|
||||
plans_q = await self.session.execute(select(AccessPlan))
|
||||
all_plans = {str(p.id): (p.name or p.code) for p in plans_q.scalars().all()}
|
||||
|
||||
mods_q = await self.session.execute(select(Module))
|
||||
all_mods = {str(m.id): m.name for m in mods_q.scalars().all()}
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
result: list[dict] = []
|
||||
for c in coupons:
|
||||
s_date = c.start_date.replace(tzinfo=timezone.utc) if c.start_date.tzinfo is None else c.start_date
|
||||
e_date = c.end_date.replace(tzinfo=timezone.utc) if c.end_date.tzinfo is None else c.end_date
|
||||
|
||||
if not c.is_active:
|
||||
status = "inactive"
|
||||
elif now < s_date:
|
||||
status = "scheduled"
|
||||
elif now > e_date:
|
||||
status = "expired"
|
||||
else:
|
||||
status = "active"
|
||||
|
||||
plan_names = [all_plans.get(str(pid), str(pid)[:8]) for pid in (c.applicable_plan_ids or [])]
|
||||
module_names = [all_mods.get(str(mid), str(mid)[:8]) for mid in (c.applicable_module_ids or [])]
|
||||
|
||||
result.append({
|
||||
"id": str(c.id),
|
||||
"code": c.code,
|
||||
"discount_type": c.discount_type,
|
||||
"coupon_category": c.coupon_category,
|
||||
"value": float(c.value),
|
||||
"max_discount_limit": float(c.max_discount_limit or 0.0),
|
||||
"start_date": s_date.isoformat(),
|
||||
"end_date": e_date.isoformat(),
|
||||
"usage_limit": c.usage_limit,
|
||||
"usage_count": c.usage_count,
|
||||
"min_purchase_amount": float(c.min_purchase_amount or 0.0),
|
||||
"is_first_purchase_only": c.is_first_purchase_only,
|
||||
"is_active": c.is_active,
|
||||
"description": c.description or "",
|
||||
"schedule_status": status,
|
||||
"applicable_plan_ids": [str(pid) for pid in (c.applicable_plan_ids or [])],
|
||||
"applicable_module_ids": [str(mid) for mid in (c.applicable_module_ids or [])],
|
||||
"plan_names": plan_names,
|
||||
"module_names": module_names,
|
||||
"created_at": c.created_at.isoformat() if c.created_at else None,
|
||||
})
|
||||
return result
|
||||
|
||||
async def create_coupon(self, payload: CreateCouponRequest, admin: AppUser) -> dict:
|
||||
code = payload.code.strip().upper()
|
||||
if not code:
|
||||
raise ValueError("Coupon code cannot be empty.")
|
||||
if (await self.session.execute(select(Coupon.id).where(Coupon.code == code))).scalar_one_or_none():
|
||||
raise ValueError(f"Coupon code '{code}' already exists.")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
start = datetime.fromisoformat(payload.start_date.replace("Z", "+00:00")) if payload.start_date else now
|
||||
end = datetime.fromisoformat(payload.end_date.replace("Z", "+00:00")) if payload.end_date else (now + timedelta(days=30))
|
||||
|
||||
plan_uuids = [UUID(pid) for pid in payload.applicable_plan_ids] if payload.applicable_plan_ids else None
|
||||
module_uuids = [UUID(mid) for mid in payload.applicable_module_ids] if payload.applicable_module_ids else None
|
||||
|
||||
coupon = Coupon(
|
||||
code=code,
|
||||
discount_type=payload.discount_type,
|
||||
coupon_category=payload.coupon_category,
|
||||
value=Decimal(str(payload.value)),
|
||||
max_discount_limit=Decimal(str(payload.max_discount_limit or 0)),
|
||||
start_date=start,
|
||||
end_date=end,
|
||||
usage_limit=payload.usage_limit,
|
||||
usage_count=0,
|
||||
min_purchase_amount=Decimal(str(payload.min_purchase_amount or 0)),
|
||||
is_first_purchase_only=payload.is_first_purchase_only,
|
||||
applicable_plan_ids=plan_uuids,
|
||||
applicable_module_ids=module_uuids,
|
||||
is_active=payload.is_active,
|
||||
description=payload.description,
|
||||
)
|
||||
self.session.add(coupon)
|
||||
await self.session.commit()
|
||||
await self.session.refresh(coupon)
|
||||
return {"status": "success", "message": f"Coupon '{coupon.code}' created successfully.", "coupon_id": str(coupon.id)}
|
||||
|
||||
async def update_coupon(self, coupon_id: str, payload: UpdateCouponRequest) -> dict:
|
||||
try:
|
||||
cid = UUID(coupon_id)
|
||||
except ValueError:
|
||||
raise ValueError("Invalid coupon UUID.")
|
||||
coupon = (await self.session.execute(select(Coupon).where(Coupon.id == cid))).scalar_one_or_none()
|
||||
if not coupon:
|
||||
raise LookupError("Coupon not found.")
|
||||
|
||||
if payload.discount_type is not None:
|
||||
coupon.discount_type = payload.discount_type
|
||||
if payload.coupon_category is not None:
|
||||
coupon.coupon_category = payload.coupon_category
|
||||
if payload.value is not None:
|
||||
coupon.value = Decimal(str(payload.value))
|
||||
if payload.max_discount_limit is not None:
|
||||
coupon.max_discount_limit = Decimal(str(payload.max_discount_limit))
|
||||
if payload.start_date is not None:
|
||||
coupon.start_date = datetime.fromisoformat(payload.start_date.replace("Z", "+00:00"))
|
||||
if payload.end_date is not None:
|
||||
coupon.end_date = datetime.fromisoformat(payload.end_date.replace("Z", "+00:00"))
|
||||
if payload.usage_limit is not None:
|
||||
coupon.usage_limit = payload.usage_limit
|
||||
if payload.min_purchase_amount is not None:
|
||||
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_amount))
|
||||
if payload.is_first_purchase_only is not None:
|
||||
coupon.is_first_purchase_only = payload.is_first_purchase_only
|
||||
if payload.applicable_plan_ids is not None:
|
||||
coupon.applicable_plan_ids = [UUID(pid) for pid in payload.applicable_plan_ids]
|
||||
if payload.applicable_module_ids is not None:
|
||||
coupon.applicable_module_ids = [UUID(mid) for mid in payload.applicable_module_ids]
|
||||
if payload.is_active is not None:
|
||||
coupon.is_active = payload.is_active
|
||||
if payload.description is not None:
|
||||
coupon.description = payload.description
|
||||
|
||||
await self.session.commit()
|
||||
return {"status": "success", "message": f"Coupon '{coupon.code}' updated successfully."}
|
||||
|
||||
async def toggle_status(self, coupon_id: str, is_active: bool) -> dict:
|
||||
try:
|
||||
cid = UUID(coupon_id)
|
||||
except ValueError:
|
||||
raise ValueError("Invalid coupon UUID.")
|
||||
coupon = (await self.session.execute(select(Coupon).where(Coupon.id == cid))).scalar_one_or_none()
|
||||
if not coupon:
|
||||
raise LookupError("Coupon not found.")
|
||||
|
||||
coupon.is_active = is_active
|
||||
await self.session.commit()
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Coupon '{coupon.code}' status toggled to {'Active' if is_active else 'Inactive'}.",
|
||||
"is_active": is_active,
|
||||
}
|
||||
|
||||
async def delete_coupon(self, coupon_id: str) -> dict:
|
||||
try:
|
||||
cid = UUID(coupon_id)
|
||||
except ValueError:
|
||||
raise ValueError("Invalid coupon UUID.")
|
||||
coupon = (await self.session.execute(select(Coupon).where(Coupon.id == cid))).scalar_one_or_none()
|
||||
if not coupon:
|
||||
raise LookupError("Coupon not found.")
|
||||
|
||||
code = coupon.code
|
||||
await self.session.delete(coupon)
|
||||
await self.session.commit()
|
||||
return {"status": "success", "message": f"Coupon '{code}' deleted successfully."}
|
||||
|
|
@ -0,0 +1,282 @@
|
|||
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
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
from __future__ import annotations
|
||||
import asyncio
|
||||
import shlex
|
||||
import shutil
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlparse
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
class AdminDatabaseService:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self.session = session
|
||||
|
||||
async def get_database_info(self) -> dict:
|
||||
size_res = await self.session.execute(text(
|
||||
"SELECT pg_size_pretty(pg_database_size(current_database())), "
|
||||
"pg_database_size(current_database()), "
|
||||
"version();"
|
||||
))
|
||||
row = size_res.fetchone()
|
||||
size_human = row[0] if row else "Unknown"
|
||||
size_bytes = row[1] if row else 0
|
||||
pg_version = row[2].split(",")[0] if row else "PostgreSQL"
|
||||
|
||||
tables_res = await self.session.execute(text(
|
||||
"SELECT schemaname, count(*) as count "
|
||||
"FROM pg_tables "
|
||||
"WHERE schemaname NOT IN ('pg_catalog', 'information_schema') "
|
||||
"GROUP BY schemaname "
|
||||
"ORDER BY count DESC;"
|
||||
))
|
||||
schemas = [{"schema": r[0], "table_count": r[1]} for r in tables_res.fetchall()]
|
||||
total_tables = sum(s["table_count"] for s in schemas)
|
||||
|
||||
u = settings.database_url.replace("postgresql+asyncpg://", "postgresql://")
|
||||
p = urlparse(u)
|
||||
db_name = p.path.lstrip("/") or "acupedia_db"
|
||||
|
||||
return {
|
||||
"status": "healthy",
|
||||
"database_name": db_name,
|
||||
"host": p.hostname or "localhost",
|
||||
"port": p.port or 5432,
|
||||
"size_human": size_human,
|
||||
"size_bytes": size_bytes,
|
||||
"total_tables": total_tables,
|
||||
"schemas": schemas,
|
||||
"postgres_version": pg_version,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
async def download_database_backup(self, scope: str = "full") -> StreamingResponse:
|
||||
if scope not in ("full", "content"):
|
||||
raise ValueError("Invalid scope. Supported: 'full', 'content'.")
|
||||
|
||||
u = settings.database_url.replace("postgresql+asyncpg://", "postgresql://")
|
||||
p = urlparse(u)
|
||||
pwd = p.password or ""
|
||||
host = p.hostname or "localhost"
|
||||
port = str(p.port or 5432)
|
||||
user = p.username or "db_admin"
|
||||
db_name = p.path.lstrip("/") or "acupedia_db"
|
||||
|
||||
scope_flag = "" if scope == "full" else "-n content"
|
||||
if shutil.which("pg_dump"):
|
||||
cmd = (
|
||||
f"PGPASSWORD={shlex.quote(pwd)} pg_dump "
|
||||
f"-h {shlex.quote(host)} -p {shlex.quote(port)} -U {shlex.quote(user)} -d {shlex.quote(db_name)} "
|
||||
f"--clean --if-exists {scope_flag} | gzip -9"
|
||||
)
|
||||
else:
|
||||
cmd = (
|
||||
f"docker exec -e PGPASSWORD={shlex.quote(pwd)} panacea-postgres pg_dump "
|
||||
f"-U {shlex.quote(user)} -d {shlex.quote(db_name)} "
|
||||
f"--clean --if-exists {scope_flag} | gzip -9"
|
||||
)
|
||||
|
||||
timestamp_str = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
|
||||
filename = f"acupedia_db_backup_{scope}_{timestamp_str}.sql.gz"
|
||||
|
||||
async def backup_stream():
|
||||
proc = await asyncio.create_subprocess_shell(
|
||||
cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE
|
||||
)
|
||||
try:
|
||||
while True:
|
||||
chunk = await proc.stdout.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
await proc.wait()
|
||||
|
||||
return StreamingResponse(
|
||||
backup_stream(),
|
||||
media_type="application/gzip",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename}"',
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
}
|
||||
)
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
from __future__ import annotations
|
||||
from uuid import UUID
|
||||
from sqlalchemy import select, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.enums import ModuleStatus
|
||||
from app.db.models import Module, AccessPlanModule
|
||||
from ..schema import ModuleStatusUpdateRequest, ModuleUpdateRequest
|
||||
|
||||
UI_MAPPINGS: dict[str, dict[str, str]] = {
|
||||
"acupoints": {"category": "point", "icon": "water-outline", "color": "#2563EB"},
|
||||
"ear-acupuncture": {"category": "point", "icon": "ear-outline", "color": "#F59E0B"},
|
||||
"scalp-acupuncture": {"category": "point", "icon": "accessibility-outline", "color": "#EF4444"},
|
||||
"points_tung": {"category": "point", "icon": "analytics-outline", "color": "#10B981"},
|
||||
"auriculotherapy": {"category": "point", "icon": "body-outline", "color": "#8B5CF6"},
|
||||
}
|
||||
|
||||
|
||||
class AdminModuleService:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self.session = session
|
||||
|
||||
async def list_modules(self) -> list[dict]:
|
||||
modules = (await self.session.execute(select(Module).order_by(Module.name.asc()))).scalars().all()
|
||||
plan_counts_q = await self.session.execute(
|
||||
select(AccessPlanModule.module_id, func.count(AccessPlanModule.plan_id))
|
||||
.group_by(AccessPlanModule.module_id)
|
||||
)
|
||||
plan_counts = {str(row[0]): row[1] for row in plan_counts_q.all()}
|
||||
|
||||
result: list[dict] = []
|
||||
for m in modules:
|
||||
meta = m.metadata_json or {}
|
||||
ui = UI_MAPPINGS.get(m.slug, {})
|
||||
category = meta.get("category") or ui.get("category", "General")
|
||||
icon = meta.get("icon") or ui.get("icon", "book-outline")
|
||||
color = meta.get("color") or ui.get("color", "#6366F1")
|
||||
|
||||
result.append({
|
||||
"id": str(m.id),
|
||||
"code": m.code or "",
|
||||
"slug": m.slug,
|
||||
"name": m.name,
|
||||
"description": m.description or "",
|
||||
"status": getattr(m.status, "value", m.status),
|
||||
"is_active": m.is_active,
|
||||
"category": category,
|
||||
"icon": icon,
|
||||
"color": color,
|
||||
"linked_plans_count": plan_counts.get(str(m.id), 0),
|
||||
"created_at": m.created_at.isoformat() if m.created_at else None,
|
||||
"updated_at": m.updated_at.isoformat() if m.updated_at else None,
|
||||
})
|
||||
return result
|
||||
|
||||
async def update_status(self, module_id: str, payload: ModuleStatusUpdateRequest) -> dict:
|
||||
try:
|
||||
mid = UUID(module_id)
|
||||
except ValueError:
|
||||
raise ValueError("Invalid module UUID.")
|
||||
module = (await self.session.execute(select(Module).where(Module.id == mid))).scalar_one_or_none()
|
||||
if not module:
|
||||
raise LookupError("Module not found.")
|
||||
|
||||
module.is_active = payload.is_active
|
||||
if payload.status and payload.status in ["draft", "active", "inactive", "archived"]:
|
||||
module.status = ModuleStatus(payload.status)
|
||||
elif not payload.is_active:
|
||||
module.status = ModuleStatus.INACTIVE
|
||||
else:
|
||||
module.status = ModuleStatus.ACTIVE
|
||||
|
||||
await self.session.commit()
|
||||
await self.session.refresh(module)
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Module '{module.name}' status updated to {'Active' if module.is_active else 'Inactive'}.",
|
||||
"module": {
|
||||
"id": str(module.id),
|
||||
"slug": module.slug,
|
||||
"name": module.name,
|
||||
"is_active": module.is_active,
|
||||
"status": getattr(module.status, "value", module.status),
|
||||
},
|
||||
}
|
||||
|
||||
async def update_details(self, module_id: str, payload: ModuleUpdateRequest) -> dict:
|
||||
try:
|
||||
mid = UUID(module_id)
|
||||
except ValueError:
|
||||
raise ValueError("Invalid module UUID.")
|
||||
module = (await self.session.execute(select(Module).where(Module.id == mid))).scalar_one_or_none()
|
||||
if not module:
|
||||
raise LookupError("Module not found.")
|
||||
|
||||
if payload.name:
|
||||
module.name = payload.name
|
||||
if payload.description is not None:
|
||||
module.description = payload.description
|
||||
|
||||
meta = dict(module.metadata_json or {})
|
||||
if payload.category:
|
||||
meta["category"] = payload.category
|
||||
if payload.color:
|
||||
meta["color"] = payload.color
|
||||
if payload.icon:
|
||||
meta["icon"] = payload.icon
|
||||
module.metadata_json = meta
|
||||
|
||||
await self.session.commit()
|
||||
await self.session.refresh(module)
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Module '{module.name}' updated successfully.",
|
||||
"module": {
|
||||
"id": str(module.id),
|
||||
"slug": module.slug,
|
||||
"name": module.name,
|
||||
"description": module.description,
|
||||
"category": meta.get("category"),
|
||||
"color": meta.get("color"),
|
||||
"icon": meta.get("icon"),
|
||||
},
|
||||
}
|
||||
|
|
@ -0,0 +1,718 @@
|
|||
from __future__ import annotations
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal
|
||||
from fastapi.responses import HTMLResponse
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.enums import BillingPeriod, EntitlementStatus, PaymentStatus, SubscriptionStatus
|
||||
from app.db.models import (
|
||||
AccessPlan,
|
||||
AccessPlanModule,
|
||||
AppUser,
|
||||
Invoice,
|
||||
PaymentTransaction,
|
||||
RefundDecision,
|
||||
UserBillingProfile,
|
||||
UserEntitlement,
|
||||
UserSubscription,
|
||||
)
|
||||
from ..schema import AdminRefundRequest, AdminRefundResponse, AdminSyncResponse
|
||||
from app.features.email import send_invoice_email
|
||||
from app.features.payments import get_razorpay_service
|
||||
|
||||
|
||||
class AdminPaymentService:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self.session = session
|
||||
|
||||
async def process_refund(self, request: AdminRefundRequest, admin: AppUser) -> AdminRefundResponse:
|
||||
tx = (await self.session.execute(
|
||||
select(PaymentTransaction).where(
|
||||
PaymentTransaction.id == request.payment_transaction_id,
|
||||
PaymentTransaction.status == PaymentStatus.SUCCESS,
|
||||
)
|
||||
)).scalar_one_or_none()
|
||||
if not tx:
|
||||
raise LookupError("The specified successful payment transaction could not be located.")
|
||||
if request.refund_amount > tx.amount:
|
||||
raise ValueError("Refund amount cannot exceed the captured payment amount.")
|
||||
|
||||
existing = (await self.session.execute(
|
||||
select(RefundDecision.id).where(RefundDecision.payment_transaction_id == tx.id).limit(1)
|
||||
)).scalar_one_or_none()
|
||||
if existing:
|
||||
raise ValueError("A refund has already been registered or calculated for this transaction.")
|
||||
|
||||
sub = (await self.session.execute(
|
||||
select(UserSubscription).where(UserSubscription.id == tx.subscription_id)
|
||||
)).scalar_one()
|
||||
|
||||
rzp = get_razorpay_service()
|
||||
refund = rzp.create_refund(
|
||||
payment_id=tx.gateway_transaction_id,
|
||||
amount=request.refund_amount,
|
||||
currency=tx.currency,
|
||||
notes={
|
||||
"support_ticket": request.support_ticket_reference,
|
||||
"admin_id": str(admin.id),
|
||||
"reason": request.reason_detail or "Customer request",
|
||||
},
|
||||
)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
start = sub.started_at
|
||||
if start.tzinfo is None:
|
||||
start = start.replace(tzinfo=timezone.utc)
|
||||
active_months = max(1, (now - start).days // 30)
|
||||
reduction = (Decimal("1") - (request.refund_amount / Decimal(tx.amount))) * Decimal("100")
|
||||
|
||||
decision = RefundDecision(
|
||||
payment_transaction_id=tx.id,
|
||||
original_paid_amount=tx.amount,
|
||||
original_currency=tx.currency,
|
||||
calculated_reduction_percent=reduction,
|
||||
refund_amount=request.refund_amount,
|
||||
active_duration_months=active_months,
|
||||
support_ticket_reference=request.support_ticket_reference,
|
||||
reason_detail=request.reason_detail,
|
||||
status="approved",
|
||||
approved_by_admin_id=admin.id,
|
||||
decided_at=now,
|
||||
)
|
||||
self.session.add(decision)
|
||||
tx.status = PaymentStatus.REVERSED
|
||||
sub.status = SubscriptionStatus.REFUNDED
|
||||
sub.cancelled_at = now
|
||||
sub.cancellation_reason = "refund_processed"
|
||||
sub.cancelled_by = admin.id
|
||||
|
||||
ents = (await self.session.execute(
|
||||
select(UserEntitlement).where(
|
||||
UserEntitlement.source_subscription_id == sub.id,
|
||||
UserEntitlement.status == EntitlementStatus.ACTIVE,
|
||||
)
|
||||
)).scalars().all()
|
||||
for ent in ents:
|
||||
ent.status = EntitlementStatus.REVOKED
|
||||
ent.revoked_at = now
|
||||
ent.revoked_by = admin.id
|
||||
ent.revoke_reason = "refund_processed"
|
||||
|
||||
await self.session.commit()
|
||||
await self.session.refresh(decision)
|
||||
return AdminRefundResponse(
|
||||
status="refunded",
|
||||
refund_decision_id=decision.id,
|
||||
gateway_refund_id=refund["id"],
|
||||
refunded_amount=request.refund_amount,
|
||||
currency=tx.currency,
|
||||
)
|
||||
|
||||
async def force_sync(self) -> AdminSyncResponse:
|
||||
rzp = get_razorpay_service()
|
||||
log: list[str] = []
|
||||
count = 0
|
||||
payments = rzp.client.payment.all({"count": 100}).get("items", [])
|
||||
for payment in payments:
|
||||
if payment.get("status") != "captured" or not payment.get("id"):
|
||||
continue
|
||||
pid = payment["id"]
|
||||
if (await self.session.execute(
|
||||
select(PaymentTransaction.id).where(PaymentTransaction.gateway_transaction_id == pid)
|
||||
)).scalar_one_or_none():
|
||||
continue
|
||||
order_id = payment.get("order_id")
|
||||
if not order_id:
|
||||
log.append(f"Skipped {pid}: no Razorpay order_id")
|
||||
continue
|
||||
sub = (await self.session.execute(
|
||||
select(UserSubscription).where(UserSubscription.payment_reference == order_id).limit(1)
|
||||
)).scalar_one_or_none()
|
||||
if not sub:
|
||||
log.append(f"Skipped {pid}: no matching local subscription for {order_id}")
|
||||
continue
|
||||
await self._reconcile_payment(payment, sub)
|
||||
count += 1
|
||||
log.append(f"Reconciled {pid} → subscription {sub.id}")
|
||||
if not log:
|
||||
log.append("All records are already synchronized. No changes needed.")
|
||||
await self.session.commit()
|
||||
return AdminSyncResponse(
|
||||
status="completed",
|
||||
message=f"Sync complete. {count} record(s) processed.",
|
||||
records_processed=count,
|
||||
sync_log=log,
|
||||
)
|
||||
|
||||
async def _reconcile_payment(self, payment: dict, sub: UserSubscription) -> None:
|
||||
now = datetime.now(timezone.utc)
|
||||
plan = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == sub.plan_id))).scalar_one_or_none()
|
||||
if sub.status == SubscriptionStatus.PENDING:
|
||||
sub.status = SubscriptionStatus.ACTIVE
|
||||
sub.started_at = now
|
||||
sub.expires_at = now + timedelta(days=3650 if plan and plan.billing_period == BillingPeriod.LIFETIME else 365)
|
||||
amount = Decimal(str(payment.get("amount", 0))) / 100
|
||||
curr = str(payment.get("currency", "INR")).upper()
|
||||
tx = PaymentTransaction(
|
||||
user_id=sub.user_id,
|
||||
subscription_id=sub.id,
|
||||
gateway_name="razorpay",
|
||||
gateway_transaction_id=payment["id"],
|
||||
status=PaymentStatus.SUCCESS,
|
||||
amount=amount,
|
||||
currency=curr,
|
||||
)
|
||||
self.session.add(tx)
|
||||
await self.session.flush()
|
||||
|
||||
meta = sub.metadata_json or {}
|
||||
taxable = Decimal(str(meta.get("taxable_amount", 0)))
|
||||
gst = Decimal(str(meta.get("gst_amount", 0)))
|
||||
base = Decimal(str(meta.get("base_subtotal", amount)))
|
||||
discount = Decimal(str(meta.get("total_discounts", 0)))
|
||||
user = (await self.session.execute(select(AppUser).where(AppUser.id == sub.user_id))).scalar_one()
|
||||
|
||||
self.session.add(
|
||||
Invoice(
|
||||
payment_transaction_id=tx.id,
|
||||
invoice_number=f"INV-{now.strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}",
|
||||
billing_name=user.display_name or user.email,
|
||||
billing_email=user.email,
|
||||
billing_address="Synced from Razorpay",
|
||||
base_amount=base,
|
||||
discount_amount=discount,
|
||||
taxable_amount=taxable,
|
||||
gst_amount=gst,
|
||||
total_amount=amount,
|
||||
currency_code=curr,
|
||||
exchange_rate_to_inr=Decimal("1"),
|
||||
total_amount_inr=amount if curr == "INR" else None,
|
||||
)
|
||||
)
|
||||
|
||||
module_ids = (await self.session.execute(
|
||||
select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id == sub.plan_id)
|
||||
)).scalars().all()
|
||||
for module_id in module_ids:
|
||||
active = (await self.session.execute(
|
||||
select(UserEntitlement.id).where(
|
||||
UserEntitlement.user_id == sub.user_id,
|
||||
UserEntitlement.module_id == module_id,
|
||||
UserEntitlement.status == EntitlementStatus.ACTIVE,
|
||||
).limit(1)
|
||||
)).scalar_one_or_none()
|
||||
if active is None:
|
||||
self.session.add(
|
||||
UserEntitlement(
|
||||
user_id=sub.user_id,
|
||||
module_id=module_id,
|
||||
source_subscription_id=sub.id,
|
||||
source_plan_id=sub.plan_id,
|
||||
status=EntitlementStatus.ACTIVE,
|
||||
granted_at=now,
|
||||
grant_reason="force_sync_reconciliation",
|
||||
expires_at=sub.expires_at,
|
||||
)
|
||||
)
|
||||
|
||||
async def subscriptions(self) -> list[dict]:
|
||||
rows = (await self.session.execute(
|
||||
select(UserSubscription, AppUser, AccessPlan)
|
||||
.join(AppUser, AppUser.id == UserSubscription.user_id)
|
||||
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
||||
.where(UserSubscription.status != SubscriptionStatus.PENDING)
|
||||
.order_by(UserSubscription.started_at.desc())
|
||||
)).all()
|
||||
now = datetime.now(timezone.utc)
|
||||
result: list[dict] = []
|
||||
for sub, user, plan in rows:
|
||||
exp = sub.expires_at
|
||||
days = max(0, (exp - now).days) if exp and sub.status == SubscriptionStatus.ACTIVE else 0
|
||||
result.append({
|
||||
"id": str(sub.id),
|
||||
"user_email": user.email,
|
||||
"user_name": user.display_name or user.email.split("@")[0].title(),
|
||||
"user_phone": user.phone_number,
|
||||
"user_external_ref": user.external_ref,
|
||||
"plan_code": plan.code if plan else "UNKNOWN",
|
||||
"plan_name": plan.name if plan else "Unknown Access Plan",
|
||||
"status": getattr(sub.status, "value", sub.status),
|
||||
"started_at": sub.started_at.isoformat() if sub.started_at else None,
|
||||
"expires_at": exp.isoformat() if exp else None,
|
||||
"days_left": days,
|
||||
"payment_reference": sub.payment_reference,
|
||||
})
|
||||
return result
|
||||
|
||||
async def get_or_create_invoice(self, payment_id: str) -> tuple[str | None, str, str]:
|
||||
tx = (await self.session.execute(
|
||||
select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id == payment_id)
|
||||
)).scalar_one_or_none()
|
||||
if not tx:
|
||||
raise LookupError("Payment transaction not found.")
|
||||
|
||||
invoice = (await self.session.execute(
|
||||
select(Invoice).where(Invoice.payment_transaction_id == tx.id)
|
||||
)).scalar_one_or_none()
|
||||
rzp = get_razorpay_service()
|
||||
user = (await self.session.execute(select(AppUser).where(AppUser.id == tx.user_id))).scalar_one()
|
||||
|
||||
if invoice and invoice.invoice_number and invoice.invoice_number.startswith("inv_"):
|
||||
return f"/api/admin/payments/{payment_id}/invoice/view", invoice.invoice_number, user.email
|
||||
|
||||
profile = (await self.session.execute(
|
||||
select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
|
||||
)).scalar_one_or_none()
|
||||
payment = rzp.fetch_payment(payment_id)
|
||||
customer = {
|
||||
"name": profile.billing_name if profile else (user.display_name or user.email),
|
||||
"email": payment.get("email") or user.email,
|
||||
}
|
||||
contact = payment.get("contact") or (profile.billing_phone if profile else user.phone_number)
|
||||
if contact:
|
||||
customer["contact"] = contact
|
||||
|
||||
inv_id = None
|
||||
url = None
|
||||
try:
|
||||
remote = rzp.client.invoice.create(data={
|
||||
"type": "invoice",
|
||||
"customer": customer,
|
||||
"line_items": [
|
||||
{
|
||||
"name": payment.get("description") or "Access Plan Subscription",
|
||||
"amount": payment.get("amount"),
|
||||
"currency": payment.get("currency", "INR"),
|
||||
"quantity": 1,
|
||||
}
|
||||
],
|
||||
"email_notify": False,
|
||||
"sms_notify": False,
|
||||
"notes": {"payment_id": payment_id},
|
||||
})
|
||||
inv_id = remote.get("id")
|
||||
url = remote.get("short_url")
|
||||
if remote.get("status") == "draft":
|
||||
url = rzp.client.invoice.issue(inv_id).get("short_url") or url
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not inv_id:
|
||||
inv_id = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}"
|
||||
|
||||
# Always return our internal branded Acupedia Tax Invoice view URL
|
||||
url = f"/api/admin/payments/{payment_id}/invoice/view"
|
||||
|
||||
if invoice:
|
||||
if not invoice.invoice_number or invoice.invoice_number.startswith("Tx:"):
|
||||
invoice.invoice_number = inv_id
|
||||
else:
|
||||
amount = Decimal(str(payment.get("amount", 0))) / 100
|
||||
curr = str(payment.get("currency", "INR")).upper()
|
||||
taxable = (amount / Decimal("1.0236") * Decimal("0.02")).quantize(Decimal("0.01")) if curr == "INR" else (amount / Decimal("1.03") * Decimal("0.03")).quantize(Decimal("0.01"))
|
||||
gst = (taxable * Decimal("0.18")).quantize(Decimal("0.01")) if curr == "INR" else Decimal("0")
|
||||
base = amount - taxable - gst
|
||||
self.session.add(
|
||||
Invoice(
|
||||
payment_transaction_id=tx.id,
|
||||
invoice_number=inv_id,
|
||||
billing_name=customer["name"],
|
||||
billing_email=customer["email"],
|
||||
billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}" if profile else "Not Configured",
|
||||
base_amount=base,
|
||||
discount_amount=Decimal("0"),
|
||||
taxable_amount=taxable,
|
||||
gst_amount=gst,
|
||||
total_amount=amount,
|
||||
currency_code=curr,
|
||||
exchange_rate_to_inr=Decimal("1"),
|
||||
total_amount_inr=amount if curr == "INR" else None,
|
||||
)
|
||||
)
|
||||
await self.session.commit()
|
||||
return url, inv_id, customer["email"]
|
||||
|
||||
async def share_invoice(self, payment_id: str) -> dict:
|
||||
url, num, email = await self.get_or_create_invoice(payment_id)
|
||||
if not url:
|
||||
raise LookupError("Could not retrieve or generate invoice.")
|
||||
return {"status": "success", "message": f"Invoice {num} shared to {email}"}
|
||||
|
||||
async def render_invoice_html(self, payment_id: str) -> HTMLResponse:
|
||||
tx = (await self.session.execute(
|
||||
select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id == payment_id)
|
||||
)).scalar_one_or_none()
|
||||
|
||||
user = (await self.session.execute(select(AppUser).where(AppUser.id == tx.user_id))).scalar_one_or_none() if tx else None
|
||||
invoice = (await self.session.execute(select(Invoice).where(Invoice.payment_transaction_id == tx.id))).scalar_one_or_none() if tx else None
|
||||
|
||||
profile = None
|
||||
if user:
|
||||
profile = (await self.session.execute(
|
||||
select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
|
||||
)).scalar_one_or_none()
|
||||
|
||||
rzp_payment = {}
|
||||
try:
|
||||
rzp_payment = get_razorpay_service().fetch_payment(payment_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cust_name = (invoice.billing_name if invoice else None) or (profile.billing_name if profile else None) or (user.display_name if user else None) or rzp_payment.get("email", "").split("@")[0].title() or "Valued Customer"
|
||||
cust_email = (invoice.billing_email if invoice else None) or (profile.billing_email if profile else None) or (user.email if user else None) or rzp_payment.get("email") or "customer@example.com"
|
||||
cust_phone = (profile.billing_phone if profile else None) or (user.phone_number if user else None) or rzp_payment.get("contact") or ""
|
||||
|
||||
# Clean address string
|
||||
clean_addr_parts = []
|
||||
if profile:
|
||||
for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]:
|
||||
if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]:
|
||||
clean_addr_parts.append(p.strip())
|
||||
c = profile.country or (user.country if user else None)
|
||||
if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]:
|
||||
clean_addr_parts.append(c.strip())
|
||||
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
|
||||
clean_addr_parts.append(user.country.strip())
|
||||
elif invoice and invoice.billing_address and "not configured" not in invoice.billing_address.lower():
|
||||
clean_addr_parts.append(invoice.billing_address.strip())
|
||||
|
||||
cust_address = ", ".join(clean_addr_parts) if clean_addr_parts else (user.country if user and user.country else "Digital Access")
|
||||
|
||||
inv_number = (invoice.invoice_number if invoice else None) or f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}"
|
||||
inv_date = invoice.created_at.strftime("%B %d, %Y") if invoice and invoice.created_at else (tx.created_at.strftime("%B %d, %Y") if tx and tx.created_at else datetime.now(timezone.utc).strftime("%B %d, %Y"))
|
||||
|
||||
currency = (invoice.currency_code if invoice else None) or (tx.currency if tx else None) or str(rzp_payment.get("currency", "USD")).upper()
|
||||
curr_symbol = "$" if currency == "USD" else ("₹" if currency == "INR" else f"{currency} ")
|
||||
|
||||
total_val = float(invoice.total_amount) if (invoice and invoice.total_amount is not None) else (float(tx.amount) if tx else float(rzp_payment.get("amount", 0)) / 100.0)
|
||||
base_val = total_val
|
||||
|
||||
# Item description
|
||||
item_desc = rzp_payment.get("description")
|
||||
if not item_desc:
|
||||
item_desc = "Clinical Access Plan Subscription"
|
||||
|
||||
pay_method = str(rzp_payment.get("method", "Online Gateway")).title()
|
||||
if pay_method.lower() == "card" and rzp_payment.get("card"):
|
||||
card_network = rzp_payment["card"].get("network", "Card")
|
||||
card_last4 = rzp_payment["card"].get("last4", "")
|
||||
pay_method = f"{card_network} ending in •••• {card_last4}" if card_last4 else card_network
|
||||
|
||||
html = f"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Tax Invoice - {inv_number}</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
* {{
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}}
|
||||
body {{
|
||||
background-color: #f8fafc;
|
||||
color: #1e293b;
|
||||
padding: 30px 16px;
|
||||
}}
|
||||
.no-print-bar {{
|
||||
max-width: 800px;
|
||||
margin: 0 auto 20px auto;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background: #ffffff;
|
||||
padding: 12px 20px;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
|
||||
border: 1px solid #e2e8f0;
|
||||
}}
|
||||
.btn {{
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
border: none;
|
||||
transition: all 0.15s ease;
|
||||
}}
|
||||
.btn-primary {{
|
||||
background-color: #4f46e5;
|
||||
color: #ffffff;
|
||||
}}
|
||||
.btn-primary:hover {{
|
||||
background-color: #4338ca;
|
||||
}}
|
||||
.btn-secondary {{
|
||||
background-color: #f1f5f9;
|
||||
color: #475569;
|
||||
}}
|
||||
.btn-secondary:hover {{
|
||||
background-color: #e2e8f0;
|
||||
}}
|
||||
.invoice-card {{
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
background: #ffffff;
|
||||
border-radius: 16px;
|
||||
padding: 40px;
|
||||
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
|
||||
border: 1px solid #e2e8f0;
|
||||
}}
|
||||
.header {{
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
border-bottom: 2px solid #f1f5f9;
|
||||
padding-bottom: 24px;
|
||||
margin-bottom: 28px;
|
||||
}}
|
||||
.logo-box h1 {{
|
||||
font-size: 24px;
|
||||
font-weight: 800;
|
||||
color: #4f46e5;
|
||||
letter-spacing: -0.5px;
|
||||
}}
|
||||
.logo-box p {{
|
||||
font-size: 13px;
|
||||
color: #64748b;
|
||||
margin-top: 2px;
|
||||
}}
|
||||
.invoice-badge-box {{
|
||||
text-align: right;
|
||||
}}
|
||||
.badge-paid {{
|
||||
display: inline-block;
|
||||
background: #ecfdf5;
|
||||
color: #059669;
|
||||
padding: 4px 12px;
|
||||
border-radius: 9999px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
border: 1px solid #a7f3d0;
|
||||
margin-bottom: 8px;
|
||||
}}
|
||||
.invoice-title {{
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: #0f172a;
|
||||
}}
|
||||
.invoice-num {{
|
||||
font-size: 13px;
|
||||
font-family: monospace;
|
||||
color: #64748b;
|
||||
margin-top: 4px;
|
||||
}}
|
||||
.grid-details {{
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 24px;
|
||||
margin-bottom: 32px;
|
||||
}}
|
||||
.section-label {{
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 6px;
|
||||
}}
|
||||
.detail-text {{
|
||||
font-size: 14px;
|
||||
color: #334155;
|
||||
line-height: 1.5;
|
||||
}}
|
||||
.detail-strong {{
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
}}
|
||||
.table-wrap {{
|
||||
margin-bottom: 24px;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}}
|
||||
table {{
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
text-align: left;
|
||||
}}
|
||||
th {{
|
||||
background: #f8fafc;
|
||||
padding: 12px 16px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
color: #64748b;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
}}
|
||||
td {{
|
||||
padding: 16px;
|
||||
font-size: 14px;
|
||||
color: #334155;
|
||||
border-bottom: 1px solid #f1f5f9;
|
||||
}}
|
||||
tr:last-child td {{
|
||||
border-bottom: none;
|
||||
}}
|
||||
.summary-wrap {{
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-bottom: 32px;
|
||||
}}
|
||||
.summary-card {{
|
||||
width: 320px;
|
||||
background: #f8fafc;
|
||||
border-radius: 12px;
|
||||
padding: 16px 20px;
|
||||
border: 1px solid #e2e8f0;
|
||||
}}
|
||||
.summary-row {{
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 13px;
|
||||
color: #64748b;
|
||||
margin-bottom: 8px;
|
||||
}}
|
||||
.summary-row.total {{
|
||||
border-top: 2px solid #cbd5e1;
|
||||
padding-top: 10px;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: #0f172a;
|
||||
}}
|
||||
.footer-note {{
|
||||
border-top: 1px dashed #e2e8f0;
|
||||
padding-top: 20px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
line-height: 1.6;
|
||||
}}
|
||||
@media print {{
|
||||
body {{
|
||||
background-color: #ffffff !important;
|
||||
padding: 0 !important;
|
||||
}}
|
||||
.no-print-bar {{
|
||||
display: none !important;
|
||||
}}
|
||||
.invoice-card {{
|
||||
box-shadow: none !important;
|
||||
border: none !important;
|
||||
padding: 20px 0 !important;
|
||||
max-width: 100% !important;
|
||||
}}
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="no-print-bar">
|
||||
<div style="font-size: 13px; color: #64748b; font-weight: 500;">
|
||||
Acupedia Official Tax Invoice • <strong>{inv_number}</strong>
|
||||
</div>
|
||||
<div style="display: flex; gap: 8px;">
|
||||
<button class="btn btn-secondary" onclick="window.close()">Close</button>
|
||||
<button class="btn btn-primary" onclick="window.print()">
|
||||
<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path></svg>
|
||||
Print / Save PDF
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="invoice-card">
|
||||
<div class="header">
|
||||
<div class="logo-box">
|
||||
<h1>ACUPEDIA ACCESS</h1>
|
||||
<p>Clinical Reference & TCM Modular Portal</p>
|
||||
<p style="font-size: 12px; color: #94a3b8; margin-top: 4px;">billing@acupedia.in • acupedia.in</p>
|
||||
</div>
|
||||
<div class="invoice-badge-box">
|
||||
<span class="badge-paid">✓ PAID</span>
|
||||
<div class="invoice-title">TAX INVOICE</div>
|
||||
<div class="invoice-num">No: {inv_number}</div>
|
||||
<div style="font-size: 12px; color: #64748b; margin-top: 2px;">Date: {inv_date}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid-details">
|
||||
<div>
|
||||
<div class="section-label">Billed To</div>
|
||||
<div class="detail-text detail-strong">{cust_name}</div>
|
||||
<div class="detail-text">{cust_email}</div>
|
||||
{f'<div class="detail-text">{cust_phone}</div>' if cust_phone else ''}
|
||||
<div class="detail-text" style="color: #64748b; margin-top: 4px;">{cust_address}</div>
|
||||
</div>
|
||||
<div style="text-align: right;">
|
||||
<div class="section-label">Payment Overview</div>
|
||||
<div class="detail-text">Gateway Reference: <span class="detail-strong" style="font-family: monospace;">{payment_id}</span></div>
|
||||
<div class="detail-text">Payment Method: <span class="detail-strong">{pay_method}</span></div>
|
||||
<div class="detail-text">Currency: <span class="detail-strong">{currency}</span></div>
|
||||
<div class="detail-text">Status: <span class="detail-strong" style="color: #059669;">Completed / Captured</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 50px;">#</th>
|
||||
<th>Item Description</th>
|
||||
<th style="text-align: center; width: 80px;">Qty</th>
|
||||
<th style="text-align: right; width: 120px;">Price</th>
|
||||
<th style="text-align: right; width: 120px;">Total</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>1</td>
|
||||
<td>
|
||||
<div style="font-weight: 600; color: #0f172a;">{item_desc}</div>
|
||||
<div style="font-size: 12px; color: #64748b; margin-top: 2px;">Digital Subscription & Clinical Module Access</div>
|
||||
</td>
|
||||
<td style="text-align: center;">1</td>
|
||||
<td style="text-align: right;">{curr_symbol}{total_val:.2f}</td>
|
||||
<td style="text-align: right; font-weight: 600;">{curr_symbol}{total_val:.2f}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="summary-wrap">
|
||||
<div class="summary-card">
|
||||
<div class="summary-row">
|
||||
<span>Base Subtotal:</span>
|
||||
<span>{curr_symbol}{base_val:.2f}</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span>Taxes & Fees (Included):</span>
|
||||
<span>{curr_symbol}0.00</span>
|
||||
</div>
|
||||
<div class="summary-row total">
|
||||
<span>Grand Total Paid:</span>
|
||||
<span style="color: #4f46e5;">{curr_symbol}{total_val:.2f} {currency}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer-note">
|
||||
This is an electronically generated Tax Invoice & Payment Receipt.<br>
|
||||
Thank you for choosing Acupedia Clinical TCM Systems. For inquiries or support, contact support@acupedia.in.
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>"""
|
||||
return HTMLResponse(content=html)
|
||||
|
|
@ -0,0 +1,236 @@
|
|||
from __future__ import annotations
|
||||
from decimal import Decimal
|
||||
from uuid import UUID
|
||||
from sqlalchemy import select, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.enums import BillingPeriod, PlanType, SubscriptionStatus
|
||||
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Module, UserSubscription
|
||||
from ..schema import CreatePlanRequest, PlanPricingUpdateRequest, PlanStatusUpdateRequest
|
||||
from .module_service import UI_MAPPINGS
|
||||
|
||||
|
||||
class AdminPlanService:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self.session = session
|
||||
|
||||
async def list_plans(self) -> list[dict]:
|
||||
all_plans = (await self.session.execute(
|
||||
select(AccessPlan).order_by(AccessPlan.created_at.asc())
|
||||
)).scalars().all()
|
||||
|
||||
plan_mods_q = await self.session.execute(
|
||||
select(AccessPlanModule.plan_id, Module)
|
||||
.join(Module, AccessPlanModule.module_id == Module.id)
|
||||
)
|
||||
plan_mods_map: dict[str, list[dict]] = {}
|
||||
for pid, m in plan_mods_q.all():
|
||||
p_str = str(pid)
|
||||
if p_str not in plan_mods_map:
|
||||
plan_mods_map[p_str] = []
|
||||
meta = m.metadata_json or {}
|
||||
ui = UI_MAPPINGS.get(m.slug, {})
|
||||
plan_mods_map[p_str].append({
|
||||
"id": str(m.id),
|
||||
"slug": m.slug,
|
||||
"name": m.name,
|
||||
"category": meta.get("category") or ui.get("category", "General"),
|
||||
"icon": meta.get("icon") or ui.get("icon", "book-outline"),
|
||||
"color": meta.get("color") or ui.get("color", "#6366F1"),
|
||||
"is_active": m.is_active,
|
||||
})
|
||||
|
||||
sub_counts_q = await self.session.execute(
|
||||
select(UserSubscription.plan_id, func.count(UserSubscription.id))
|
||||
.where(UserSubscription.status == SubscriptionStatus.ACTIVE)
|
||||
.group_by(UserSubscription.plan_id)
|
||||
)
|
||||
sub_counts = {str(row[0]): row[1] for row in sub_counts_q.all()}
|
||||
|
||||
groups: dict[str, dict] = {}
|
||||
for p in all_plans:
|
||||
code = p.code
|
||||
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
||||
base_code = code[:-4] if code.endswith("_USD") else code
|
||||
p_str = str(p.id)
|
||||
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
||||
meta = p.metadata_json or {}
|
||||
|
||||
if base_code not in groups:
|
||||
groups[base_code] = {
|
||||
"base_code": base_code,
|
||||
"name": p.name.replace(" (USD)", "").replace(" - USD", ""),
|
||||
"description": p.description or "",
|
||||
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
||||
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
||||
"is_active": p.is_active,
|
||||
"is_featured": meta.get("is_featured", False),
|
||||
"badge_text": meta.get("badge_text"),
|
||||
"heading": meta.get("heading"),
|
||||
"subtitle": meta.get("subtitle"),
|
||||
"inr_plan_id": None,
|
||||
"usd_plan_id": None,
|
||||
"price_inr": 0.0,
|
||||
"price_usd": 0.0,
|
||||
"modules": [],
|
||||
"module_ids": [],
|
||||
"subscribers_count": 0,
|
||||
"created_at": p.created_at.isoformat() if p.created_at else None,
|
||||
}
|
||||
|
||||
grp = groups[base_code]
|
||||
if is_usd:
|
||||
grp["usd_plan_id"] = p_str
|
||||
grp["price_usd"] = fee
|
||||
else:
|
||||
grp["inr_plan_id"] = p_str
|
||||
grp["price_inr"] = fee
|
||||
grp["name"] = p.name
|
||||
grp["description"] = p.description or ""
|
||||
grp["plan_type"] = getattr(p.plan_type, "value", p.plan_type)
|
||||
grp["billing_period"] = getattr(p.billing_period, "value", p.billing_period)
|
||||
grp["is_active"] = p.is_active
|
||||
grp["is_featured"] = meta.get("is_featured", False)
|
||||
if p.created_at:
|
||||
grp["created_at"] = p.created_at.isoformat()
|
||||
|
||||
if meta.get("badge_text"):
|
||||
grp["badge_text"] = meta.get("badge_text")
|
||||
if meta.get("heading"):
|
||||
grp["heading"] = meta.get("heading")
|
||||
if meta.get("subtitle"):
|
||||
grp["subtitle"] = meta.get("subtitle")
|
||||
|
||||
grp["subscribers_count"] += sub_counts.get(p_str, 0)
|
||||
mods = plan_mods_map.get(p_str, [])
|
||||
if mods and not grp["modules"]:
|
||||
grp["modules"] = mods
|
||||
grp["module_ids"] = [m["id"] for m in mods]
|
||||
|
||||
res = list(groups.values())
|
||||
def sort_key(item: dict) -> tuple[int, str]:
|
||||
if "LIFETIME" in item["base_code"]:
|
||||
return (0, item["name"])
|
||||
if item["plan_type"] == "bundle":
|
||||
return (1, item["name"])
|
||||
return (2, item["name"])
|
||||
res.sort(key=sort_key)
|
||||
return res
|
||||
|
||||
async def create_plan(self, payload: CreatePlanRequest, admin: AppUser) -> dict:
|
||||
base_code = payload.code.strip().upper()
|
||||
if not base_code:
|
||||
raise ValueError("Plan code cannot be empty.")
|
||||
|
||||
existing = (await self.session.execute(
|
||||
select(AccessPlan.id).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||
)).scalar_one_or_none()
|
||||
if existing:
|
||||
raise ValueError(f"Plan code '{base_code}' already exists.")
|
||||
|
||||
meta = {
|
||||
"is_featured": payload.is_featured,
|
||||
"badge_text": payload.badge_text,
|
||||
"heading": payload.heading,
|
||||
"subtitle": payload.subtitle,
|
||||
"created_by_admin": str(admin.id),
|
||||
}
|
||||
|
||||
p_type = PlanType(payload.plan_type) if payload.plan_type in PlanType.__members__.values() else PlanType.BUNDLE
|
||||
b_period = BillingPeriod(payload.billing_period) if payload.billing_period in BillingPeriod.__members__.values() else BillingPeriod.YEARLY
|
||||
|
||||
inr_plan = AccessPlan(
|
||||
code=base_code,
|
||||
name=payload.name,
|
||||
description=payload.description or "",
|
||||
plan_type=p_type,
|
||||
billing_period=b_period,
|
||||
member_fee=Decimal(0),
|
||||
module_fee=Decimal(str(payload.price_inr)),
|
||||
currency_code="INR",
|
||||
country="India",
|
||||
is_active=True,
|
||||
metadata_json=meta,
|
||||
)
|
||||
self.session.add(inr_plan)
|
||||
|
||||
usd_plan = AccessPlan(
|
||||
code=f"{base_code}_USD",
|
||||
name=f"{payload.name} (USD)",
|
||||
description=payload.description or "",
|
||||
plan_type=p_type,
|
||||
billing_period=b_period,
|
||||
member_fee=Decimal(0),
|
||||
module_fee=Decimal(str(payload.price_usd)),
|
||||
currency_code="USD",
|
||||
country="International",
|
||||
is_active=True,
|
||||
metadata_json=meta,
|
||||
)
|
||||
self.session.add(usd_plan)
|
||||
await self.session.flush()
|
||||
|
||||
for mid_str in payload.module_ids:
|
||||
try:
|
||||
mid = UUID(mid_str)
|
||||
self.session.add(AccessPlanModule(plan_id=inr_plan.id, module_id=mid))
|
||||
self.session.add(AccessPlanModule(plan_id=usd_plan.id, module_id=mid))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await self.session.commit()
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Plan '{payload.name}' created successfully with INR and USD tiers.",
|
||||
"base_code": base_code,
|
||||
"inr_plan_id": str(inr_plan.id),
|
||||
"usd_plan_id": str(usd_plan.id),
|
||||
}
|
||||
|
||||
async def update_pricing(self, plan_code: str, payload: PlanPricingUpdateRequest) -> dict:
|
||||
base_code = plan_code.strip().upper()
|
||||
plans = (await self.session.execute(
|
||||
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||
)).scalars().all()
|
||||
if not plans:
|
||||
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
||||
|
||||
for p in plans:
|
||||
is_usd = p.code.endswith("_USD") or p.currency_code == "USD"
|
||||
if is_usd and payload.price_usd is not None:
|
||||
p.module_fee = Decimal(str(payload.price_usd))
|
||||
elif not is_usd and payload.price_inr is not None:
|
||||
p.module_fee = Decimal(str(payload.price_inr))
|
||||
|
||||
if payload.name:
|
||||
p.name = f"{payload.name} (USD)" if is_usd else payload.name
|
||||
if payload.description is not None:
|
||||
p.description = payload.description
|
||||
|
||||
meta = dict(p.metadata_json or {})
|
||||
if payload.badge_text is not None:
|
||||
meta["badge_text"] = payload.badge_text
|
||||
if payload.heading is not None:
|
||||
meta["heading"] = payload.heading
|
||||
if payload.subtitle is not None:
|
||||
meta["subtitle"] = payload.subtitle
|
||||
p.metadata_json = meta
|
||||
|
||||
await self.session.commit()
|
||||
return {"status": "success", "message": f"Pricing and metadata for plan '{base_code}' updated successfully."}
|
||||
|
||||
async def toggle_status(self, plan_code: str, is_active: bool) -> dict:
|
||||
base_code = plan_code.strip().upper()
|
||||
plans = (await self.session.execute(
|
||||
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||
)).scalars().all()
|
||||
if not plans:
|
||||
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
||||
|
||||
for p in plans:
|
||||
p.is_active = is_active
|
||||
await self.session.commit()
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Plan '{base_code}' has been {'activated' if is_active else 'deactivated'}.",
|
||||
"is_active": is_active,
|
||||
}
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
from __future__ import annotations
|
||||
import csv
|
||||
import io
|
||||
from datetime import datetime, timezone
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.models import AccessPlan, AppUser, Coupon, Invoice, PaymentTransaction, 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()
|
||||
writer.writerow(["ID", "Email", "Display Name", "Phone Number", "Country", "Active", "Created At"])
|
||||
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 ""])
|
||||
|
||||
elif report_type == "payments":
|
||||
q = (
|
||||
select(PaymentTransaction, Invoice, AppUser)
|
||||
.join(Invoice, Invoice.payment_transaction_id == PaymentTransaction.id, isouter=True)
|
||||
.join(AppUser, AppUser.id == PaymentTransaction.user_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(["ID", "Gateway ID", "User Email", "User Name", "Amount", "Currency", "Status", "Invoice Number", "Created At"])
|
||||
for t, inv, u in rows:
|
||||
writer.writerow([
|
||||
str(t.id),
|
||||
t.gateway_transaction_id,
|
||||
u.email if u else "",
|
||||
u.display_name if u else "",
|
||||
float(t.amount),
|
||||
t.currency,
|
||||
getattr(t.status, "value", t.status),
|
||||
inv.invoice_number if inv else "",
|
||||
t.created_at.isoformat() if t.created_at else "",
|
||||
])
|
||||
|
||||
elif report_type == "subscriptions":
|
||||
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(["ID", "User Email", "User Name", "Plan Code", "Plan Name", "Status", "Started At", "Expires At", "Payment Reference"])
|
||||
for s, p, u in rows:
|
||||
writer.writerow([
|
||||
str(s.id),
|
||||
u.email if u else "",
|
||||
u.display_name if u else "",
|
||||
p.code if p else "",
|
||||
p.name if p else "",
|
||||
getattr(s.status, "value", s.status),
|
||||
s.started_at.isoformat() if s.started_at else "",
|
||||
s.expires_at.isoformat() if s.expires_at else "",
|
||||
s.payment_reference or "",
|
||||
])
|
||||
|
||||
elif report_type == "coupons":
|
||||
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"])
|
||||
for c in coupons:
|
||||
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 "",
|
||||
])
|
||||
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}"'}
|
||||
)
|
||||
|
|
@ -126,6 +126,7 @@ class AuthRepository:
|
|||
user_id: UUID,
|
||||
display_name: str | None,
|
||||
phone_number: str | None,
|
||||
country: str | None = None,
|
||||
) -> AppUser | None:
|
||||
values: dict[str, object] = {}
|
||||
|
||||
|
|
@ -133,6 +134,8 @@ class AuthRepository:
|
|||
values["display_name"] = display_name
|
||||
if phone_number is not None:
|
||||
values["phone_number"] = phone_number
|
||||
if country is not None:
|
||||
values["country"] = country
|
||||
|
||||
if values:
|
||||
await self._session.execute(
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ class ProfileUpdateRequest(StrictModel):
|
|||
full_name: str | None = Field(default=None, max_length=255)
|
||||
email: str | None = Field(default=None, max_length=320)
|
||||
phone_number: str | None = Field(default=None, max_length=64)
|
||||
country: str | None = Field(default=None, max_length=128)
|
||||
|
||||
|
||||
class ChangePasswordRequest(StrictModel):
|
||||
|
|
|
|||
|
|
@ -218,11 +218,13 @@ class AuthService:
|
|||
if request.phone_number
|
||||
else None
|
||||
)
|
||||
country = request.country.strip() if request.country else None
|
||||
|
||||
user = await self.repository.update_profile(
|
||||
user_id=user_id,
|
||||
display_name=full_name,
|
||||
phone_number=phone,
|
||||
country=country,
|
||||
)
|
||||
if user is None:
|
||||
raise UserNotFoundError("User not found.")
|
||||
|
|
|
|||
|
|
@ -0,0 +1,95 @@
|
|||
from __future__ import annotations
|
||||
from typing import Any
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from app.db.session import get_db_session
|
||||
from app.db.models import AccessPlan, AccessPlanModule, Module
|
||||
|
||||
router = APIRouter(tags=["Public Plans Catalog"])
|
||||
|
||||
@router.get("/plans")
|
||||
async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Returns active subscription plans with dynamic prices in INR & USD
|
||||
and included clinical module slugs for dynamic storefront rendering.
|
||||
"""
|
||||
plans_q = await session.execute(
|
||||
select(AccessPlan)
|
||||
.where(AccessPlan.is_active.is_(True))
|
||||
.order_by(AccessPlan.created_at.asc())
|
||||
)
|
||||
all_plans = plans_q.scalars().all()
|
||||
|
||||
plan_mods_q = await session.execute(
|
||||
select(AccessPlanModule.plan_id, Module.slug, Module.name)
|
||||
.join(Module, AccessPlanModule.module_id == Module.id)
|
||||
.where(Module.is_active.is_(True))
|
||||
)
|
||||
mod_map: dict[str, list[dict[str, str]]] = {}
|
||||
for pid, slug, name in plan_mods_q.all():
|
||||
pid_str = str(pid)
|
||||
if pid_str not in mod_map:
|
||||
mod_map[pid_str] = []
|
||||
mod_map[pid_str].append({"slug": slug, "name": name})
|
||||
|
||||
groups: dict[str, dict[str, Any]] = {}
|
||||
for p in all_plans:
|
||||
code = p.code
|
||||
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
||||
base_code = code[:-4] if code.endswith("_USD") else code
|
||||
pid_str = str(p.id)
|
||||
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
||||
|
||||
meta = p.metadata_json or {}
|
||||
if base_code not in groups:
|
||||
groups[base_code] = {
|
||||
"code": base_code,
|
||||
"name": p.name.replace(" (USD)", "").replace(" - USD", ""),
|
||||
"description": p.description or "",
|
||||
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
||||
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
||||
"price_inr": 0.0,
|
||||
"price_usd": 0.0,
|
||||
"is_active": p.is_active,
|
||||
"badge_text": meta.get("badge_text"),
|
||||
"heading": meta.get("heading"),
|
||||
"subtitle": meta.get("subtitle"),
|
||||
"modules": [],
|
||||
"module_slugs": [],
|
||||
"is_featured": meta.get("is_featured", False),
|
||||
}
|
||||
|
||||
grp = groups[base_code]
|
||||
if is_usd:
|
||||
grp["price_usd"] = fee
|
||||
else:
|
||||
grp["price_inr"] = fee
|
||||
grp["name"] = p.name
|
||||
grp["description"] = p.description or ""
|
||||
grp["plan_type"] = getattr(p.plan_type, "value", p.plan_type)
|
||||
grp["billing_period"] = getattr(p.billing_period, "value", p.billing_period)
|
||||
grp["is_active"] = p.is_active
|
||||
grp["is_featured"] = meta.get("is_featured", False)
|
||||
if meta.get("badge_text"):
|
||||
grp["badge_text"] = meta.get("badge_text")
|
||||
if meta.get("heading"):
|
||||
grp["heading"] = meta.get("heading")
|
||||
if meta.get("subtitle"):
|
||||
grp["subtitle"] = meta.get("subtitle")
|
||||
|
||||
if pid_str in mod_map and not grp["modules"]:
|
||||
grp["modules"] = mod_map[pid_str]
|
||||
grp["module_slugs"] = [m["slug"] for m in mod_map[pid_str]]
|
||||
|
||||
result = list(groups.values())
|
||||
|
||||
def sort_key(item: dict[str, Any]) -> tuple[int, str]:
|
||||
if "LIFETIME" in str(item["code"]):
|
||||
return (0, str(item["name"]))
|
||||
if item["plan_type"] == "bundle":
|
||||
return (1, str(item["name"]))
|
||||
return (2, str(item["name"]))
|
||||
|
||||
result.sort(key=sort_key)
|
||||
return result
|
||||
61
app/main.py
61
app/main.py
|
|
@ -1,4 +1,5 @@
|
|||
from fastapi import FastAPI
|
||||
from typing import Any
|
||||
from fastapi import FastAPI, Depends
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
import uvicorn
|
||||
|
|
@ -12,13 +13,18 @@ from app.features.content.api import router as contents_router
|
|||
from app.features.search.api import router as search_router
|
||||
from app.features.cart import router as cart_router
|
||||
from app.features.checkout import router as checkout_router
|
||||
from app.features.plans import router as plans_router
|
||||
from app.features.admin import router as admin_router
|
||||
from app.features.webhooks import router as webhooks_router
|
||||
|
||||
from app.cache.health import router as cache_health_router
|
||||
|
||||
from app.core.settings import settings
|
||||
<<<<<<< HEAD
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
=======
|
||||
from app.core.exception_handlers import register_exception_handlers
|
||||
>>>>>>> origin/main
|
||||
from app.db.session import get_db_session
|
||||
from app.lifespan import lifespan
|
||||
|
||||
|
|
@ -40,7 +46,9 @@ app.add_middleware(
|
|||
"http://localhost:8081",
|
||||
"http://127.0.0.1:8081",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000"
|
||||
"http://127.0.0.1:3000",
|
||||
"http://localhost:3001",
|
||||
"http://127.0.0.1:3001",
|
||||
],
|
||||
allow_origin_regex=r"https?://.*",
|
||||
allow_credentials=True,
|
||||
|
|
@ -51,7 +59,8 @@ app.add_middleware(
|
|||
# Register API routers
|
||||
app.include_router(auth_router, prefix="/api")
|
||||
app.include_router(access_router, prefix="/api")
|
||||
app.include_router(contents_router,prefix="/api")
|
||||
app.include_router(contents_router, prefix="/api")
|
||||
app.include_router(plans_router, prefix="/api")
|
||||
app.include_router(cart_router, prefix="/api")
|
||||
app.include_router(checkout_router, prefix="/api")
|
||||
app.include_router(admin_router, prefix="/api")
|
||||
|
|
@ -60,36 +69,24 @@ app.include_router(cache_health_router, prefix="/api")
|
|||
app.include_router(search_router, prefix="/api")
|
||||
|
||||
|
||||
# @app.get("/")
|
||||
# async def root() -> dict[str,Any]:
|
||||
# connection = await get_db_session()
|
||||
# try:
|
||||
# with connection.cursor() as cursor:
|
||||
# cursor.execute("SELECT current_database();")
|
||||
# database_name = cursor.fetchone()[0]
|
||||
# finally:
|
||||
# connection.close()
|
||||
@app.get("/")
|
||||
async def root(session: AsyncSession = Depends(get_db_session)) -> dict[str, Any]:
|
||||
from sqlalchemy import text
|
||||
db_name = "acupedia_db"
|
||||
try:
|
||||
res = await session.execute(text("SELECT current_database();"))
|
||||
db_name = res.scalar_one() or "acupedia_db"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# minio_status = "active"
|
||||
# bucket_count = 0
|
||||
# try:
|
||||
# minio_client = get_minio_client()
|
||||
# buckets = minio_client.list_buckets()
|
||||
# bucket_count = len(buckets)
|
||||
# except Exception:
|
||||
# minio_status = "MinIO not activated (bypassed)"
|
||||
|
||||
# return {
|
||||
# "status": "Acupedia Backend is Running",
|
||||
# "version": "1.0.0",
|
||||
# "docs_url": "/docs",
|
||||
# "environment": os.getenv("ENVIRONMENT", "development"),
|
||||
# "database_name": database_name,
|
||||
# "database_schema": settings.database_schema,
|
||||
# "minio_endpoint": settings.minio_endpoint,
|
||||
# "minio_status": minio_status,
|
||||
# "bucket_count": bucket_count if minio_status == "active" else "MinIO not activated, bypassing",
|
||||
# }
|
||||
return {
|
||||
"status": "Acupedia Backend is Running",
|
||||
"version": "1.0.0",
|
||||
"docs_url": "/docs",
|
||||
"environment": os.getenv("ENVIRONMENT", "development"),
|
||||
"database_name": db_name,
|
||||
"database_schema": settings.database_schema,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
Loading…
Reference in New Issue