phungtuan commited on
Commit
2e20b15
·
1 Parent(s): cfe1653

fixed new chat msg not auto poll on dashboard, signing out should also sign user out of everything

Browse files
app/(main)/auth/account-disabled/page.tsx CHANGED
@@ -2,11 +2,12 @@
2
 
3
  import { Card, CardBody, CardHeader, Button } from "@heroui/react";
4
  import { Ban } from "lucide-react";
5
- import { signOut } from "next-auth/react";
 
6
 
7
  export default function AccountDisabledPage() {
8
  const handleSignOut = async () => {
9
- await signOut({ callbackUrl: "/" });
10
  };
11
 
12
  return (
@@ -18,8 +19,8 @@ export default function AccountDisabledPage() {
18
  </CardHeader>
19
  <CardBody className="text-center space-y-4">
20
  <p className="text-default-500">
21
- Tài khoản của bạn đã bị vô hiệu hóa. Nếu bạn tin rằng đây là một sai sót,
22
- vui lòng liên hệ với bộ phận hỗ trợ của chúng tôi để được giúp đỡ.
23
  </p>
24
  <div className="flex gap-2 justify-center">
25
  <Button color="primary" onPress={handleSignOut}>
 
2
 
3
  import { Card, CardBody, CardHeader, Button } from "@heroui/react";
4
  import { Ban } from "lucide-react";
5
+
6
+ import { signOutWithBroadcast } from "@/hooks/useLogoutSync";
7
 
8
  export default function AccountDisabledPage() {
9
  const handleSignOut = async () => {
10
+ await signOutWithBroadcast("/");
11
  };
12
 
13
  return (
 
19
  </CardHeader>
20
  <CardBody className="text-center space-y-4">
21
  <p className="text-default-500">
22
+ Tài khoản của bạn đã bị vô hiệu hóa. Nếu bạn tin rằng đây là một sai sót,
23
+ vui lòng liên hệ với bộ phận hỗ trợ của chúng tôi để được giúp đỡ.
24
  </p>
25
  <div className="flex gap-2 justify-center">
26
  <Button color="primary" onPress={handleSignOut}>
app/(main)/auth/error/page.tsx CHANGED
@@ -14,10 +14,10 @@ export default function AuthErrorPage() {
14
  </CardHeader>
15
  <CardBody className="text-center space-y-4">
16
  <p className="text-default-500">
17
- Có lỗi xảy ra trong quá trình đăng nhập.
18
  </p>
19
  <div className="flex gap-2 justify-center">
20
- <Link href="/auth/login">
21
  <Button color="primary">Thử lại</Button>
22
  </Link>
23
  <Link href="/">
 
14
  </CardHeader>
15
  <CardBody className="text-center space-y-4">
16
  <p className="text-default-500">
17
+ Có lỗi xảy ra trong quá trình đăng nhập.
18
  </p>
19
  <div className="flex gap-2 justify-center">
20
+ <Link href="/?modal=login">
21
  <Button color="primary">Thử lại</Button>
22
  </Link>
23
  <Link href="/">
app/api/chat/unread/route.ts ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { auth } from "@/lib/auth";
2
+ import { prisma } from "@/lib/prisma";
3
+ import { errorResponse, successResponse } from "@/lib/api/responses";
4
+
5
+ /**
6
+ * GET /api/chat/unread
7
+ * Get total unread message count for the current user
8
+ * Query params:
9
+ * - role: "user" | "vendor" (which role to check unread for)
10
+ */
11
+ export async function GET(request: Request) {
12
+ try {
13
+ const session = await auth();
14
+
15
+ if (!session?.user?.email) {
16
+ return errorResponse("Unauthorized", 401);
17
+ }
18
+
19
+ const user = await prisma.user.findUnique({
20
+ where: { email: session.user.email },
21
+ include: { vendorProfile: true },
22
+ });
23
+
24
+ if (!user) {
25
+ return errorResponse("User not found", 404);
26
+ }
27
+
28
+ const { searchParams } = new URL(request.url);
29
+ const role = searchParams.get("role");
30
+
31
+ let unreadCount = 0;
32
+
33
+ if (role === "vendor" && user.vendorProfile) {
34
+ // Count unread messages for vendor (from users)
35
+ unreadCount = await prisma.chatMessage.count({
36
+ where: {
37
+ conversation: {
38
+ vendorId: user.vendorProfile.id,
39
+ },
40
+ senderType: "USER",
41
+ isRead: false,
42
+ },
43
+ });
44
+ } else {
45
+ // Count unread messages for user (from vendors)
46
+ unreadCount = await prisma.chatMessage.count({
47
+ where: {
48
+ conversation: {
49
+ userId: user.id,
50
+ },
51
+ senderType: "VENDOR",
52
+ isRead: false,
53
+ },
54
+ });
55
+ }
56
+
57
+ return successResponse({ unreadCount });
58
+ } catch (error) {
59
+ return errorResponse("Failed to get unread count", 500, error);
60
+ }
61
+ }
app/orders/page.tsx CHANGED
@@ -8,7 +8,7 @@ export default async function OrdersPage() {
8
  const session = await auth();
9
 
10
  if (!session) {
11
- redirect("/auth/login");
12
  }
13
 
14
  return (
 
8
  const session = await auth();
9
 
10
  if (!session) {
11
+ redirect("/?modal=login");
12
  }
13
 
14
  return (
app/providers.tsx CHANGED
@@ -9,6 +9,8 @@ import { useRouter } from "next/navigation";
9
  import { ThemeProvider as NextThemesProvider } from "next-themes";
10
  import { SessionProvider } from "next-auth/react";
11
 
 
 
12
  export interface ProvidersProps {
13
  children: React.ReactNode;
14
  themeProps?: ThemeProviderProps;
@@ -25,6 +27,9 @@ declare module "@react-types/shared" {
25
  export function Providers({ children, themeProps }: ProvidersProps) {
26
  const router = useRouter();
27
 
 
 
 
28
  return (
29
  <HeroUIProvider navigate={router.push}>
30
  <NextThemesProvider {...themeProps}>
 
9
  import { ThemeProvider as NextThemesProvider } from "next-themes";
10
  import { SessionProvider } from "next-auth/react";
11
 
12
+ import { useLogoutListener } from "@/hooks/useLogoutSync";
13
+
14
  export interface ProvidersProps {
15
  children: React.ReactNode;
16
  themeProps?: ThemeProviderProps;
 
27
  export function Providers({ children, themeProps }: ProvidersProps) {
28
  const router = useRouter();
29
 
30
+ // Listen for logout events from other tabs
31
+ useLogoutListener();
32
+
33
  return (
34
  <HeroUIProvider navigate={router.push}>
35
  <NextThemesProvider {...themeProps}>
app/vendor/analytics/page.tsx CHANGED
@@ -10,7 +10,7 @@ export default async function VendorAnalyticsPage() {
10
  !session?.user ||
11
  (session.user.role !== "VENDOR" && session.user.role !== "ADMIN")
12
  ) {
13
- redirect("/auth/login");
14
  }
15
 
16
  return <AnalyticsDashboard />;
 
10
  !session?.user ||
11
  (session.user.role !== "VENDOR" && session.user.role !== "ADMIN")
12
  ) {
13
+ redirect("/?modal=login");
14
  }
15
 
16
  return <AnalyticsDashboard />;
app/vendor/page.tsx CHANGED
@@ -9,7 +9,7 @@ export default async function VendorPage() {
9
  const auth = await getAuthenticatedVendor();
10
 
11
  if ("error" in auth) {
12
- redirect("/auth/login");
13
  }
14
 
15
  // 1. Get vendor products
 
9
  const auth = await getAuthenticatedVendor();
10
 
11
  if ("error" in auth) {
12
+ redirect("/?modal=login");
13
  }
14
 
15
  // 1. Get vendor products
components/common/DashboardSidebar.tsx CHANGED
@@ -9,6 +9,7 @@ export interface SidebarMenuItem {
9
  label: string;
10
  icon: LucideIcon;
11
  path: string;
 
12
  }
13
 
14
  interface DashboardSidebarProps {
@@ -48,6 +49,13 @@ export default function DashboardSidebar({
48
  className={`w-full justify-start ${isActive ? "font-semibold" : "text-default-500"}`}
49
  color={isActive ? "primary" : "default"}
50
  startContent={<Icon size={20} />}
 
 
 
 
 
 
 
51
  variant={isActive ? "flat" : "light"}
52
  onPress={() => router.push(item.path)}
53
  >
 
9
  label: string;
10
  icon: LucideIcon;
11
  path: string;
12
+ badge?: number; // Optional badge for notifications (e.g., unread messages)
13
  }
14
 
15
  interface DashboardSidebarProps {
 
49
  className={`w-full justify-start ${isActive ? "font-semibold" : "text-default-500"}`}
50
  color={isActive ? "primary" : "default"}
51
  startContent={<Icon size={20} />}
52
+ endContent={
53
+ item.badge && item.badge > 0 ? (
54
+ <span className="ml-auto bg-danger text-white text-xs font-bold rounded-full min-w-[20px] h-5 flex items-center justify-center px-1.5">
55
+ {item.badge > 99 ? "99+" : item.badge}
56
+ </span>
57
+ ) : null
58
+ }
59
  variant={isActive ? "flat" : "light"}
60
  onPress={() => router.push(item.path)}
61
  >
components/dashboard/DashboardLayout.tsx CHANGED
@@ -6,7 +6,7 @@ import { useEffect, ReactNode } from "react";
6
  import { Spinner } from "@heroui/spinner";
7
  import { Button } from "@heroui/button";
8
  import { Settings, LogOut } from "lucide-react";
9
- import { signOut } from "next-auth/react";
10
 
11
  import DashboardSidebar, {
12
  SidebarMenuItem,
@@ -69,7 +69,7 @@ export default function DashboardLayout({
69
  showLogout = true,
70
  showSettings = true,
71
  unauthorizedRedirect = "/",
72
- loginRedirect = "/auth/login",
73
  }: DashboardLayoutProps) {
74
  const { data: session, status } = useSession();
75
  const router = useRouter();
@@ -105,7 +105,8 @@ export default function DashboardLayout({
105
  ]);
106
 
107
  const handleLogout = () => {
108
- signOut({ callbackUrl: loginRedirect });
 
109
  };
110
 
111
  // Show loading while checking auth
 
6
  import { Spinner } from "@heroui/spinner";
7
  import { Button } from "@heroui/button";
8
  import { Settings, LogOut } from "lucide-react";
9
+ import { signOutWithBroadcast } from "@/hooks/useLogoutSync";
10
 
11
  import DashboardSidebar, {
12
  SidebarMenuItem,
 
69
  showLogout = true,
70
  showSettings = true,
71
  unauthorizedRedirect = "/",
72
+ loginRedirect = "/?modal=login",
73
  }: DashboardLayoutProps) {
74
  const { data: session, status } = useSession();
75
  const router = useRouter();
 
105
  ]);
106
 
107
  const handleLogout = () => {
108
+ // Always redirect to home with login modal instead of loginRedirect
109
+ signOutWithBroadcast("/?modal=login");
110
  };
111
 
112
  // Show loading while checking auth
components/navbar/sign-out-button.tsx CHANGED
@@ -1,12 +1,12 @@
1
  "use client";
2
 
3
- import { signOut } from "next-auth/react";
4
 
5
  export function SignOutButton() {
6
  return (
7
  <button
8
  className="w-full text-left"
9
- onClick={() => signOut({ callbackUrl: "/" })}
10
  >
11
  sign out
12
  </button>
 
1
  "use client";
2
 
3
+ import { signOutWithBroadcast } from "@/hooks/useLogoutSync";
4
 
5
  export function SignOutButton() {
6
  return (
7
  <button
8
  className="w-full text-left"
9
+ onClick={() => signOutWithBroadcast("/?modal=login")}
10
  >
11
  sign out
12
  </button>
components/vendor/VendorChatPage.tsx CHANGED
@@ -15,6 +15,7 @@ import { useRouter } from "next/navigation";
15
 
16
  import { api } from "@/lib/api/api";
17
  import { toast } from "@/lib/toast";
 
18
 
19
  interface Message {
20
  id: string;
@@ -97,6 +98,8 @@ export default function VendorChatPage() {
97
  setIsLoadingMessages(true);
98
  fetchMessages().finally(() => {
99
  setIsLoadingMessages(false);
 
 
100
  });
101
  }
102
  }, [selectedConversation, fetchMessages]);
@@ -153,13 +156,15 @@ export default function VendorChatPage() {
153
  prev.map((conv) =>
154
  conv.id === selectedConversation
155
  ? {
156
- ...conv,
157
- lastMessage: data.message,
158
- updatedAt: data.message.createdAt,
159
- }
160
  : conv,
161
  ),
162
  );
 
 
163
  } catch (error) {
164
  console.error("Failed to send message:", error);
165
  toast.error("Không thể gửi tin nhắn");
@@ -279,11 +284,10 @@ export default function VendorChatPage() {
279
  {conversations.map((conv) => (
280
  <button
281
  key={conv.id}
282
- className={`w-full p-4 text-left hover:bg-default-100 transition-colors ${
283
- selectedConversation === conv.id
284
- ? "bg-primary-50 border-l-4 border-primary"
285
- : ""
286
- }`}
287
  onClick={() => handleSelectConversation(conv.id)}
288
  >
289
  <div className="flex items-start gap-3">
@@ -395,28 +399,25 @@ export default function VendorChatPage() {
395
  {msgs.map((message) => (
396
  <div
397
  key={message.id}
398
- className={`flex ${
399
- message.senderType === "VENDOR"
400
- ? "justify-end"
401
- : "justify-start"
402
- }`}
403
  >
404
  <div
405
- className={`max-w-[75%] rounded-2xl px-4 py-2 ${
406
- message.senderType === "VENDOR"
407
- ? "bg-primary text-primary-foreground"
408
- : "bg-default-100"
409
- }`}
410
  >
411
  <p className="text-sm whitespace-pre-wrap break-words">
412
  {message.content}
413
  </p>
414
  <p
415
- className={`text-xs mt-1 ${
416
- message.senderType === "VENDOR"
417
- ? "text-primary-foreground/70"
418
- : "text-default-400"
419
- }`}
420
  >
421
  {formatTime(message.createdAt)}
422
  </p>
 
15
 
16
  import { api } from "@/lib/api/api";
17
  import { toast } from "@/lib/toast";
18
+ import { broadcastChatUpdate } from "@/hooks/useUnreadMessages";
19
 
20
  interface Message {
21
  id: string;
 
98
  setIsLoadingMessages(true);
99
  fetchMessages().finally(() => {
100
  setIsLoadingMessages(false);
101
+ // Messages fetched -> marked as read on server -> broadcast update
102
+ broadcastChatUpdate();
103
  });
104
  }
105
  }, [selectedConversation, fetchMessages]);
 
156
  prev.map((conv) =>
157
  conv.id === selectedConversation
158
  ? {
159
+ ...conv,
160
+ lastMessage: data.message,
161
+ updatedAt: data.message.createdAt,
162
+ }
163
  : conv,
164
  ),
165
  );
166
+
167
+ broadcastChatUpdate();
168
  } catch (error) {
169
  console.error("Failed to send message:", error);
170
  toast.error("Không thể gửi tin nhắn");
 
284
  {conversations.map((conv) => (
285
  <button
286
  key={conv.id}
287
+ className={`w-full p-4 text-left hover:bg-default-100 transition-colors ${selectedConversation === conv.id
288
+ ? "bg-primary-50 border-l-4 border-primary"
289
+ : ""
290
+ }`}
 
291
  onClick={() => handleSelectConversation(conv.id)}
292
  >
293
  <div className="flex items-start gap-3">
 
399
  {msgs.map((message) => (
400
  <div
401
  key={message.id}
402
+ className={`flex ${message.senderType === "VENDOR"
403
+ ? "justify-end"
404
+ : "justify-start"
405
+ }`}
 
406
  >
407
  <div
408
+ className={`max-w-[75%] rounded-2xl px-4 py-2 ${message.senderType === "VENDOR"
409
+ ? "bg-primary text-primary-foreground"
410
+ : "bg-default-100"
411
+ }`}
 
412
  >
413
  <p className="text-sm whitespace-pre-wrap break-words">
414
  {message.content}
415
  </p>
416
  <p
417
+ className={`text-xs mt-1 ${message.senderType === "VENDOR"
418
+ ? "text-primary-foreground/70"
419
+ : "text-default-400"
420
+ }`}
 
421
  >
422
  {formatTime(message.createdAt)}
423
  </p>
components/vendor/VendorLayout.tsx CHANGED
@@ -12,8 +12,9 @@ import {
12
  } from "lucide-react";
13
 
14
  import { DashboardLayout } from "@/components/dashboard";
 
15
 
16
- const VENDOR_MENU_ITEMS: SidebarMenuItem[] = [
17
  {
18
  key: "dashboard",
19
  label: "Tổng quan",
@@ -52,9 +53,17 @@ export default function VendorLayout({
52
  }: {
53
  children: React.ReactNode;
54
  }) {
 
 
 
 
 
 
 
 
55
  return (
56
  <DashboardLayout
57
- menuItems={VENDOR_MENU_ITEMS}
58
  requiredRole="VENDOR"
59
  showLogout={false}
60
  >
 
12
  } from "lucide-react";
13
 
14
  import { DashboardLayout } from "@/components/dashboard";
15
+ import { useUnreadMessages } from "@/hooks/useUnreadMessages";
16
 
17
+ const BASE_MENU_ITEMS: Omit<SidebarMenuItem, "badge">[] = [
18
  {
19
  key: "dashboard",
20
  label: "Tổng quan",
 
53
  }: {
54
  children: React.ReactNode;
55
  }) {
56
+ const { unreadCount } = useUnreadMessages({ role: "vendor" });
57
+
58
+ // Add badge to chat menu item
59
+ const menuItems: SidebarMenuItem[] = BASE_MENU_ITEMS.map((item) => ({
60
+ ...item,
61
+ badge: item.key === "chat" ? unreadCount : undefined,
62
+ }));
63
+
64
  return (
65
  <DashboardLayout
66
+ menuItems={menuItems}
67
  requiredRole="VENDOR"
68
  showLogout={false}
69
  >
hooks/useLogoutSync.ts ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useEffect } from "react";
4
+ import { signOut } from "next-auth/react";
5
+
6
+ const LOGOUT_CHANNEL_NAME = "fluxify_logout_channel";
7
+
8
+ /**
9
+ * Broadcasts a logout event to all other tabs
10
+ * Call this before or after signOut to notify other tabs
11
+ */
12
+ export function broadcastLogout() {
13
+ try {
14
+ const channel = new BroadcastChannel(LOGOUT_CHANNEL_NAME);
15
+ channel.postMessage({ type: "logout", timestamp: Date.now() });
16
+ channel.close();
17
+ } catch {
18
+ // BroadcastChannel not supported, try localStorage fallback
19
+ try {
20
+ localStorage.setItem("logout_event", Date.now().toString());
21
+ localStorage.removeItem("logout_event");
22
+ } catch {
23
+ // localStorage also not available, ignore
24
+ }
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Signs out and broadcasts logout to other tabs
30
+ * Use this instead of signOut directly to ensure cross-tab logout
31
+ */
32
+ export async function signOutWithBroadcast(callbackUrl = "/") {
33
+ // Set flag to prevent this tab from reloading when it receives its own broadcast
34
+ if (typeof window !== "undefined") {
35
+ sessionStorage.setItem("is_logging_out", "true");
36
+ }
37
+
38
+ broadcastLogout();
39
+ await signOut({ callbackUrl });
40
+ }
41
+
42
+ /**
43
+ * Hook that listens for logout events from other tabs
44
+ * When a logout is detected, it refreshes the current page
45
+ */
46
+ export function useLogoutListener() {
47
+ useEffect(() => {
48
+ let channel: BroadcastChannel | null = null;
49
+
50
+ const handleLogout = () => {
51
+ // Check if this tab is the one performing logout
52
+ if (sessionStorage.getItem("is_logging_out") === "true") {
53
+ // Clear the flag and ignore (signOut will handle redirect)
54
+ sessionStorage.removeItem("is_logging_out");
55
+ return;
56
+ }
57
+
58
+ // Refresh the page to update auth state
59
+ window.location.reload();
60
+ };
61
+
62
+ try {
63
+ // Primary method: BroadcastChannel
64
+ channel = new BroadcastChannel(LOGOUT_CHANNEL_NAME);
65
+ channel.onmessage = (event) => {
66
+ if (event.data?.type === "logout") {
67
+ handleLogout();
68
+ }
69
+ };
70
+ } catch {
71
+ // Fallback: localStorage event (for older browsers)
72
+ const handleStorageChange = (event: StorageEvent) => {
73
+ if (event.key === "logout_event" && event.newValue) {
74
+ handleLogout();
75
+ }
76
+ };
77
+ window.addEventListener("storage", handleStorageChange);
78
+
79
+ return () => {
80
+ window.removeEventListener("storage", handleStorageChange);
81
+ };
82
+ }
83
+
84
+ return () => {
85
+ channel?.close();
86
+ };
87
+ }, []);
88
+ }
hooks/useUnreadMessages.ts ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useEffect, useCallback } from "react";
4
+
5
+ import { api } from "@/lib/api/api";
6
+
7
+ const POLL_INTERVAL = 30000; // 30 seconds
8
+
9
+ interface UseUnreadMessagesOptions {
10
+ role: "user" | "vendor";
11
+ enabled?: boolean;
12
+ }
13
+
14
+ /**
15
+ * Broadcasts a chat update event to all tabs
16
+ */
17
+ export function broadcastChatUpdate() {
18
+ try {
19
+ const channel = new BroadcastChannel("fluxify_chat_channel");
20
+ channel.postMessage({ type: "chat_update", timestamp: Date.now() });
21
+ channel.close();
22
+ } catch {
23
+ // ignore
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Hook to fetch and poll unread message count
29
+ * @param options.role - "user" or "vendor" to check unread for
30
+ * @param options.enabled - Whether to enable polling (default: true)
31
+ * @returns Object with unreadCount and refetch function
32
+ */
33
+ export function useUnreadMessages({ role, enabled = true }: UseUnreadMessagesOptions) {
34
+ const [unreadCount, setUnreadCount] = useState(0);
35
+ const [isLoading, setIsLoading] = useState(true);
36
+
37
+ const fetchUnreadCount = useCallback(async () => {
38
+ if (!enabled) return;
39
+
40
+ try {
41
+ const data = await api.get<{ unreadCount: number }>(
42
+ `/api/chat/unread?role=${role}`
43
+ );
44
+ setUnreadCount(data.unreadCount);
45
+ } catch (error) {
46
+ console.error("Failed to fetch unread count:", error);
47
+ } finally {
48
+ setIsLoading(false);
49
+ }
50
+ }, [role, enabled]);
51
+
52
+ useEffect(() => {
53
+ fetchUnreadCount();
54
+
55
+ // Poll for updates
56
+ let interval: NodeJS.Timeout;
57
+ if (enabled) {
58
+ interval = setInterval(fetchUnreadCount, POLL_INTERVAL);
59
+ }
60
+
61
+ // Listen for updates from other tabs
62
+ const channel = new BroadcastChannel("fluxify_chat_channel");
63
+ channel.onmessage = (event) => {
64
+ if (event.data?.type === "chat_update") {
65
+ fetchUnreadCount();
66
+ }
67
+ };
68
+
69
+ return () => {
70
+ if (interval) clearInterval(interval);
71
+ channel.close();
72
+ };
73
+ }, [fetchUnreadCount, enabled]);
74
+
75
+ return {
76
+ unreadCount,
77
+ isLoading,
78
+ refetch: fetchUnreadCount,
79
+ };
80
+ }
lib/auth.ts CHANGED
@@ -33,7 +33,7 @@ declare module "next-auth" {
33
  export const { handlers, signIn, signOut, auth } = NextAuth({
34
  session: { strategy: "jwt" },
35
  pages: {
36
- signIn: "/auth/login",
37
  error: "/auth/error",
38
  },
39
  providers: [
@@ -100,6 +100,11 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
100
  const shouldCheckStatus = now - lastCheck > STATUS_CHECK_INTERVAL;
101
 
102
  if (shouldCheckStatus && token.id) {
 
 
 
 
 
103
  try {
104
  const { prisma } = await import("@/lib/prisma");
105
  const dbUser = await prisma.user.findUnique({
@@ -111,8 +116,12 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
111
  token.isActive = dbUser.isActive;
112
  token.lastActiveCheck = now;
113
  }
114
- } catch (error) {
115
  // If check fails, keep the previous status
 
 
 
 
116
  console.error("Error checking user active status:", error);
117
  }
118
  }
 
33
  export const { handlers, signIn, signOut, auth } = NextAuth({
34
  session: { strategy: "jwt" },
35
  pages: {
36
+ signIn: "/?modal=login", // Use modal at home page instead of separate page
37
  error: "/auth/error",
38
  },
39
  providers: [
 
100
  const shouldCheckStatus = now - lastCheck > STATUS_CHECK_INTERVAL;
101
 
102
  if (shouldCheckStatus && token.id) {
103
+ // Skip DB check in Edge runtime (middleware)
104
+ if (process.env.NEXT_RUNTIME === "edge") {
105
+ return token;
106
+ }
107
+
108
  try {
109
  const { prisma } = await import("@/lib/prisma");
110
  const dbUser = await prisma.user.findUnique({
 
116
  token.isActive = dbUser.isActive;
117
  token.lastActiveCheck = now;
118
  }
119
+ } catch (error: any) {
120
  // If check fails, keep the previous status
121
+ // Suppress specific edge runtime error that happens in middleware
122
+ if (error?.message?.includes("The edge runtime does not support Node.js")) {
123
+ return token;
124
+ }
125
  console.error("Error checking user active status:", error);
126
  }
127
  }