keyvault-api / src /services /admin_service.py
hashir-qt's picture
Upload folder using huggingface_hub
e656014 verified
Raw History Blame Contribute Delete
7.06 kB
"""Admin dashboard business logic — platform stats, seller management."""
import logging
from sqlalchemy import func
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select
from src.models.order import Order, OrderItem
from src.models.seller_profile import SellerProfile, SellerStatus
from src.models.user import User, UserRole
from src.schemas.admin import AdminOrderView, AdminSellerView, AdminStatsResponse, AdminUserView
from src.utils.exceptions import NotFoundError
logger = logging.getLogger("marketplace.admin_service")
async def get_platform_stats(db: AsyncSession) -> AdminStatsResponse:
"""
Compute platform-wide KPIs for the admin dashboard.
Returns total user count (buyers + sellers), seller count,
order count, and gross merchandise value (GMV).
"""
total_users_result = await db.execute(
select(func.count(User.id)).where(User.role != UserRole.ADMIN)
)
total_users: int = total_users_result.scalar() or 0
total_sellers_result = await db.execute(
select(func.count(SellerProfile.id))
)
total_sellers: int = total_sellers_result.scalar() or 0
total_orders_result = await db.execute(
select(func.count(Order.id))
)
total_orders: int = total_orders_result.scalar() or 0
gmv_result = await db.execute(
select(func.sum(Order.total_price))
)
platform_gmv: float = round(gmv_result.scalar() or 0.0, 2)
return AdminStatsResponse(
total_users=total_users,
total_sellers=total_sellers,
total_orders=total_orders,
platform_gmv=platform_gmv,
)
async def get_recent_orders(
db: AsyncSession, limit: int = 20
) -> list[AdminOrderView]:
"""
Return the most recent orders across the entire platform.
Enriches each order with the buyer's username and the first
item's product title for display in the admin table.
Args:
db: Async database session.
limit: Max orders to return (default 20).
Returns:
List of AdminOrderView sorted newest-first.
"""
orders_result = await db.execute(
select(Order).order_by(Order.created_at.desc()).limit(limit)
)
orders = orders_result.scalars().all()
views: list[AdminOrderView] = []
for order in orders:
buyer = await db.get(User, order.buyer_id)
buyer_username = buyer.username if buyer else "unknown"
first_item_result = await db.execute(
select(OrderItem).where(OrderItem.order_id == order.id).limit(1)
)
first_item = first_item_result.scalars().first()
product_title = first_item.title_at_purchase if first_item else "—"
views.append(
AdminOrderView(
id=order.id,
product_title=product_title,
buyer_username=buyer_username,
created_at=order.created_at,
total_price=order.total_price,
status=order.status.value,
)
)
return views
async def get_all_sellers(db: AsyncSession) -> list[AdminSellerView]:
"""
Return all seller profiles with email, sorted pending-first.
Args:
db: Async database session.
Returns:
List of AdminSellerView (pending sellers shown first).
"""
result = await db.execute(select(SellerProfile))
sellers = result.scalars().all()
views: list[AdminSellerView] = []
for sp in sellers:
user = await db.get(User, sp.user_id)
if not user:
continue
views.append(
AdminSellerView(
id=sp.id,
user_id=sp.user_id,
store_name=sp.store_name,
store_description=sp.store_description,
email=user.email,
tier=sp.tier,
status=sp.status,
total_sales=sp.total_sales,
id_submitted=sp.id_submitted,
created_at=sp.created_at,
)
)
# Pending sellers first, then approved, then rejected
STATUS_ORDER = {SellerStatus.PENDING: 0, SellerStatus.APPROVED: 1, SellerStatus.REJECTED: 2}
views.sort(key=lambda v: STATUS_ORDER.get(v.status, 99))
return views
async def approve_seller(db: AsyncSession, seller_id: str) -> AdminSellerView:
"""
Approve a seller's account so they can list products.
Args:
db: Async database session.
seller_id: The SellerProfile ID.
Returns:
Updated AdminSellerView.
Raises:
NotFoundError: If the seller profile does not exist.
"""
sp = await db.get(SellerProfile, seller_id)
if not sp:
raise NotFoundError("SellerProfile", seller_id)
sp.status = SellerStatus.APPROVED
db.add(sp)
await db.commit()
await db.refresh(sp)
user = await db.get(User, sp.user_id)
logger.info("Seller %s approved by admin", seller_id)
return AdminSellerView(
id=sp.id,
user_id=sp.user_id,
store_name=sp.store_name,
store_description=sp.store_description,
email=user.email if user else "",
tier=sp.tier,
status=sp.status,
total_sales=sp.total_sales,
id_submitted=sp.id_submitted,
created_at=sp.created_at,
)
async def reject_seller(db: AsyncSession, seller_id: str) -> AdminSellerView:
"""
Reject a seller's account application.
Args:
db: Async database session.
seller_id: The SellerProfile ID.
Returns:
Updated AdminSellerView.
Raises:
NotFoundError: If the seller profile does not exist.
"""
sp = await db.get(SellerProfile, seller_id)
if not sp:
raise NotFoundError("SellerProfile", seller_id)
sp.status = SellerStatus.REJECTED
db.add(sp)
await db.commit()
await db.refresh(sp)
user = await db.get(User, sp.user_id)
logger.info("Seller %s rejected by admin", seller_id)
return AdminSellerView(
id=sp.id,
user_id=sp.user_id,
store_name=sp.store_name,
store_description=sp.store_description,
email=user.email if user else "",
tier=sp.tier,
status=sp.status,
total_sales=sp.total_sales,
id_submitted=sp.id_submitted,
created_at=sp.created_at,
)
async def get_all_users(db: AsyncSession) -> list[AdminUserView]:
"""
Return all non-admin users sorted newest-first.
Args:
db: Async database session.
Returns:
List of AdminUserView for every buyer and seller account.
"""
result = await db.execute(
select(User)
.where(User.role != UserRole.ADMIN)
.order_by(User.created_at.desc())
)
users = result.scalars().all()
return [
AdminUserView(
id=u.id,
email=u.email,
username=u.username,
full_name=u.full_name,
role=u.role.value,
is_active=u.is_active,
created_at=u.created_at,
)
for u in users
]