src services notifications.tsx
Anonymous
plain_text
02/18/2026 1:48 AM
10.1 KB
9
Indexable
import { supabase } from '@/constants/supabase';
export interface Notification {
id: string;
user_id: string;
type: string;
title: string;
message: string;
related_id?: string;
related_type?: string;
action_url?: string;
is_read: boolean;
read_at?: string;
push_sent: boolean;
email_sent: boolean;
created_at: string;
updated_at: string;
}
/**
* Create a notification
*/
export async function createNotification(notification: {
user_id: string;
type: string;
title: string;
message: string;
related_id?: string;
related_type?: string;
action_url?: string;
}): Promise<{ success: boolean; data?: Notification; error?: string }> {
try {
console.log('[Notifications] Creating notification for user:', notification.user_id);
const { data, error } = await supabase
.from('notifications')
.insert({
...notification,
is_read: false,
push_sent: false,
email_sent: false,
})
.select()
.single();
if (error) {
console.error('[Notifications] Error creating notification:', error.message, error);
return { success: false, error: error.message };
}
console.log('[Notifications] Notification created successfully:', data.id);
return { success: true, data };
} catch (error: any) {
console.error('[Notifications] Exception creating notification:', error?.message || error, error);
return { success: false, error: error?.message || 'Failed to create notification' };
}
}
/**
* Get all notifications for a user
*/
export async function getUserNotifications(
userId: string,
limit: number = 50
): Promise<{ success: boolean; data?: Notification[]; error?: string }> {
try {
console.log('[Notifications] Fetching notifications for user:', userId);
const { data, error } = await supabase
.from('notifications')
.select('*')
.eq('user_id', userId)
.order('created_at', { ascending: false })
.limit(limit);
if (error) {
console.error('[Notifications] Error fetching notifications:', error.message, error);
return { success: false, error: error.message };
}
console.log('[Notifications] Found', data?.length || 0, 'notifications');
return { success: true, data: data || [] };
} catch (error: any) {
console.error('[Notifications] Exception fetching notifications:', error);
return { success: false, error: error?.message || 'Failed to fetch notifications' };
}
}
/**
* Get unread notifications count
*/
export async function getUnreadCount(
userId: string
): Promise<{ success: boolean; count?: number; error?: string }> {
try {
const { count, error } = await supabase
.from('notifications')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('is_read', false);
if (error) {
console.error('[Notifications] Error getting unread count:', error.message, error);
return { success: false, error: error.message };
}
return { success: true, count: count || 0 };
} catch (error: any) {
console.error('[Notifications] Exception getting unread count:', error);
return { success: false, error: error?.message || 'Failed to get unread count' };
}
}
/**
* Mark notification as read
*/
export async function markAsRead(
notificationId: string
): Promise<{ success: boolean; error?: string }> {
try {
console.log('[Notifications] Marking notification as read:', notificationId);
const { error } = await supabase
.from('notifications')
.update({
is_read: true,
read_at: new Date().toISOString(),
})
.eq('id', notificationId);
if (error) {
console.error('[Notifications] Error marking as read:', error.message, error);
return { success: false, error: error.message };
}
console.log('[Notifications] Notification marked as read');
return { success: true };
} catch (error: any) {
console.error('[Notifications] Exception marking as read:', error);
return { success: false, error: error?.message || 'Failed to mark as read' };
}
}
/**
* Mark all notifications as read for a user
*/
export async function markAllAsRead(
userId: string
): Promise<{ success: boolean; error?: string }> {
try {
console.log('[Notifications] Marking all notifications as read for user:', userId);
const { error } = await supabase
.from('notifications')
.update({
is_read: true,
read_at: new Date().toISOString(),
})
.eq('user_id', userId)
.eq('is_read', false);
if (error) {
console.error('[Notifications] Error marking all as read:', error.message, error);
return { success: false, error: error.message };
}
console.log('[Notifications] All notifications marked as read');
return { success: true };
} catch (error: any) {
console.error('[Notifications] Exception marking all as read:', error);
return { success: false, error: error?.message || 'Failed to mark all as read' };
}
}
/**
* Delete a notification
*/
export async function deleteNotification(
notificationId: string
): Promise<{ success: boolean; error?: string }> {
try {
console.log('[Notifications] Deleting notification:', notificationId);
const { error } = await supabase
.from('notifications')
.delete()
.eq('id', notificationId);
if (error) {
console.error('[Notifications] Error deleting notification:', error.message, error);
return { success: false, error: error.message };
}
console.log('[Notifications] Notification deleted');
return { success: true };
} catch (error: any) {
console.error('[Notifications] Exception deleting notification:', error);
return { success: false, error: error?.message || 'Failed to delete notification' };
}
}
/**
* Delete all notifications for a user
*/
export async function clearNotifications(
userId: string
): Promise<{ success: boolean; error?: string }> {
try {
console.log('[Notifications] Clearing all notifications for user:', userId);
const { error } = await supabase
.from('notifications')
.delete()
.eq('user_id', userId);
if (error) {
console.error('[Notifications] Error clearing notifications:', error.message, error);
return { success: false, error: error.message };
}
console.log('[Notifications] Notifications cleared');
return { success: true };
} catch (error: any) {
console.error('[Notifications] Exception clearing notifications:', error);
return { success: false, error: error?.message || 'Failed to clear notifications' };
}
}
/**
* Subscribe to real-time notification updates
*/
export function subscribeToNotifications(
userId: string,
onNewNotification: (notification: Notification) => void
) {
console.log('[Notifications] Subscribing to notifications for user:', userId);
const channel = supabase
.channel(`notifications:${userId}`)
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'notifications',
filter: `user_id=eq.${userId}`,
},
(payload) => {
console.log('[Notifications] New notification received:', payload);
onNewNotification(payload.new as Notification);
}
)
.subscribe();
return () => {
console.log('[Notifications] Unsubscribing from notifications');
supabase.removeChannel(channel);
};
}
Editor is loading...
Leave a Comment