diff --git a/backend/apps/chat/tests/test_chat_api.py b/backend/apps/chat/tests/test_chat_api.py index f2b5486..58f76bc 100644 --- a/backend/apps/chat/tests/test_chat_api.py +++ b/backend/apps/chat/tests/test_chat_api.py @@ -97,6 +97,22 @@ def test_admin_can_list_conversations_and_reply( ) +@pytest.mark.django_db +def test_admin_gets_a_conversation_summary( + admin_client: APIClient, customer: User +) -> None: + conversation = Conversation.objects.create(customer=customer) + Message.objects.create(conversation=conversation, sender=customer, body="Need help") + + response = admin_client.get("/api/v1/chat/conversations/summary/") + + assert response.status_code == 200 + assert response.data["total"] == 1 + assert response.data["by_status"][Conversation.Status.OPEN] == 1 + assert response.data["unassigned_open"] == 1 + assert response.data["unread_customer_messages"] == 1 + + @pytest.mark.django_db def test_message_client_identifier_makes_rest_retries_idempotent( customer_client: APIClient, customer: User diff --git a/backend/apps/chat/urls.py b/backend/apps/chat/urls.py index e009414..442286e 100644 --- a/backend/apps/chat/urls.py +++ b/backend/apps/chat/urls.py @@ -3,6 +3,7 @@ from .views import ( AdminConversationListAPIView, AdminConversationManageAPIView, + AdminConversationSummaryAPIView, CustomerConversationAPIView, MessageListCreateAPIView, ) @@ -16,6 +17,11 @@ AdminConversationListAPIView.as_view(), name="conversation-list", ), + path( + "conversations/summary/", + AdminConversationSummaryAPIView.as_view(), + name="conversation-summary", + ), path( "conversations//", AdminConversationManageAPIView.as_view(), diff --git a/backend/apps/chat/views.py b/backend/apps/chat/views.py index 72c2e1a..ca1aae5 100644 --- a/backend/apps/chat/views.py +++ b/backend/apps/chat/views.py @@ -1,4 +1,5 @@ from django.db import transaction +from django.db.models import Count from rest_framework import status from rest_framework.exceptions import NotFound from rest_framework.generics import ListAPIView @@ -7,6 +8,8 @@ from rest_framework.response import Response from rest_framework.views import APIView +from apps.accounts.models import User + from .models import Conversation, Message from .permissions import IsPlatformAdmin from .serializers import ( @@ -42,6 +45,32 @@ def get_queryset(self): return Conversation.objects.select_related("customer", "assigned_admin") +class AdminConversationSummaryAPIView(APIView): + permission_classes = (IsPlatformAdmin,) + + def get(self, request): + by_status = {status: 0 for status, _ in Conversation.Status.choices} + for item in Conversation.objects.values("status").annotate(count=Count("id")): + by_status[item["status"]] = item["count"] + open_conversations = Conversation.objects.filter( + status=Conversation.Status.OPEN + ) + return Response( + { + "total": sum(by_status.values()), + "by_status": by_status, + "unassigned_open": open_conversations.filter( + assigned_admin__isnull=True + ).count(), + "unread_customer_messages": Message.objects.filter( + conversation__status=Conversation.Status.OPEN, + sender__role=User.Role.CUSTOMER, + read_at__isnull=True, + ).count(), + } + ) + + class AdminConversationManageAPIView(APIView): permission_classes = (IsPlatformAdmin,) diff --git a/backend/apps/orders/tests/test_admin_orders_api.py b/backend/apps/orders/tests/test_admin_orders_api.py index a5a7bb8..6745cee 100644 --- a/backend/apps/orders/tests/test_admin_orders_api.py +++ b/backend/apps/orders/tests/test_admin_orders_api.py @@ -93,6 +93,18 @@ def test_admin_lists_and_filters_orders( assert response.data["results"][0]["customer_phone"] == customer.phone +@pytest.mark.django_db +def test_admin_gets_an_order_summary( + admin_client: APIClient, paid_order: Order +) -> None: + response = admin_client.get("/api/v1/orders/admin/summary/") + + assert response.status_code == 200 + assert response.data["total"] == 1 + assert response.data["by_status"][Order.Status.PAID] == 1 + assert response.data["by_status"][Order.Status.PENDING] == 0 + + @pytest.mark.django_db def test_admin_can_move_paid_order_through_fulfilment( admin_client: APIClient, paid_order: Order diff --git a/backend/apps/orders/urls.py b/backend/apps/orders/urls.py index 1a6d147..21d763b 100644 --- a/backend/apps/orders/urls.py +++ b/backend/apps/orders/urls.py @@ -4,6 +4,7 @@ AddressListCreateAPIView, AdminOrderListAPIView, AdminOrderStatusAPIView, + AdminOrderSummaryAPIView, CheckoutAPIView, OrderListAPIView, StartPaymentAPIView, @@ -15,6 +16,11 @@ urlpatterns = [ path("addresses/", AddressListCreateAPIView.as_view(), name="address-list"), path("admin/", AdminOrderListAPIView.as_view(), name="admin-order-list"), + path( + "admin/summary/", + AdminOrderSummaryAPIView.as_view(), + name="admin-order-summary", + ), path( "admin//status/", AdminOrderStatusAPIView.as_view(), diff --git a/backend/apps/orders/views.py b/backend/apps/orders/views.py index 6813902..41225f2 100644 --- a/backend/apps/orders/views.py +++ b/backend/apps/orders/views.py @@ -1,6 +1,6 @@ from django.contrib.auth import get_user_model from django.db import transaction -from django.db.models import Q +from django.db.models import Count, Q from django.http import HttpResponseRedirect from rest_framework import status from rest_framework.exceptions import NotFound, ValidationError @@ -77,6 +77,16 @@ def get_queryset(self): return queryset +class AdminOrderSummaryAPIView(APIView): + permission_classes = (IsPlatformAdmin,) + + def get(self, request): + by_status = {status: 0 for status, _ in Order.Status.choices} + for item in Order.objects.values("status").annotate(count=Count("id")): + by_status[item["status"]] = item["count"] + return Response({"total": sum(by_status.values()), "by_status": by_status}) + + class AdminOrderStatusAPIView(APIView): permission_classes = (IsPlatformAdmin,) diff --git a/backend/config/asgi.py b/backend/config/asgi.py index 5c75d5b..f6b5d08 100644 --- a/backend/config/asgi.py +++ b/backend/config/asgi.py @@ -3,16 +3,21 @@ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.base") from channels.routing import ProtocolTypeRouter, URLRouter +from django.conf import settings +from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() +http_application = ( + ASGIStaticFilesHandler(django_asgi_app) if settings.DEBUG else django_asgi_app +) from apps.chat.realtime import JwtAuthMiddleware from apps.chat.routing import websocket_urlpatterns application = ProtocolTypeRouter( { - "http": django_asgi_app, + "http": http_application, "websocket": JwtAuthMiddleware(URLRouter(websocket_urlpatterns)), } ) diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index f62ea1b..6fc7767 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -105,6 +105,16 @@ type AdminOrder = Order & { type AdminOrdersResponse = Omit & { results: AdminOrder[]; }; +type OrderSummary = { + total: number; + by_status: Record; +}; +type ConversationSummary = { + total: number; + by_status: Record; + unassigned_open: number; + unread_customer_messages: number; +}; type Conversation = { id: string; customer_phone: string; @@ -144,6 +154,7 @@ type Route = | { name: "checkout" } | { name: "payment-result" } | { name: "profile" } + | { name: "admin-dashboard" } | { name: "admin-orders" } | { name: "chat" } | { name: "admin-chat" } @@ -166,6 +177,8 @@ function getRoute(): Route { if (parts[0] === "payment-result" && parts.length === 1) return { name: "payment-result" }; if (parts[0] === "profile" && parts.length === 1) return { name: "profile" }; + if (parts[0] === "admin" && parts.length === 1) + return { name: "admin-dashboard" }; if (parts[0] === "admin" && parts[1] === "orders" && parts.length === 2) return { name: "admin-orders" }; if (parts[0] === "chat" && parts.length === 1) return { name: "chat" }; @@ -1320,6 +1333,9 @@ function ProfilePage({ {user.role === "admin" && (
+ + نمای کلی مدیریت + مدیریت سفارش‌ها @@ -1433,6 +1449,126 @@ function ProfilePage({ ); } +function AdminDashboardPage({ user }: { user: AuthUser | null }) { + const [orders, setOrders] = useState(null); + const [conversations, setConversations] = + useState(null); + const [error, setError] = useState(""); + + useEffect(() => { + if (user?.role !== "admin") return; + setError(""); + Promise.all([ + fetchAuthenticated("/api/v1/orders/admin/summary/"), + fetchAuthenticated("/api/v1/chat/conversations/summary/"), + ]) + .then(async ([ordersResponse, conversationsResponse]) => { + if (!ordersResponse.ok) throw new Error(await getError(ordersResponse)); + if (!conversationsResponse.ok) + throw new Error(await getError(conversationsResponse)); + const [orderData, conversationData] = await Promise.all([ + ordersResponse.json() as Promise, + conversationsResponse.json() as Promise, + ]); + setOrders(orderData); + setConversations(conversationData); + }) + .catch((reason) => + setError( + reason instanceof Error + ? reason.message + : "دریافت نمای کلی مدیریت ناموفق بود.", + ), + ); + }, [user?.id, user?.role]); + + if (user?.role !== "admin") + return ( + + ); + + if (error) return ; + + return ( +
+
+

مرکز عملیات

+

نمای کلی مدیریت

+

وضعیت سفارش‌ها و صف پشتیبانی را در یک نگاه پیگیری کن.

+
+ {!orders || !conversations ? ( +

در حال دریافت نمای کلی…

+ ) : ( +
+
+
+
+

فروش

+

سفارش‌ها

+
+ {orders.total} +
+
+
+
در انتظار پرداخت
+
{orders.by_status.pending ?? 0}
+
+
+
آمادهٔ رسیدگی
+
{orders.by_status.paid ?? 0}
+
+
+
در حال ارسال
+
{orders.by_status.processing ?? 0}
+
+
+
ارسال‌شده
+
{orders.by_status.shipped ?? 0}
+
+
+ + مدیریت سفارش‌ها + +
+
+
+
+

پشتیبانی

+

گفت‌وگوها

+
+ {conversations.total} +
+
+
+
گفت‌وگوی باز
+
{conversations.by_status.open ?? 0}
+
+
+
بدون مسئول
+
{conversations.unassigned_open}
+
+
+
پیام خوانده‌نشده
+
{conversations.unread_customer_messages}
+
+
+
حل‌شده
+
{conversations.by_status.resolved ?? 0}
+
+
+ + گفت‌وگوهای پشتیبانی + +
+
+ )} +
+ ); +} + function AdminOrdersPage({ user }: { user: AuthUser | null }) { const [orders, setOrders] = useState([]); const [ordersResponse, setOrdersResponse] = @@ -2463,6 +2599,8 @@ function App() { navigate("/"); }} /> + ) : route.name === "admin-dashboard" ? ( + ) : route.name === "admin-orders" ? ( ) : route.name === "chat" ? ( diff --git a/frontend/src/styles.css b/frontend/src/styles.css index df3b644..c4a0c1f 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -1166,6 +1166,62 @@ footer small { display: grid; gap: 8px; } +.admin-overview-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px; +} +.admin-overview-card { + padding: 24px; + border: 1px solid #dfe6dc; + border-radius: 17px; + background: #fff; + box-shadow: 0 12px 28px #2744310a; +} +.admin-overview-heading { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 14px; + padding-bottom: 17px; + border-bottom: 1px solid #edf0ea; +} +.admin-overview-heading h2 { + margin: 3px 0 0; + color: #1b2a20; + font-size: 1.2rem; +} +.admin-overview-heading strong { + min-width: 46px; + min-height: 46px; + display: grid; + place-items: center; + border-radius: 13px; + color: #315f47; + background: #edf5eb; + font-size: 1.1rem; +} +.admin-overview-metrics { + margin: 18px 0; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} +.admin-overview-metrics div { + padding: 11px; + border-radius: 10px; + background: #f8faf7; +} +.admin-overview-metrics dt { + color: #78857a; + font-size: 0.66rem; +} +.admin-overview-metrics dd { + margin: 5px 0 0; + color: #2b523c; + font-size: 0.95rem; + font-weight: 800; +} @media (max-width: 860px) { .account-button { order: -1; @@ -2045,6 +2101,9 @@ footer small { .admin-orders-filters { grid-template-columns: 1fr; } + .admin-overview-grid { + grid-template-columns: 1fr; + } .admin-chat-layout { grid-template-columns: 1fr; }