Add notification context and privacy toggle for analytics

Introduces a NotificationProvider context to centralize notification logic and state, refactoring UnifiedNotifications to use this context. Adds a privacy toggle to AnalyticsDashboard and RevenueChart to allow hiding sensitive numbers. Updates layout to wrap the app with NotificationProvider.
This commit is contained in:
NotII
2025-07-28 22:50:55 +02:00
parent 2452a3c5f6
commit 48cfd45fb1
6 changed files with 460 additions and 287 deletions

View File

@@ -4,6 +4,7 @@ import { ThemeProvider } from "@/components/layout/theme-provider"
import { Toaster } from "sonner" import { Toaster } from "sonner"
import type React from "react" import type React from "react"
import KeepOnline from "@/components/KeepOnline" import KeepOnline from "@/components/KeepOnline"
import { NotificationProvider } from "@/lib/notification-context"
import { Metadata, Viewport } from "next" import { Metadata, Viewport } from "next"
const inter = Inter({ subsets: ["latin"] }) const inter = Inter({ subsets: ["latin"] })
@@ -70,6 +71,7 @@ export default function RootLayout({
<html lang="en" suppressHydrationWarning> <html lang="en" suppressHydrationWarning>
<body className={inter.className}> <body className={inter.className}>
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem disableTransitionOnChange> <ThemeProvider attribute="class" defaultTheme="dark" enableSystem disableTransitionOnChange>
<NotificationProvider>
<Toaster <Toaster
theme="dark" theme="dark"
richColors richColors
@@ -77,6 +79,7 @@ export default function RootLayout({
/> />
<KeepOnline /> <KeepOnline />
{children} {children}
</NotificationProvider>
</ThemeProvider> </ThemeProvider>
</body> </body>
</html> </html>

View File

@@ -15,7 +15,9 @@ import {
BarChart3, BarChart3,
PieChart, PieChart,
Activity, Activity,
RefreshCw RefreshCw,
Eye,
EyeOff
} from "lucide-react"; } from "lucide-react";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import MetricsCard from "./MetricsCard"; import MetricsCard from "./MetricsCard";
@@ -70,8 +72,27 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
const [data, setData] = useState<AnalyticsOverview>(initialData); const [data, setData] = useState<AnalyticsOverview>(initialData);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [timeRange, setTimeRange] = useState('30'); const [timeRange, setTimeRange] = useState('30');
const [hideNumbers, setHideNumbers] = useState(false);
const { toast } = useToast(); const { toast } = useToast();
// Function to mask sensitive numbers
const maskValue = (value: string): string => {
if (!hideNumbers) return value;
// For currency values (£X.XX), show £***
if (value.includes('£')) {
return '£***';
}
// For regular numbers, replace with asterisks maintaining similar length
if (value.match(/^\d/)) {
const numLength = value.replace(/[,\.]/g, '').length;
return '*'.repeat(Math.min(numLength, 4));
}
return value;
};
const refreshData = async () => { const refreshData = async () => {
try { try {
setIsLoading(true); setIsLoading(true);
@@ -95,23 +116,23 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
const metrics = [ const metrics = [
{ {
title: "Total Revenue", title: "Total Revenue",
value: formatGBP(data.revenue.total), value: maskValue(formatGBP(data.revenue.total)),
description: "All-time revenue", description: "All-time revenue",
icon: DollarSign, icon: DollarSign,
trend: data.revenue.monthly > 0 ? "up" as const : "neutral" as const, trend: data.revenue.monthly > 0 ? "up" as const : "neutral" as const,
trendValue: `${formatGBP(data.revenue.monthly)} this month` trendValue: hideNumbers ? "Hidden" : `${formatGBP(data.revenue.monthly)} this month`
}, },
{ {
title: "Total Orders", title: "Total Orders",
value: data.orders.total.toLocaleString(), value: maskValue(data.orders.total.toLocaleString()),
description: "All-time orders", description: "All-time orders",
icon: ShoppingCart, icon: ShoppingCart,
trend: data.orders.completed > 0 ? "up" as const : "neutral" as const, trend: data.orders.completed > 0 ? "up" as const : "neutral" as const,
trendValue: `${data.orders.completed} completed` trendValue: hideNumbers ? "Hidden" : `${data.orders.completed} completed`
}, },
{ {
title: "Unique Customers", title: "Unique Customers",
value: data.customers.unique.toLocaleString(), value: maskValue(data.customers.unique.toLocaleString()),
description: "Total customers", description: "Total customers",
icon: Users, icon: Users,
trend: "neutral" as const, trend: "neutral" as const,
@@ -119,7 +140,7 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
}, },
{ {
title: "Products", title: "Products",
value: data.products.total.toLocaleString(), value: maskValue(data.products.total.toLocaleString()),
description: "Active products", description: "Active products",
icon: Package, icon: Package,
trend: "neutral" as const, trend: "neutral" as const,
@@ -129,6 +150,46 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Header with Privacy Toggle */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-3xl font-bold tracking-tight">Analytics Dashboard</h2>
<p className="text-muted-foreground">
Overview of your store's performance and metrics.
</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setHideNumbers(!hideNumbers)}
className="flex items-center gap-2"
>
{hideNumbers ? (
<>
<EyeOff className="h-4 w-4" />
Show Numbers
</>
) : (
<>
<Eye className="h-4 w-4" />
Hide Numbers
</>
)}
</Button>
<Button
variant="outline"
size="sm"
onClick={refreshData}
disabled={isLoading}
className="flex items-center gap-2"
>
<RefreshCw className={`h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
Refresh
</Button>
</div>
</div>
{/* Key Metrics Cards */} {/* Key Metrics Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{isLoading ? ( {isLoading ? (
@@ -165,18 +226,18 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
) : ( ) : (
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<div className="text-3xl font-bold"> <div className="text-3xl font-bold">
{data.orders.completionRate}% {hideNumbers ? "**%" : `${data.orders.completionRate}%`}
</div> </div>
<div className="flex-1"> <div className="flex-1">
<div className="w-full bg-secondary rounded-full h-2"> <div className="w-full bg-secondary rounded-full h-2">
<div <div
className="bg-primary h-2 rounded-full transition-all duration-300" className="bg-primary h-2 rounded-full transition-all duration-300"
style={{ width: `${data.orders.completionRate}%` }} style={{ width: hideNumbers ? "0%" : `${data.orders.completionRate}%` }}
/> />
</div> </div>
</div> </div>
<Badge variant="secondary"> <Badge variant="secondary">
{data.orders.completed} / {data.orders.total} {hideNumbers ? "** / **" : `${data.orders.completed} / ${data.orders.total}`}
</Badge> </Badge>
</div> </div>
)} )}
@@ -186,7 +247,7 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
{/* Time Period Selector */} {/* Time Period Selector */}
<div className="flex flex-col sm:flex-row gap-4 sm:items-center sm:justify-between"> <div className="flex flex-col sm:flex-row gap-4 sm:items-center sm:justify-between">
<div> <div>
<h3 className="text-lg font-semibold">Time period:</h3> <h3 className="text-lg font-semibold">Time Period</h3>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
Revenue and Orders tabs use time filtering. Products and Customers show all-time data. Revenue and Orders tabs use time filtering. Products and Customers show all-time data.
</p> </p>
@@ -227,7 +288,7 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
<TabsContent value="revenue" className="space-y-6"> <TabsContent value="revenue" className="space-y-6">
<Suspense fallback={<ChartSkeleton />}> <Suspense fallback={<ChartSkeleton />}>
<RevenueChart timeRange={timeRange} /> <RevenueChart timeRange={timeRange} hideNumbers={hideNumbers} />
</Suspense> </Suspense>
</TabsContent> </TabsContent>

View File

@@ -12,6 +12,7 @@ import { ChartSkeleton } from './SkeletonLoaders';
interface RevenueChartProps { interface RevenueChartProps {
timeRange: string; timeRange: string;
hideNumbers?: boolean;
} }
interface ChartDataPoint { interface ChartDataPoint {
@@ -21,7 +22,7 @@ interface ChartDataPoint {
formattedDate: string; formattedDate: string;
} }
export default function RevenueChart({ timeRange }: RevenueChartProps) { export default function RevenueChart({ timeRange, hideNumbers = false }: RevenueChartProps) {
const [data, setData] = useState<RevenueData[]>([]); const [data, setData] = useState<RevenueData[]>([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -75,6 +76,19 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
const totalOrders = safeData.reduce((sum, item) => sum + (item.orders || 0), 0); const totalOrders = safeData.reduce((sum, item) => sum + (item.orders || 0), 0);
const averageRevenue = safeData.length > 0 ? totalRevenue / safeData.length : 0; const averageRevenue = safeData.length > 0 ? totalRevenue / safeData.length : 0;
// Function to mask sensitive numbers
const maskValue = (value: string): string => {
if (!hideNumbers) return value;
// For currency values (£X.XX), show £***
if (value.includes('£')) {
return '£***';
}
// For regular numbers, replace with asterisks
return '***';
};
// Custom tooltip for the chart // Custom tooltip for the chart
const CustomTooltip = ({ active, payload, label }: any) => { const CustomTooltip = ({ active, payload, label }: any) => {
if (active && payload && payload.length) { if (active && payload && payload.length) {
@@ -83,10 +97,10 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
<div className="bg-white p-3 border border-gray-200 rounded-lg shadow-lg"> <div className="bg-white p-3 border border-gray-200 rounded-lg shadow-lg">
<p className="text-sm font-medium text-gray-900">{data.formattedDate}</p> <p className="text-sm font-medium text-gray-900">{data.formattedDate}</p>
<p className="text-sm text-blue-600"> <p className="text-sm text-blue-600">
Revenue: <span className="font-semibold">{formatGBP(data.revenue)}</span> Revenue: <span className="font-semibold">{hideNumbers ? '£***' : formatGBP(data.revenue)}</span>
</p> </p>
<p className="text-sm text-green-600"> <p className="text-sm text-green-600">
Orders: <span className="font-semibold">{data.orders}</span> Orders: <span className="font-semibold">{hideNumbers ? '***' : data.orders}</span>
</p> </p>
</div> </div>
); );
@@ -173,7 +187,7 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
/> />
<YAxis <YAxis
tick={{ fontSize: 12 }} tick={{ fontSize: 12 }}
tickFormatter={(value) => `£${(value / 1000).toFixed(0)}k`} tickFormatter={(value) => hideNumbers ? '***' : `£${(value / 1000).toFixed(0)}k`}
/> />
<Tooltip content={<CustomTooltip />} /> <Tooltip content={<CustomTooltip />} />
<Bar <Bar
@@ -191,19 +205,19 @@ export default function RevenueChart({ timeRange }: RevenueChartProps) {
<div className="grid grid-cols-3 gap-4 pt-4 border-t"> <div className="grid grid-cols-3 gap-4 pt-4 border-t">
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-green-600"> <div className="text-2xl font-bold text-green-600">
{formatGBP(totalRevenue)} {maskValue(formatGBP(totalRevenue))}
</div> </div>
<div className="text-sm text-muted-foreground">Total Revenue</div> <div className="text-sm text-muted-foreground">Total Revenue</div>
</div> </div>
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-blue-600"> <div className="text-2xl font-bold text-blue-600">
{totalOrders} {maskValue(totalOrders.toString())}
</div> </div>
<div className="text-sm text-muted-foreground">Total Orders</div> <div className="text-sm text-muted-foreground">Total Orders</div>
</div> </div>
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-purple-600"> <div className="text-2xl font-bold text-purple-600">
{formatGBP(averageRevenue)} {maskValue(formatGBP(averageRevenue))}
</div> </div>
<div className="text-sm text-muted-foreground">Avg Daily Revenue</div> <div className="text-sm text-muted-foreground">Avg Daily Revenue</div>
</div> </div>

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import React, { useState, useEffect, useRef } from "react"; import React, { useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -13,264 +13,21 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { clientFetch } from "@/lib/api"; import { useNotifications } from "@/lib/notification-context";
import { toast } from "sonner";
import { getCookie } from "@/lib/api";
import axios from "axios";
import { cacheUtils } from '@/lib/api-client';
interface Order {
_id: string;
orderId: string;
status: string;
totalPrice: number;
orderDate: string;
underpaid?: boolean;
underpaymentAmount?: number;
}
interface ChatMessage {
chatId: string;
buyerId: string;
messageCount: number;
}
interface UnreadCounts {
totalUnread: number;
chatCounts: Record<string, number>;
}
export default function UnifiedNotifications() { export default function UnifiedNotifications() {
const router = useRouter(); const router = useRouter();
// Chat notification state
const [unreadCounts, setUnreadCounts] = useState<UnreadCounts>({ totalUnread: 0, chatCounts: {} });
const [previousUnreadTotal, setPreviousUnreadTotal] = useState<number>(0);
const [chatMetadata, setChatMetadata] = useState<Record<string, { buyerId: string }>>({});
// Order notification state
const [newOrders, setNewOrders] = useState<Order[]>([]);
const seenOrderIds = useRef<Set<string>>(new Set());
const isInitialOrdersFetch = useRef(true);
// Shared state
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<string>("all"); const [activeTab, setActiveTab] = useState<string>("all");
const audioRef = useRef<HTMLAudioElement | null>(null);
const vendorIdRef = useRef<string | null>(null);
// Total notifications count // Get notification state from context
const totalNotifications = unreadCounts.totalUnread + newOrders.length; const {
unreadCounts,
// Initialize audio chatMetadata,
useEffect(() => { newOrders,
audioRef.current = new Audio('/notification.mp3'); clearOrderNotifications,
totalNotifications,
audioRef.current.addEventListener('error', () => { loading,
audioRef.current = null; } = useNotifications();
});
return () => {
if (audioRef.current) {
audioRef.current = null;
}
};
}, []);
// Get vendor ID from JWT token
const getVendorIdFromToken = () => {
if (vendorIdRef.current) {
return vendorIdRef.current;
}
const authToken = getCookie("Authorization") || "";
if (!authToken) {
throw new Error("No auth token found");
}
const tokenParts = authToken.split(".");
if (tokenParts.length !== 3) {
throw new Error("Invalid token format");
}
const payload = JSON.parse(atob(tokenParts[1]));
const vendorId = payload.id;
if (!vendorId) {
throw new Error("Vendor ID not found in token");
}
vendorIdRef.current = vendorId;
return vendorId;
};
// Function to play notification sound
const playNotificationSound = () => {
if (audioRef.current) {
audioRef.current.currentTime = 0;
audioRef.current.play().catch(err => {
console.log('Error playing sound:', err);
// Fallback beep if audio file fails
try {
const context = new (window.AudioContext || (window as any).webkitAudioContext)();
const oscillator = context.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(800, context.currentTime);
oscillator.connect(context.destination);
oscillator.start();
oscillator.stop(context.currentTime + 0.2);
} catch (e) {
console.error('Could not play fallback audio', e);
}
});
}
};
// Check for new paid orders
useEffect(() => {
// Only run this on dashboard pages
if (typeof window === 'undefined' || !window.location.pathname.includes("/dashboard")) return;
const checkForNewOrders = async () => {
try {
// Get orders from the last 24 hours with a more efficient query
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const timestamp = yesterday.toISOString();
const orderData = await clientFetch(`/orders?status=paid&limit=10&orderDate[gte]=${timestamp}`);
const orders: Order[] = orderData.orders || [];
// Filter out orders that are still showing as underpaid (cache issue)
const validPaidOrders = orders.filter(order => {
// Only include orders that are actually fully paid (not underpaid)
return order.status === 'paid' &&
(!order.underpaid || order.underpaymentAmount === 0);
});
// If this is the first fetch, just store the orders without notifications
if (isInitialOrdersFetch.current) {
validPaidOrders.forEach(order => seenOrderIds.current.add(order._id));
isInitialOrdersFetch.current = false;
return;
}
// Check for new paid orders that haven't been seen before
const latestNewOrders = validPaidOrders.filter(order => !seenOrderIds.current.has(order._id));
// Show notifications for new orders
if (latestNewOrders.length > 0) {
// Update the seen orders set
latestNewOrders.forEach(order => seenOrderIds.current.add(order._id));
// Show a toast notification for each new order
latestNewOrders.forEach(order => {
toast.success(
<div className="flex flex-col">
<p className="font-semibold">New Paid Order!</p>
<p className="text-sm">Order #{order.orderId}</p>
<p className="text-sm font-semibold">£{order.totalPrice.toFixed(2)}</p>
</div>,
{
duration: 8000,
icon: <Package className="h-5 w-5" />,
action: {
label: "View",
onClick: () => window.open(`/dashboard/orders/${order._id}`, "_blank")
}
}
);
});
// Play notification sound
playNotificationSound();
// Update the state with new orders for the dropdown
setNewOrders(prev => [...latestNewOrders, ...prev].slice(0, 10));
// Invalidate order cache to ensure all components refresh
cacheUtils.invalidateOrderData();
}
} catch (error) {
console.error("Error checking for new orders:", error);
}
};
// Check for new orders every minute
const orderInterval = setInterval(checkForNewOrders, 60000);
// Initial check for orders
checkForNewOrders();
return () => {
clearInterval(orderInterval);
};
}, []);
// Fetch unread chat counts
useEffect(() => {
// Only run this on dashboard pages
if (typeof window === 'undefined' || !window.location.pathname.includes("/dashboard")) return;
const fetchUnreadCounts = async () => {
try {
// Get vendor ID from token
const vendorId = getVendorIdFromToken();
// Use clientFetch which will properly route through Next.js API rewrites
const response = await clientFetch(`/chats/vendor/${vendorId}/unread`);
// Check if there are new notifications and play sound if needed
if (!loading && response.totalUnread > previousUnreadTotal) {
playNotificationSound();
}
// Update chat state - note that clientFetch already parses the JSON response
setUnreadCounts(response);
setPreviousUnreadTotal(response.totalUnread);
if (response.totalUnread > 0) {
const chatIds = Object.keys(response.chatCounts);
if (chatIds.length > 0) {
// Create a simplified metadata object with just needed info
const metadata: Record<string, { buyerId: string }> = {};
// Fetch each chat to get buyer IDs
await Promise.all(
chatIds.map(async (chatId) => {
try {
// Use markAsRead=false to ensure we don't mark messages as read
const chatResponse = await clientFetch(`/chats/${chatId}?markAsRead=false`);
metadata[chatId] = {
buyerId: chatResponse.buyerId,
};
} catch (error) {
console.error(`Error fetching chat ${chatId}:`, error);
}
})
);
setChatMetadata(metadata);
}
}
setLoading(false);
} catch (error) {
console.error("Error fetching unread counts:", error);
setLoading(false);
}
};
// Initial fetch
fetchUnreadCounts();
// Set polling interval (every 10 seconds for more responsive chat notifications)
const chatInterval = setInterval(fetchUnreadCounts, 10000);
return () => clearInterval(chatInterval);
}, [loading, previousUnreadTotal]);
// Navigation handlers // Navigation handlers
const handleChatClick = (chatId: string) => { const handleChatClick = (chatId: string) => {
@@ -281,11 +38,6 @@ export default function UnifiedNotifications() {
router.push(`/dashboard/orders/${orderId}`); router.push(`/dashboard/orders/${orderId}`);
}; };
// Clear notification handlers
const clearOrderNotifications = () => {
setNewOrders([]);
};
// Format the price as currency // Format the price as currency
const formatPrice = (price: number) => { const formatPrice = (price: number) => {
return `£${price.toFixed(2)}`; return `£${price.toFixed(2)}`;

View File

@@ -0,0 +1,343 @@
"use client";
import React, { createContext, useContext, useState, useEffect, useRef, ReactNode } from "react";
import { clientFetch } from "@/lib/api";
import { toast } from "sonner";
import { getCookie } from "@/lib/api";
import { cacheUtils } from '@/lib/api-client';
import { Package } from "lucide-react";
interface Order {
_id: string;
orderId: string;
status: string;
totalPrice: number;
orderDate: string;
underpaid?: boolean;
underpaymentAmount?: number;
}
interface UnreadCounts {
totalUnread: number;
chatCounts: Record<string, number>;
}
interface NotificationContextType {
// Chat notifications
unreadCounts: UnreadCounts;
chatMetadata: Record<string, { buyerId: string }>;
// Order notifications
newOrders: Order[];
clearOrderNotifications: () => void;
// Shared state
totalNotifications: number;
loading: boolean;
}
const NotificationContext = createContext<NotificationContextType | undefined>(undefined);
const STORAGE_KEYS = {
SEEN_ORDER_IDS: 'ember-notifications-seen-orders',
NEW_ORDERS: 'ember-notifications-new-orders',
LAST_CHAT_CHECK: 'ember-notifications-last-chat-check'
};
interface NotificationProviderProps {
children: ReactNode;
}
export function NotificationProvider({ children }: NotificationProviderProps) {
// Chat notification state
const [unreadCounts, setUnreadCounts] = useState<UnreadCounts>({ totalUnread: 0, chatCounts: {} });
const [previousUnreadTotal, setPreviousUnreadTotal] = useState<number>(0);
const [chatMetadata, setChatMetadata] = useState<Record<string, { buyerId: string }>>({});
// Order notification state
const [newOrders, setNewOrders] = useState<Order[]>([]);
const seenOrderIds = useRef<Set<string>>(new Set());
const isInitialOrdersFetch = useRef(true);
// Shared state
const [loading, setLoading] = useState(true);
const audioRef = useRef<HTMLAudioElement | null>(null);
const vendorIdRef = useRef<string | null>(null);
// Total notifications count
const totalNotifications = unreadCounts.totalUnread + newOrders.length;
// Initialize localStorage and audio
useEffect(() => {
// Load seen order IDs from localStorage
const savedSeenOrders = localStorage.getItem(STORAGE_KEYS.SEEN_ORDER_IDS);
if (savedSeenOrders) {
try {
const orderIds = JSON.parse(savedSeenOrders);
seenOrderIds.current = new Set(orderIds);
} catch (error) {
console.error('Error loading seen order IDs from localStorage:', error);
}
}
// Load new orders from localStorage
const savedNewOrders = localStorage.getItem(STORAGE_KEYS.NEW_ORDERS);
if (savedNewOrders) {
try {
const orders = JSON.parse(savedNewOrders);
setNewOrders(orders);
} catch (error) {
console.error('Error loading new orders from localStorage:', error);
}
}
// Initialize audio
audioRef.current = new Audio('/notification.mp3');
audioRef.current.addEventListener('error', () => {
audioRef.current = null;
});
return () => {
if (audioRef.current) {
audioRef.current = null;
}
};
}, []);
// Save seen order IDs to localStorage whenever it changes
const updateSeenOrderIds = (orderIds: Set<string>) => {
seenOrderIds.current = orderIds;
localStorage.setItem(STORAGE_KEYS.SEEN_ORDER_IDS, JSON.stringify(Array.from(orderIds)));
};
// Save new orders to localStorage whenever it changes
useEffect(() => {
localStorage.setItem(STORAGE_KEYS.NEW_ORDERS, JSON.stringify(newOrders));
}, [newOrders]);
// Get vendor ID from JWT token
const getVendorIdFromToken = () => {
if (vendorIdRef.current) {
return vendorIdRef.current;
}
const authToken = getCookie("Authorization") || "";
if (!authToken) {
throw new Error("No auth token found");
}
const tokenParts = authToken.split(".");
if (tokenParts.length !== 3) {
throw new Error("Invalid token format");
}
const payload = JSON.parse(atob(tokenParts[1]));
const vendorId = payload.id;
if (!vendorId) {
throw new Error("Vendor ID not found in token");
}
vendorIdRef.current = vendorId;
return vendorId;
};
// Function to play notification sound
const playNotificationSound = () => {
if (audioRef.current) {
audioRef.current.currentTime = 0;
audioRef.current.play().catch(err => {
console.log('Error playing sound:', err);
// Fallback beep if audio file fails
try {
const context = new (window.AudioContext || (window as any).webkitAudioContext)();
const oscillator = context.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(800, context.currentTime);
oscillator.connect(context.destination);
oscillator.start();
oscillator.stop(context.currentTime + 0.2);
} catch (e) {
console.error('Could not play fallback audio', e);
}
});
}
};
// Check for new paid orders
useEffect(() => {
// Only run this on dashboard pages
if (typeof window === 'undefined' || !window.location.pathname.includes("/dashboard")) return;
const checkForNewOrders = async () => {
try {
// Get orders from the last 24 hours with a more efficient query
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const timestamp = yesterday.toISOString();
const orderData = await clientFetch(`/orders?status=paid&limit=10&orderDate[gte]=${timestamp}`);
const orders: Order[] = orderData.orders || [];
// Filter out orders that are still showing as underpaid (cache issue)
const validPaidOrders = orders.filter(order => {
// Only include orders that are actually fully paid (not underpaid)
return order.status === 'paid' &&
(!order.underpaid || order.underpaymentAmount === 0);
});
// If this is the first fetch, just store the orders without notifications
if (isInitialOrdersFetch.current) {
const orderIds = new Set([...seenOrderIds.current, ...validPaidOrders.map(order => order._id)]);
updateSeenOrderIds(orderIds);
isInitialOrdersFetch.current = false;
return;
}
// Check for new paid orders that haven't been seen before
const latestNewOrders = validPaidOrders.filter(order => !seenOrderIds.current.has(order._id));
// Show notifications for new orders
if (latestNewOrders.length > 0) {
// Update the seen orders set
const updatedSeenOrders = new Set([...seenOrderIds.current, ...latestNewOrders.map(order => order._id)]);
updateSeenOrderIds(updatedSeenOrders);
// Show a toast notification for each new order
latestNewOrders.forEach(order => {
toast.success(
<div className="flex flex-col">
<p className="font-semibold">New Paid Order!</p>
<p className="text-sm">Order #{order.orderId}</p>
<p className="text-sm font-semibold">£{order.totalPrice.toFixed(2)}</p>
</div>,
{
duration: 8000,
icon: <Package className="h-5 w-5" />,
action: {
label: "View",
onClick: () => window.open(`/dashboard/orders/${order._id}`, "_blank")
}
}
);
});
// Play notification sound
playNotificationSound();
// Update the state with new orders for the dropdown
setNewOrders(prev => [...latestNewOrders, ...prev].slice(0, 10));
// Invalidate order cache to ensure all components refresh
cacheUtils.invalidateOrderData();
}
} catch (error) {
console.error("Error checking for new orders:", error);
}
};
// Check for new orders every minute
const orderInterval = setInterval(checkForNewOrders, 60000);
// Initial check for orders
checkForNewOrders();
return () => {
clearInterval(orderInterval);
};
}, []);
// Fetch unread chat counts
useEffect(() => {
// Only run this on dashboard pages
if (typeof window === 'undefined' || !window.location.pathname.includes("/dashboard")) return;
const fetchUnreadCounts = async () => {
try {
// Get vendor ID from token
const vendorId = getVendorIdFromToken();
// Use clientFetch which will properly route through Next.js API rewrites
const response = await clientFetch(`/chats/vendor/${vendorId}/unread`);
// Check if there are new notifications and play sound if needed
if (!loading && response.totalUnread > previousUnreadTotal) {
playNotificationSound();
}
// Update chat state - note that clientFetch already parses the JSON response
setUnreadCounts(response);
setPreviousUnreadTotal(response.totalUnread);
if (response.totalUnread > 0) {
const chatIds = Object.keys(response.chatCounts);
if (chatIds.length > 0) {
// Create a simplified metadata object with just needed info
const metadata: Record<string, { buyerId: string }> = {};
// Fetch each chat to get buyer IDs
await Promise.all(
chatIds.map(async (chatId) => {
try {
// Use markAsRead=false to ensure we don't mark messages as read
const chatResponse = await clientFetch(`/chats/${chatId}?markAsRead=false`);
metadata[chatId] = {
buyerId: chatResponse.buyerId,
};
} catch (error) {
console.error(`Error fetching chat ${chatId}:`, error);
}
})
);
setChatMetadata(metadata);
}
}
setLoading(false);
} catch (error) {
console.error("Error fetching unread counts:", error);
setLoading(false);
}
};
// Initial fetch
fetchUnreadCounts();
// Set polling interval (every 10 seconds for more responsive chat notifications)
const chatInterval = setInterval(fetchUnreadCounts, 10000);
return () => clearInterval(chatInterval);
}, [loading, previousUnreadTotal]);
// Clear notification handlers
const clearOrderNotifications = () => {
setNewOrders([]);
localStorage.removeItem(STORAGE_KEYS.NEW_ORDERS);
};
const contextValue: NotificationContextType = {
unreadCounts,
chatMetadata,
newOrders,
clearOrderNotifications,
totalNotifications,
loading,
};
return (
<NotificationContext.Provider value={contextValue}>
{children}
</NotificationContext.Provider>
);
}
export function useNotifications() {
const context = useContext(NotificationContext);
if (context === undefined) {
throw new Error('useNotifications must be used within a NotificationProvider');
}
return context;
}

View File

@@ -1,4 +1,4 @@
{ {
"commitHash": "308a816", "commitHash": "2452a3c",
"buildTime": "2025-05-23T06:40:22.513Z" "buildTime": "2025-07-28T20:50:17.059Z"
} }