Explorar o código

fix: ensure unread messages count resets when entering chat

unknown hai 2 meses
pai
achega
25fd1ca617
Modificáronse 3 ficheiros con 34 adicións e 4 borrados
  1. 13 0
      backend/routers/auth.py
  2. 14 0
      src/lib/api.ts
  3. 7 4
      src/stores/auth.ts

+ 13 - 0
backend/routers/auth.py

@@ -254,6 +254,19 @@ async def get_me(user: dict = Depends(get_current_user)):
     if not user_data: raise HTTPException(status_code=404, detail="User not found")
     return user_data[0]
 
+@router.get("/unread-count")
+async def get_unread_count(user: dict = Depends(get_current_user)):
+    user_id = user.get("id")
+    role = user.get("role")
+    if role == 'admin':
+        row = db.execute_query("SELECT count(*) as cnt FROM order_messages WHERE is_from_admin = FALSE AND is_read = FALSE")
+    else:
+        row = db.execute_query(
+            "SELECT count(*) as cnt FROM order_messages om JOIN orders o ON om.order_id = o.id WHERE o.user_id = %s AND om.is_from_admin = TRUE AND om.is_read = FALSE",
+            (user_id,)
+        )
+    return {"count": row[0]['cnt'] if row else 0}
+
 @router.put("/me", response_model=schemas.UserResponse)
 async def update_me(data: schemas.UserUpdate, user: dict = Depends(get_current_user)):
     user_id = user.get("id")

+ 14 - 0
src/lib/api.ts

@@ -227,6 +227,20 @@ export const getCurrentUser = async () => {
   return response.json();
 };
 
+export const getUnreadCount = async () => {
+  const token = localStorage.getItem("token");
+  if (!token) return { count: 0 };
+
+  const response = await fetch(`${API_BASE_URL}/auth/unread-count?lang=${i18n.global.locale.value}`, {
+    headers: {
+      'Authorization': `Bearer ${token}`
+    }
+  });
+  
+  if (!response.ok) return { count: 0 };
+  return response.json();
+};
+
 export const updateProfile = async (userData: any) => {
   const token = localStorage.getItem("token");
   if (!token) throw new Error("No token found");

+ 7 - 4
src/stores/auth.ts

@@ -1,6 +1,6 @@
 import { defineStore } from "pinia";
 import { ref } from "vue";
-import { getCurrentUser } from "@/lib/api";
+import { getCurrentUser, getUnreadCount } from "@/lib/api";
 import { getWsUrl } from "@/lib/utils";
 import { toast } from "vue-sonner";
 
@@ -265,9 +265,12 @@ export const useAuthStore = defineStore("auth", () => {
   }
 
   async function refreshUnreadCount() {
-    // Left empty or removed, as WS handles updates now.
-    // If you need manual force, you could re-trigger connect or add an endpoint, 
-    // but the WS pushes update automatically.
+    try {
+      const { count } = await getUnreadCount();
+      unreadMessagesCount.value = count;
+    } catch (e) {
+      console.error("Failed to refresh unread count", e);
+    }
   }
 
   return {