This commit is contained in:
NotII
2025-03-04 22:52:39 +00:00
parent c7a2ee0234
commit 75e0b65e11
4 changed files with 249 additions and 7 deletions

View File

@@ -1,6 +1,6 @@
"use client"
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -22,9 +22,63 @@ interface UnreadCounts {
export default function ChatNotifications() {
const router = useRouter();
const [unreadCounts, setUnreadCounts] = useState<UnreadCounts>({ totalUnread: 0, chatCounts: {} });
const [previousUnreadTotal, setPreviousUnreadTotal] = useState<number>(0);
const [loading, setLoading] = useState(true);
const [chatMetadata, setChatMetadata] = useState<Record<string, { buyerId: string }>>({});
const audioRef = useRef<HTMLAudioElement | null>(null);
// Initialize audio element
useEffect(() => {
// Create audio element for notification sound
audioRef.current = new Audio('/notification.mp3');
// Fallback if notification.mp3 doesn't exist - use browser API for a simple beep
audioRef.current.addEventListener('error', () => {
audioRef.current = null;
});
return () => {
if (audioRef.current) {
audioRef.current = null;
}
};
}, []);
// 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 to simple 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);
}
});
} else {
// Fallback to simple beep if audio element is not available
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);
}
}
};
// Fetch unread counts
useEffect(() => {
const fetchUnreadCounts = async () => {
@@ -52,7 +106,15 @@ export default function ChatNotifications() {
}
const response = await authAxios.get(`/chats/vendor/${vendorId}/unread`);
// Check if there are new notifications and play sound if needed
if (!loading && response.data.totalUnread > previousUnreadTotal) {
playNotificationSound();
}
// Update state
setUnreadCounts(response.data);
setPreviousUnreadTotal(response.data.totalUnread);
if (response.data.totalUnread > 0) {
const chatIds = Object.keys(response.data.chatCounts);
@@ -65,7 +127,8 @@ export default function ChatNotifications() {
await Promise.all(
chatIds.map(async (chatId) => {
try {
const chatResponse = await authAxios.get(`/chats/${chatId}`);
// Use markAsRead=false to ensure we don't mark messages as read
const chatResponse = await authAxios.get(`/chats/${chatId}?markAsRead=false`);
metadata[chatId] = {
buyerId: chatResponse.data.buyerId,
};
@@ -91,7 +154,7 @@ export default function ChatNotifications() {
const intervalId = setInterval(fetchUnreadCounts, 30000);
return () => clearInterval(intervalId);
}, []);
}, [loading, previousUnreadTotal]);
const handleChatClick = (chatId: string) => {
router.push(`/dashboard/chats/${chatId}`);