File size: 7,057 Bytes
e656014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""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
    ]