acupedia-api/app/features/admin/api.py

810 lines
28 KiB
Python

from __future__ import annotations
import io
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,
CreateCouponRequest,
CreatePlanRequest,
CustomerStatusUpdateRequest,
ModuleStatusUpdateRequest,
ModuleUpdateRequest,
PlanPricingUpdateRequest,
PlanStatusUpdateRequest,
UpdateCouponRequest,
)
from .builder_schema import (
BuilderModuleSummary,
CreateBuilderModuleRequest,
UpdateBuilderModuleRequest,
BuilderCategorySummary,
BuilderDiseaseDetailResponse,
BuilderDiseaseSummary,
ModuleBuilderExportResponse,
ModuleBuilderImportRequest,
ModuleBuilderImportResponse,
SaveCategoryRequest,
SaveDiseaseRequest,
SaveFullDiseaseRequest,
)
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
@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
# =============================================================================
# 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
],
}
except Exception as 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
],
}
except Exception as 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
],
}
except Exception as 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),
):
try:
from sqlalchemy import select
from app.db.models import Invoice, PaymentTransaction
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()
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
],
}
except Exception as 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),
):
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: {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
# =============================================================================
# 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),
):
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),
):
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),
):
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
@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
# =============================================================================
# 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
except ValueError as exc:
raise HTTPException(400, 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
# =============================================================================
# MODULE BUILDER ENDPOINTS
# =============================================================================
@router.get("/module-builder/modules", response_model=list[BuilderModuleSummary])
async def list_builder_modules(
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.get_modules()
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch module builder modules: {exc}") from exc
@router.post("/module-builder/modules", response_model=BuilderModuleSummary, status_code=status.HTTP_201_CREATED)
async def create_builder_module(
payload: CreateBuilderModuleRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.create_module(payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to create builder module: {exc}") from exc
@router.get("/module-builder/modules/{module_code}", response_model=BuilderModuleSummary)
async def get_builder_module(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.get_module(module_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch builder module: {exc}") from exc
@router.patch("/module-builder/modules/{module_code}", response_model=BuilderModuleSummary)
async def update_builder_module(
module_code: str,
payload: UpdateBuilderModuleRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.update_module(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to update builder module: {exc}") from exc
@router.delete("/module-builder/modules/{module_code}")
async def delete_builder_module(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.delete_module(module_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to delete builder module: {exc}") from exc
@router.get("/module-builder/{module_code}/categories", response_model=list[BuilderCategorySummary])
async def get_builder_categories(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.get_categories(module_code)
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch module builder categories: {exc}") from exc
@router.post("/module-builder/{module_code}/categories", response_model=BuilderCategorySummary)
async def save_builder_category(
module_code: str,
payload: SaveCategoryRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.save_category(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to save module builder category: {exc}") from exc
@router.delete("/module-builder/{module_code}/categories/{category_code}")
async def delete_builder_category(
module_code: str,
category_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
deleted = await service.builder.delete_category(module_code, category_code)
if not deleted:
raise HTTPException(404, detail="Category not found")
return {"success": True, "message": "Category deleted successfully"}
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to delete category: {exc}") from exc
@router.get("/module-builder/{module_code}/categories/{category_code}/diseases", response_model=list[BuilderDiseaseSummary])
async def get_builder_diseases(
module_code: str,
category_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.get_diseases(module_code, category_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch diseases: {exc}") from exc
@router.get("/module-builder/{module_code}/categories/{category_code}/diseases/{disease_code}", response_model=BuilderDiseaseDetailResponse)
async def get_builder_disease_detail(
module_code: str,
category_code: str,
disease_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
res = await service.builder.get_disease_detail(module_code, category_code, disease_code)
if not res:
raise HTTPException(404, detail="Disease not found")
return res
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch disease details: {exc}") from exc
@router.post("/module-builder/{module_code}/categories/{category_code}/diseases", response_model=BuilderDiseaseSummary)
async def save_builder_disease(
module_code: str,
category_code: str,
payload: SaveDiseaseRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
payload.category_code = category_code
return await service.builder.save_disease(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to save disease: {exc}") from exc
@router.delete("/module-builder/{module_code}/categories/{category_code}/diseases/{disease_code}")
async def delete_builder_disease(
module_code: str,
category_code: str,
disease_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
deleted = await service.builder.delete_disease(module_code, category_code, disease_code)
if not deleted:
raise HTTPException(404, detail="Disease not found")
return {"success": True, "message": "Disease deleted successfully"}
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to delete disease: {exc}") from exc
@router.post("/module-builder/{module_code}/save-full", response_model=BuilderDiseaseDetailResponse)
async def save_full_disease(
module_code: str,
payload: SaveFullDiseaseRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.save_full_disease(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to save full disease data: {exc}") from exc
@router.get("/module-builder/{module_code}/export-json", response_model=ModuleBuilderExportResponse)
async def export_module_json(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.export_module_json(module_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to export module JSON: {exc}") from exc
@router.get("/module-builder/{module_code}/export-bundle")
async def export_builder_module_bundle(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
filename, zip_bytes = await service.builder.export_bundle_zip(module_code)
return StreamingResponse(
io.BytesIO(zip_bytes),
media_type="application/zip",
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"Access-Control-Expose-Headers": "Content-Disposition",
},
)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to generate module package: {exc}") from exc
@router.post("/module-builder/{module_code}/sync-content-repo")
async def sync_builder_module_to_repo(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.sync_content_repo(module_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to sync module to content repository: {exc}") from exc
@router.post("/module-builder/{module_code}/import-json", response_model=ModuleBuilderImportResponse)
async def import_module_json(
module_code: str,
payload: ModuleBuilderImportRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.import_module_json(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to import module JSON: {exc}") from exc