fix
This commit is contained in:
990
package-lock.json
generated
990
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,7 @@
|
|||||||
"@giphy/react-components": "^10.1.1",
|
"@giphy/react-components": "^10.1.1",
|
||||||
"axios": "^1.13.2",
|
"axios": "^1.13.2",
|
||||||
"emoji-mart": "^5.6.0",
|
"emoji-mart": "^5.6.0",
|
||||||
|
"firebase": "^12.9.0",
|
||||||
"next": "16.1.0",
|
"next": "16.1.0",
|
||||||
"next-auth": "^5.0.0-beta.30",
|
"next-auth": "^5.0.0-beta.30",
|
||||||
"react": "19.2.3",
|
"react": "19.2.3",
|
||||||
|
|||||||
51
public/firebase-messaging-sw.js
Normal file
51
public/firebase-messaging-sw.js
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
/* eslint-disable no-undef */
|
||||||
|
// Firebase Cloud Messaging Service Worker
|
||||||
|
// Handles background push notifications when the app is not focused
|
||||||
|
|
||||||
|
importScripts('https://www.gstatic.com/firebasejs/10.14.1/firebase-app-compat.js');
|
||||||
|
importScripts('https://www.gstatic.com/firebasejs/10.14.1/firebase-messaging-compat.js');
|
||||||
|
|
||||||
|
// Firebase config (public values - safe to expose)
|
||||||
|
firebase.initializeApp({
|
||||||
|
apiKey: 'AIzaSyAZZt56_bDMhY_dQb0R9-yUPpDgXP4sDLs',
|
||||||
|
authDomain: 'real-estate-2d71e.firebaseapp.com',
|
||||||
|
projectId: 'real-estate-2d71e',
|
||||||
|
storageBucket: 'real-estate-2d71e.firebasestorage.app',
|
||||||
|
messagingSenderId: '703616926518',
|
||||||
|
appId: '1:703616926518:web:9d1291a2410b18c7fca997',
|
||||||
|
});
|
||||||
|
|
||||||
|
const messaging = firebase.messaging();
|
||||||
|
|
||||||
|
messaging.onBackgroundMessage((payload) => {
|
||||||
|
const notificationTitle = payload.notification?.title || 'New Notification';
|
||||||
|
const notificationOptions = {
|
||||||
|
body: payload.notification?.body || '',
|
||||||
|
icon: '/assets/icons/notification-bell-icon.svg',
|
||||||
|
badge: '/assets/icons/notification-bell-icon.svg',
|
||||||
|
data: payload.data || {},
|
||||||
|
};
|
||||||
|
|
||||||
|
self.registration.showNotification(notificationTitle, notificationOptions);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle notification click
|
||||||
|
self.addEventListener('notificationclick', (event) => {
|
||||||
|
event.notification.close();
|
||||||
|
|
||||||
|
const link = event.notification.data?.link || '/';
|
||||||
|
|
||||||
|
event.waitUntil(
|
||||||
|
clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
|
||||||
|
// Focus existing window if available
|
||||||
|
for (const client of clientList) {
|
||||||
|
if (client.url.includes(self.location.origin) && 'focus' in client) {
|
||||||
|
client.navigate(link);
|
||||||
|
return client.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Open new window
|
||||||
|
return clients.openWindow(link);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
|
|||||||
import { Geist, Geist_Mono } from "next/font/google";
|
import { Geist, Geist_Mono } from "next/font/google";
|
||||||
import localFont from "next/font/local";
|
import localFont from "next/font/local";
|
||||||
import { SessionProvider } from "@/components/providers/session-provider";
|
import { SessionProvider } from "@/components/providers/session-provider";
|
||||||
|
import { NotificationProvider } from "@/components/providers/notification-provider";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
const geistSans = Geist({
|
const geistSans = Geist({
|
||||||
@@ -133,7 +134,10 @@ export default function RootLayout({
|
|||||||
<body
|
<body
|
||||||
className={`${geistSans.variable} ${geistMono.variable} ${sourceSerif4.variable} ${fractul.variable} antialiased`}
|
className={`${geistSans.variable} ${geistMono.variable} ${sourceSerif4.variable} ${fractul.variable} antialiased`}
|
||||||
>
|
>
|
||||||
<SessionProvider>{children}</SessionProvider>
|
<SessionProvider>
|
||||||
|
<NotificationProvider />
|
||||||
|
{children}
|
||||||
|
</SessionProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
99
src/components/providers/notification-provider.tsx
Normal file
99
src/components/providers/notification-provider.tsx
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState, useCallback } from "react";
|
||||||
|
import { useSession } from "next-auth/react";
|
||||||
|
import { notificationService } from "@/services/notification.service";
|
||||||
|
|
||||||
|
interface ToastNotification {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let toastId = 0;
|
||||||
|
|
||||||
|
export function NotificationProvider() {
|
||||||
|
const { status } = useSession();
|
||||||
|
const initialized = useRef(false);
|
||||||
|
const [toasts, setToasts] = useState<ToastNotification[]>([]);
|
||||||
|
|
||||||
|
const addToast = useCallback(
|
||||||
|
(payload: { title: string; body: string }) => {
|
||||||
|
const id = ++toastId;
|
||||||
|
setToasts((prev) => [...prev, { id, title: payload.title, body: payload.body }]);
|
||||||
|
setTimeout(() => {
|
||||||
|
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||||
|
}, 5000);
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
const removeToast = useCallback((id: number) => {
|
||||||
|
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (status !== "authenticated" || initialized.current) return;
|
||||||
|
initialized.current = true;
|
||||||
|
|
||||||
|
let unsubscribe: (() => void) | null = null;
|
||||||
|
|
||||||
|
const init = async () => {
|
||||||
|
const registered = await notificationService.requestPermissionAndRegister();
|
||||||
|
if (registered) {
|
||||||
|
unsubscribe = notificationService.setupForegroundHandler(addToast);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
init();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (unsubscribe) unsubscribe();
|
||||||
|
};
|
||||||
|
}, [status, addToast]);
|
||||||
|
|
||||||
|
// Reset on logout
|
||||||
|
useEffect(() => {
|
||||||
|
if (status === "unauthenticated") {
|
||||||
|
initialized.current = false;
|
||||||
|
}
|
||||||
|
}, [status]);
|
||||||
|
|
||||||
|
if (toasts.length === 0) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: "fixed",
|
||||||
|
top: 16,
|
||||||
|
right: 16,
|
||||||
|
zIndex: 9999,
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
gap: 8,
|
||||||
|
maxWidth: 360,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{toasts.map((toast) => (
|
||||||
|
<div
|
||||||
|
key={toast.id}
|
||||||
|
onClick={() => removeToast(toast.id)}
|
||||||
|
style={{
|
||||||
|
background: "#fff",
|
||||||
|
borderRadius: 10,
|
||||||
|
padding: "12px 16px",
|
||||||
|
boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
|
||||||
|
borderLeft: "4px solid #e58625",
|
||||||
|
cursor: "pointer",
|
||||||
|
animation: "slideIn 0.3s ease-out",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ fontWeight: 600, fontSize: 14, color: "#00293d", marginBottom: 4 }}>
|
||||||
|
{toast.title}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 13, color: "#666" }}>{toast.body}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
15
src/lib/firebase.ts
Normal file
15
src/lib/firebase.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { initializeApp, getApps } from 'firebase/app';
|
||||||
|
import { getMessaging, getToken, onMessage, isSupported } from 'firebase/messaging';
|
||||||
|
|
||||||
|
const firebaseConfig = {
|
||||||
|
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
|
||||||
|
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
|
||||||
|
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
|
||||||
|
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
|
||||||
|
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
|
||||||
|
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
|
||||||
|
};
|
||||||
|
|
||||||
|
const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];
|
||||||
|
|
||||||
|
export { app, getMessaging, getToken, onMessage, isSupported };
|
||||||
@@ -54,3 +54,6 @@ export { messagesService } from './messages.service';
|
|||||||
|
|
||||||
// CMS Service
|
// CMS Service
|
||||||
export { cmsService } from './cms.service';
|
export { cmsService } from './cms.service';
|
||||||
|
|
||||||
|
// Notification Service
|
||||||
|
export { notificationService } from './notification.service';
|
||||||
|
|||||||
95
src/services/notification.service.ts
Normal file
95
src/services/notification.service.ts
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import { app, getMessaging, getToken, onMessage, isSupported } from '@/lib/firebase';
|
||||||
|
import api from './api';
|
||||||
|
|
||||||
|
const VAPID_KEY = process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY;
|
||||||
|
|
||||||
|
class NotificationService {
|
||||||
|
private currentToken: string | null = null;
|
||||||
|
|
||||||
|
async requestPermissionAndRegister(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
// Check if messaging is supported in this browser
|
||||||
|
const supported = await isSupported();
|
||||||
|
if (!supported) {
|
||||||
|
console.log('[Notifications] Firebase messaging not supported in this browser');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!VAPID_KEY) {
|
||||||
|
console.warn('[Notifications] VAPID key not configured');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request notification permission
|
||||||
|
const permission = await Notification.requestPermission();
|
||||||
|
if (permission !== 'granted') {
|
||||||
|
console.log('[Notifications] Permission denied');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register service worker
|
||||||
|
const registration = await navigator.serviceWorker.register(
|
||||||
|
'/firebase-messaging-sw.js'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Get FCM token
|
||||||
|
const messaging = getMessaging(app);
|
||||||
|
const token = await getToken(messaging, {
|
||||||
|
vapidKey: VAPID_KEY,
|
||||||
|
serviceWorkerRegistration: registration,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
console.warn('[Notifications] No FCM token received');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.currentToken = token;
|
||||||
|
|
||||||
|
// Register token with backend
|
||||||
|
await api.post('/notifications/fcm-token', {
|
||||||
|
token,
|
||||||
|
device: 'web',
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[Notifications] FCM token registered');
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[Notifications] Registration failed:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async unregister(): Promise<void> {
|
||||||
|
try {
|
||||||
|
if (this.currentToken) {
|
||||||
|
await api.delete('/notifications/fcm-token', {
|
||||||
|
data: { token: this.currentToken },
|
||||||
|
});
|
||||||
|
this.currentToken = null;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[Notifications] Unregister failed:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setupForegroundHandler(
|
||||||
|
callback: (payload: { title: string; body: string; data?: Record<string, string> }) => void
|
||||||
|
): (() => void) | null {
|
||||||
|
try {
|
||||||
|
const messaging = getMessaging(app);
|
||||||
|
const unsubscribe = onMessage(messaging, (payload) => {
|
||||||
|
callback({
|
||||||
|
title: payload.notification?.title || 'New Notification',
|
||||||
|
body: payload.notification?.body || '',
|
||||||
|
data: payload.data as Record<string, string>,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return unsubscribe;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const notificationService = new NotificationService();
|
||||||
Reference in New Issue
Block a user