feat: Implement notifications modernization

This commit is contained in:
gpt-engineer-app[bot]
2025-10-14 19:57:43 +00:00
parent 81d0569628
commit 93a77bf091
4 changed files with 599 additions and 336 deletions

View File

@@ -1,95 +1,38 @@
import { supabase } from "@/integrations/supabase/client";
export interface NotificationPayload {
workflowId: string;
subscriberId: string;
payload: Record<string, any>;
overrides?: Record<string, any>;
}
export interface SubscriberData {
subscriberId: string;
email?: string;
firstName?: string;
lastName?: string;
phone?: string;
avatar?: string;
data?: Record<string, any>;
}
export interface NotificationPreferences {
channelPreferences: {
in_app: boolean;
email: boolean;
push: boolean;
sms: boolean;
};
workflowPreferences: Record<string, boolean>;
frequencySettings: {
digest: 'realtime' | 'hourly' | 'daily' | 'weekly';
max_per_hour: number;
};
}
import { logger } from "@/lib/logger";
import { AppError } from "@/lib/errorHandler";
import { z } from "zod";
import type {
NotificationPayload,
SubscriberData,
NotificationPreferences,
NotificationTemplate
} from "@/types/notifications";
import {
notificationPreferencesSchema,
subscriberDataSchema,
DEFAULT_NOTIFICATION_PREFERENCES
} from "@/lib/notificationValidation";
class NotificationService {
private readonly isNovuEnabled: boolean;
constructor() {
this.isNovuEnabled = !!import.meta.env.VITE_NOVU_APPLICATION_IDENTIFIER;
}
private extractErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (error && typeof error === 'object' && 'message' in error && typeof error.message === 'string') {
return error.message;
}
return 'An unexpected error occurred';
}
/**
* Create or update a Novu subscriber
* Check if Novu is enabled by checking admin settings
*/
async createSubscriber(subscriberData: SubscriberData): Promise<{ success: boolean; error?: string }> {
if (!this.isNovuEnabled) {
console.warn('Novu is not configured. Skipping subscriber creation.');
return { success: false, error: 'Novu not configured' };
}
async isNovuEnabled(): Promise<boolean> {
try {
const { data, error } = await supabase.functions.invoke('create-novu-subscriber', {
body: subscriberData,
const { data } = await supabase
.from('admin_settings')
.select('setting_value')
.eq('setting_key', 'novu.application_identifier')
.maybeSingle();
return !!data?.setting_value;
} catch (error) {
logger.error('Failed to check Novu status', {
action: 'check_novu_status',
error: error instanceof Error ? error.message : String(error)
});
if (error) {
console.error('Edge function error creating Novu subscriber:', error);
throw error;
}
if (!data || !data.subscriberId) {
const errorMsg = 'Invalid response from create-novu-subscriber function';
console.error(errorMsg, { data });
return { success: false, error: errorMsg };
}
const { error: dbError } = await supabase
.from('user_notification_preferences')
.upsert({
user_id: subscriberData.subscriberId,
novu_subscriber_id: data.subscriberId,
});
if (dbError) {
console.error('Database error storing subscriber preferences:', dbError);
throw dbError;
}
console.log('Novu subscriber created successfully:', data.subscriberId);
return { success: true };
} catch (error: unknown) {
console.error('Error creating Novu subscriber:', error);
return { success: false, error: this.extractErrorMessage(error) };
return false;
}
}
@@ -97,137 +40,235 @@ class NotificationService {
* Update an existing Novu subscriber's profile information
*/
async updateSubscriber(subscriberData: SubscriberData): Promise<{ success: boolean; error?: string }> {
if (!this.isNovuEnabled) {
console.warn('Novu is not configured. Skipping subscriber update.');
return { success: false, error: 'Novu not configured' };
}
try {
// Validate input
const validated = subscriberDataSchema.parse(subscriberData);
const novuEnabled = await this.isNovuEnabled();
if (!novuEnabled) {
logger.warn('Novu not configured, skipping subscriber update', {
action: 'update_novu_subscriber',
userId: validated.subscriberId
});
return { success: false, error: 'Novu not configured' };
}
const { data, error } = await supabase.functions.invoke('update-novu-subscriber', {
body: subscriberData,
body: validated,
});
if (error) {
console.error('Edge function error updating Novu subscriber:', error);
throw error;
logger.error('Edge function error updating Novu subscriber', {
action: 'update_novu_subscriber',
userId: validated.subscriberId,
error: error.message
});
throw new AppError(
'Failed to update notification subscriber',
'NOTIFICATION_ERROR',
error.message
);
}
console.log('Novu subscriber updated successfully:', subscriberData.subscriberId);
logger.info('Novu subscriber updated successfully', {
action: 'update_novu_subscriber',
userId: validated.subscriberId
});
return { success: true };
} catch (error: unknown) {
console.error('Error updating Novu subscriber:', error);
return { success: false, error: this.extractErrorMessage(error) };
} catch (error) {
logger.error('Error in updateSubscriber', {
action: 'update_novu_subscriber',
userId: subscriberData.subscriberId,
error: error instanceof Error ? error.message : String(error)
});
return {
success: false,
error: error instanceof AppError ? error.message : 'Failed to update subscriber'
};
}
}
/**
* Update subscriber preferences in Novu
* Create or update a Novu subscriber
*/
async createSubscriber(subscriberData: SubscriberData): Promise<{ success: boolean; error?: string }> {
try {
// Validate input
const validated = subscriberDataSchema.parse(subscriberData);
const novuEnabled = await this.isNovuEnabled();
if (!novuEnabled) {
logger.warn('Novu not configured, skipping subscriber creation', {
action: 'create_novu_subscriber',
userId: validated.subscriberId
});
return { success: false, error: 'Novu not configured' };
}
const { data, error } = await supabase.functions.invoke('create-novu-subscriber', {
body: validated,
});
if (error) {
logger.error('Edge function error creating Novu subscriber', {
action: 'create_novu_subscriber',
userId: validated.subscriberId,
error: error.message
});
throw new AppError(
'Failed to create notification subscriber',
'NOTIFICATION_ERROR',
error.message
);
}
if (!data?.subscriberId) {
throw new AppError(
'Invalid response from notification service',
'NOTIFICATION_ERROR'
);
}
// Store subscriber ID in database
const { error: dbError } = await supabase
.from('user_notification_preferences')
.upsert({
user_id: validated.subscriberId,
novu_subscriber_id: data.subscriberId,
});
if (dbError) {
logger.error('Failed to store subscriber preferences', {
action: 'store_subscriber_preferences',
userId: validated.subscriberId,
error: dbError.message,
errorCode: dbError.code
});
throw dbError;
}
logger.info('Novu subscriber created successfully', {
action: 'create_novu_subscriber',
userId: validated.subscriberId
});
return { success: true };
} catch (error) {
logger.error('Error in createSubscriber', {
action: 'create_novu_subscriber',
userId: subscriberData.subscriberId,
error: error instanceof Error ? error.message : String(error)
});
return {
success: false,
error: error instanceof AppError ? error.message : 'Failed to create subscriber'
};
}
}
/**
* Update notification preferences with validation and audit logging
*/
async updatePreferences(
userId: string,
preferences: NotificationPreferences
): Promise<{ success: boolean; error?: string }> {
if (!this.isNovuEnabled) {
try {
const { error } = await supabase
.from('user_notification_preferences')
.upsert({
user_id: userId,
channel_preferences: preferences.channelPreferences,
workflow_preferences: preferences.workflowPreferences,
frequency_settings: preferences.frequencySettings,
});
if (error) {
console.error('Database error saving preferences (Novu disabled):', error);
throw error;
}
console.log('Preferences saved to local database:', userId);
return { success: true };
} catch (error: unknown) {
console.error('Error saving preferences to local database:', error);
return { success: false, error: this.extractErrorMessage(error) };
}
}
try {
const { error } = await supabase.functions.invoke('update-novu-preferences', {
body: {
userId,
preferences,
},
});
// Validate preferences
const validated = notificationPreferencesSchema.parse(preferences);
if (error) {
console.error('Edge function error updating Novu preferences:', error);
throw error;
// Get previous preferences for audit log
const { data: previousPrefs } = await supabase
.from('user_notification_preferences')
.select('channel_preferences, workflow_preferences, frequency_settings')
.eq('user_id', userId)
.maybeSingle();
const novuEnabled = await this.isNovuEnabled();
// Update Novu preferences if enabled
if (novuEnabled) {
const { error: novuError } = await supabase.functions.invoke('update-novu-preferences', {
body: {
userId,
preferences: validated,
},
});
if (novuError) {
logger.error('Failed to update Novu preferences', {
action: 'update_novu_preferences',
userId,
error: novuError.message
});
throw novuError;
}
}
// Update local database
const { error: dbError } = await supabase
.from('user_notification_preferences')
.upsert({
user_id: userId,
channel_preferences: preferences.channelPreferences,
workflow_preferences: preferences.workflowPreferences,
frequency_settings: preferences.frequencySettings,
channel_preferences: validated.channelPreferences,
workflow_preferences: validated.workflowPreferences,
frequency_settings: validated.frequencySettings,
});
if (dbError) {
console.error('Database error saving preferences locally:', dbError);
logger.error('Failed to save notification preferences', {
action: 'save_notification_preferences',
userId,
error: dbError.message,
errorCode: dbError.code
});
throw dbError;
}
console.log('Preferences updated successfully:', userId);
// Create audit log entry
await supabase.from('profile_audit_log').insert([{
user_id: userId,
changed_by: userId,
action: 'notification_preferences_updated',
changes: {
previous: previousPrefs || null,
updated: validated,
timestamp: new Date().toISOString()
} as any
}]);
logger.info('Notification preferences updated', {
action: 'update_notification_preferences',
userId
});
return { success: true };
} catch (error: unknown) {
console.error('Error updating preferences:', error);
return { success: false, error: this.extractErrorMessage(error) };
} catch (error) {
logger.error('Error updating notification preferences', {
action: 'update_notification_preferences',
userId,
error: error instanceof Error ? error.message : String(error)
});
if (error instanceof z.ZodError) {
return {
success: false,
error: `Invalid preferences: ${error.issues.map(i => i.message).join(', ')}`
};
}
return {
success: false,
error: 'Failed to update notification preferences'
};
}
}
/**
* Trigger a notification workflow
*/
async trigger(payload: NotificationPayload): Promise<{ success: boolean; transactionId?: string; error?: string }> {
if (!this.isNovuEnabled) {
console.warn('Novu is not configured. Notification not sent.');
return { success: false, error: 'Novu not configured' };
}
try {
const { data, error } = await supabase.functions.invoke('trigger-notification', {
body: payload,
});
if (error) {
console.error('Edge function error triggering notification:', error);
throw error;
}
if (!data || !data.transactionId) {
const errorMsg = 'Invalid response from trigger-notification function';
console.error(errorMsg, { data });
return { success: false, error: errorMsg };
}
await this.logNotification({
userId: payload.subscriberId,
workflowId: payload.workflowId,
transactionId: data.transactionId,
payload: payload.payload,
});
console.log('Notification triggered successfully:', data.transactionId);
return { success: true, transactionId: data.transactionId };
} catch (error: unknown) {
console.error('Error triggering notification:', error);
return { success: false, error: this.extractErrorMessage(error) };
}
}
/**
* Get user's notification preferences
* Get user's notification preferences with proper typing
*/
async getPreferences(userId: string): Promise<NotificationPreferences | null> {
try {
@@ -235,37 +276,38 @@ class NotificationService {
.from('user_notification_preferences')
.select('channel_preferences, workflow_preferences, frequency_settings')
.eq('user_id', userId)
.single();
.maybeSingle();
if (error && error.code !== 'PGRST116') {
console.error('Database error fetching preferences:', error);
logger.error('Failed to fetch notification preferences', {
action: 'fetch_notification_preferences',
userId,
error: error.message,
errorCode: error.code
});
throw error;
}
if (!data) {
console.log('No preferences found for user, returning defaults:', userId);
return {
channelPreferences: {
in_app: true,
email: true,
push: false,
sms: false,
},
workflowPreferences: {},
frequencySettings: {
digest: 'daily',
max_per_hour: 10,
},
};
logger.info('No preferences found, returning defaults', {
action: 'fetch_notification_preferences',
userId
});
return DEFAULT_NOTIFICATION_PREFERENCES;
}
return {
channelPreferences: data.channel_preferences as any,
workflowPreferences: data.workflow_preferences as any,
frequencySettings: data.frequency_settings as any,
};
} catch (error: unknown) {
console.error('Error fetching notification preferences for user:', userId, error);
// Validate the data from database
return notificationPreferencesSchema.parse({
channelPreferences: data.channel_preferences,
workflowPreferences: data.workflow_preferences,
frequencySettings: data.frequency_settings
});
} catch (error) {
logger.error('Error fetching notification preferences', {
action: 'fetch_notification_preferences',
userId,
error: error instanceof Error ? error.message : String(error)
});
return null;
}
}
@@ -273,7 +315,7 @@ class NotificationService {
/**
* Get notification templates
*/
async getTemplates(): Promise<any[]> {
async getTemplates(): Promise<NotificationTemplate[]> {
try {
const { data, error } = await supabase
.from('notification_templates')
@@ -282,90 +324,117 @@ class NotificationService {
.order('category', { ascending: true });
if (error) {
console.error('Database error fetching notification templates:', error);
logger.error('Failed to fetch notification templates', {
action: 'fetch_notification_templates',
error: error.message,
errorCode: error.code
});
throw error;
}
return data || [];
} catch (error: unknown) {
console.error('Error fetching notification templates:', error);
} catch (error) {
logger.error('Error fetching notification templates', {
action: 'fetch_notification_templates',
error: error instanceof Error ? error.message : String(error)
});
return [];
}
}
/**
* Log notification in database
* Trigger a notification workflow
*/
private async logNotification(log: {
userId: string;
workflowId: string;
transactionId: string;
payload: Record<string, any>;
}): Promise<void> {
async trigger(payload: NotificationPayload): Promise<{ success: boolean; error?: string }> {
try {
// Get template ID from workflow ID
const { data: template } = await supabase
.from('notification_templates')
.select('id')
.eq('workflow_id', log.workflowId)
.single();
const { error: logError } = await supabase.from('notification_logs').insert({
user_id: log.userId,
template_id: template?.id,
novu_transaction_id: log.transactionId,
channel: 'multi',
status: 'sent',
payload: log.payload,
});
if (logError) {
console.error('Error inserting notification log:', logError);
const novuEnabled = await this.isNovuEnabled();
if (!novuEnabled) {
logger.warn('Novu not configured, skipping notification', {
action: 'trigger_notification',
workflowId: payload.workflowId,
subscriberId: payload.subscriberId
});
return { success: false, error: 'Novu not configured' };
}
const { data, error } = await supabase.functions.invoke('trigger-notification', {
body: payload
});
if (error) {
logger.error('Failed to trigger notification', {
action: 'trigger_notification',
workflowId: payload.workflowId,
subscriberId: payload.subscriberId,
error: error.message
});
throw error;
}
logger.info('Notification triggered successfully', {
action: 'trigger_notification',
workflowId: payload.workflowId,
subscriberId: payload.subscriberId,
transactionId: data?.transactionId
});
return { success: true };
} catch (error) {
console.error('Error logging notification:', error);
logger.error('Error triggering notification', {
action: 'trigger_notification',
workflowId: payload.workflowId,
subscriberId: payload.subscriberId,
error: error instanceof Error ? error.message : String(error)
});
return {
success: false,
error: 'Failed to trigger notification'
};
}
}
/**
* Notify all moderators about a new submission
* Notify moderators (legacy method for backward compatibility)
*/
async notifyModerators(payload: {
submission_id: string;
submission_type: string;
submitter_name: string;
action: string;
}): Promise<{ success: boolean; count: number; error?: string }> {
}): Promise<void> {
try {
const { data, error } = await supabase.functions.invoke('notify-moderators-submission', {
body: payload,
const { error } = await supabase.functions.invoke('notify-moderators-submission', {
body: payload
});
if (error) {
console.error('Edge function error notifying moderators:', error);
logger.error('Failed to notify moderators', {
action: 'notify_moderators',
submissionId: payload.submission_id,
error: error.message
});
throw error;
}
console.log('Moderators notified successfully:', data);
return {
success: true,
count: data?.count || 0
};
} catch (error: unknown) {
console.error('Error notifying moderators:', error);
return {
success: false,
count: 0,
error: this.extractErrorMessage(error)
};
logger.info('Moderators notified successfully', {
action: 'notify_moderators',
submissionId: payload.submission_id
});
} catch (error) {
logger.error('Error notifying moderators', {
action: 'notify_moderators',
submissionId: payload.submission_id,
error: error instanceof Error ? error.message : String(error)
});
}
}
/**
* Check if Novu is enabled
* Check if notifications are enabled
*/
isEnabled(): boolean {
return this.isNovuEnabled;
return true; // Always return true, actual check happens in isNovuEnabled()
}
}

View File

@@ -0,0 +1,64 @@
import { z } from 'zod';
import type { NotificationPreferences } from '@/types/notifications';
/**
* Schema for channel preferences
*/
export const channelPreferencesSchema = z.object({
in_app: z.boolean(),
email: z.boolean(),
push: z.boolean(),
sms: z.boolean()
});
/**
* Schema for workflow preferences (dynamic keys)
*/
export const workflowPreferencesSchema = z.record(z.string(), z.boolean());
/**
* Schema for frequency settings
*/
export const frequencySettingsSchema = z.object({
digest: z.enum(['realtime', 'hourly', 'daily', 'weekly'] as const),
max_per_hour: z.number().int().min(1).max(999)
});
/**
* Complete notification preferences schema
*/
export const notificationPreferencesSchema = z.object({
channelPreferences: channelPreferencesSchema,
workflowPreferences: workflowPreferencesSchema,
frequencySettings: frequencySettingsSchema
});
/**
* Schema for subscriber data
*/
export const subscriberDataSchema = z.object({
subscriberId: z.string().uuid('Invalid subscriber ID'),
email: z.string().email('Invalid email').optional(),
firstName: z.string().max(100).optional(),
lastName: z.string().max(100).optional(),
phone: z.string().max(20).optional(),
avatar: z.string().url('Invalid avatar URL').optional(),
data: z.record(z.string(), z.any()).optional()
});
/**
* Default notification preferences for new users
*/
export const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = {
channelPreferences: {
in_app: true,
email: true,
push: false,
sms: false
},
workflowPreferences: {},
frequencySettings: {
digest: 'daily',
max_per_hour: 10
}
};