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

@@ -8,48 +8,32 @@ import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { Skeleton } from "@/components/ui/skeleton";
import { handleError, handleSuccess, handleInfo } from "@/lib/errorHandler";
import { logger } from "@/lib/logger";
import { notificationService } from "@/lib/notificationService";
interface ChannelPreferences {
in_app: boolean;
email: boolean;
push: boolean;
}
interface WorkflowPreferences {
[workflowId: string]: boolean;
}
interface FrequencySettings {
digest: 'realtime' | 'hourly' | 'daily' | 'weekly';
max_per_hour: number;
}
interface NotificationTemplate {
id: string;
workflow_id: string;
name: string;
description: string;
category: string;
is_active: boolean;
}
import type {
NotificationPreferences,
NotificationTemplate,
ChannelPreferences,
WorkflowPreferences,
FrequencySettings
} from "@/types/notifications";
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@/lib/notificationValidation";
export function NotificationsTab() {
const { user } = useAuth();
const { isEnabled: isNovuEnabled, isLoading: isNovuLoading } = usePublicNovuSettings();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
const [channelPreferences, setChannelPreferences] = useState<ChannelPreferences>({
in_app: true,
email: true,
push: false,
});
const [channelPreferences, setChannelPreferences] = useState<ChannelPreferences>(
DEFAULT_NOTIFICATION_PREFERENCES.channelPreferences
);
const [workflowPreferences, setWorkflowPreferences] = useState<WorkflowPreferences>({});
const [frequencySettings, setFrequencySettings] = useState<FrequencySettings>({
digest: 'daily',
max_per_hour: 10,
});
const [frequencySettings, setFrequencySettings] = useState<FrequencySettings>(
DEFAULT_NOTIFICATION_PREFERENCES.frequencySettings
);
useEffect(() => {
if (user) {
@@ -65,71 +49,109 @@ export function NotificationsTab() {
const preferences = await notificationService.getPreferences(user.id);
if (preferences) {
const { sms, ...channelPrefs } = preferences.channelPreferences;
setChannelPreferences(channelPrefs);
setChannelPreferences(preferences.channelPreferences);
setWorkflowPreferences(preferences.workflowPreferences);
setFrequencySettings(preferences.frequencySettings);
}
logger.info('Notification preferences loaded', {
action: 'load_notification_preferences',
userId: user.id
});
} catch (error) {
console.error('Error loading preferences:', error);
toast.error("Failed to load notification preferences");
logger.error('Failed to load notification preferences', {
action: 'load_notification_preferences',
userId: user.id,
error: error instanceof Error ? error.message : String(error)
});
handleError(error, {
action: 'Load notification preferences',
userId: user.id
});
} finally {
setLoading(false);
}
};
const loadTemplates = async () => {
if (!user) return;
try {
const templateData = await notificationService.getTemplates();
setTemplates(templateData);
// Initialize workflow preferences if not set
// Initialize workflow preferences for new templates
const initialPrefs: WorkflowPreferences = {};
templateData.forEach((template) => {
if (!(template.workflow_id in workflowPreferences)) {
initialPrefs[template.workflow_id] = true;
}
});
if (Object.keys(initialPrefs).length > 0) {
setWorkflowPreferences((prev) => ({ ...prev, ...initialPrefs }));
}
logger.info('Notification templates loaded', {
action: 'load_notification_templates',
userId: user.id,
count: templateData.length
});
} catch (error) {
console.error('Error loading templates:', error);
logger.error('Failed to load notification templates', {
action: 'load_notification_templates',
userId: user.id,
error: error instanceof Error ? error.message : String(error)
});
handleError(error, {
action: 'Load notification templates',
userId: user.id
});
}
};
const savePreferences = async () => {
if (!user) return;
setLoading(true);
setSaving(true);
try {
const result = await notificationService.updatePreferences(user.id, {
channelPreferences: {
...channelPreferences,
sms: false, // SMS not supported in UI
},
const preferences: NotificationPreferences = {
channelPreferences,
workflowPreferences,
frequencySettings,
frequencySettings
};
const result = await notificationService.updatePreferences(user.id, preferences);
if (!result.success) {
throw new Error(result.error || 'Failed to save notification preferences');
}
logger.info('Notification preferences saved', {
action: 'save_notification_preferences',
userId: user.id
});
if (result.success) {
toast.success("Notification preferences saved successfully");
// Also update Novu subscriber profile to sync channel preferences
if (notificationService.isEnabled()) {
await notificationService.updateSubscriber({
subscriberId: user.id,
email: user.email,
handleSuccess(
'Notification preferences saved',
'Your notification settings have been updated successfully.'
);
} catch (error) {
logger.error('Error saving notification preferences', {
action: 'save_notification_preferences',
userId: user.id,
error: error instanceof Error ? error.message : String(error)
});
handleError(error, {
action: 'Save notification preferences',
userId: user.id
});
}
} else {
throw new Error(result.error || 'Failed to save preferences');
}
} catch (error: any) {
console.error('Error saving preferences:', error);
toast.error(error.message || "Failed to save notification preferences");
} finally {
setLoading(false);
setSaving(false);
}
};
@@ -143,21 +165,36 @@ export function NotificationsTab() {
const requestPushPermission = async () => {
if (!('Notification' in window)) {
toast.error("This browser doesn't support push notifications");
handleInfo(
'Push notifications not supported',
'Your browser does not support push notifications.'
);
return;
}
try {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
updateChannelPreference('push', true);
toast.success("Push notifications enabled");
handleSuccess('Push notifications enabled', 'You will now receive push notifications.');
} else {
toast.error("Push notification permission denied");
handleInfo(
'Permission denied',
'Push notifications were not enabled. You can change this in your browser settings.'
);
}
} catch (error) {
console.error('Error requesting push permission:', error);
toast.error("Failed to enable push notifications");
logger.error('Error requesting push permission', {
action: 'request_push_permission',
userId: user?.id,
error: error instanceof Error ? error.message : String(error)
});
handleError(error, {
action: 'Enable push notifications',
userId: user?.id
});
}
};
@@ -169,24 +206,38 @@ export function NotificationsTab() {
return acc;
}, {} as Record<string, NotificationTemplate[]>);
if (loading || isNovuLoading) {
return (
<div className="space-y-6">
{isNovuLoading ? (
<Card>
<CardHeader>
<CardDescription>Loading notification settings...</CardDescription>
<Skeleton className="h-6 w-48" />
<Skeleton className="h-4 w-full max-w-md" />
</CardHeader>
<CardContent className="space-y-4">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</CardContent>
</Card>
) : !isNovuEnabled ? (
</div>
);
}
return (
<div className="space-y-6">
{!isNovuEnabled && (
<Card className="border-yellow-500/50 bg-yellow-500/10">
<CardHeader>
<CardTitle className="text-yellow-600 dark:text-yellow-400">Novu Not Configured</CardTitle>
<CardTitle className="text-yellow-600 dark:text-yellow-400">
Novu Not Configured
</CardTitle>
<CardDescription>
Novu notifications are not configured. Contact an administrator to configure the Novu Application Identifier in admin settings.
Notifications are not fully configured. Contact an administrator to enable Novu integration.
</CardDescription>
</CardHeader>
</Card>
) : null}
)}
<Card>
<CardHeader>
@@ -247,7 +298,6 @@ export function NotificationsTab() {
}}
/>
</div>
</CardContent>
</Card>
@@ -263,7 +313,7 @@ export function NotificationsTab() {
<Label>Digest Frequency</Label>
<Select
value={frequencySettings.digest}
onValueChange={(value: any) =>
onValueChange={(value: 'realtime' | 'hourly' | 'daily' | 'weekly') =>
setFrequencySettings((prev) => ({ ...prev, digest: value }))
}
>
@@ -325,9 +375,11 @@ export function NotificationsTab() {
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>{template.name}</Label>
{template.description && (
<p className="text-sm text-muted-foreground">
{template.description}
</p>
)}
</div>
<Switch
checked={workflowPreferences[template.workflow_id] ?? true}
@@ -345,9 +397,9 @@ export function NotificationsTab() {
<Button
onClick={savePreferences}
className="w-full"
disabled={loading}
disabled={saving}
>
{loading ? 'Saving...' : 'Save Notification Preferences'}
{saving ? 'Saving...' : 'Save Notification Preferences'}
</Button>
</div>
);

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.');
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' };
}
try {
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
// Validate preferences
const validated = notificationPreferencesSchema.parse(preferences);
// Get previous preferences for audit log
const { data: previousPrefs } = await supabase
.from('user_notification_preferences')
.upsert({
user_id: userId,
channel_preferences: preferences.channelPreferences,
workflow_preferences: preferences.workflowPreferences,
frequency_settings: preferences.frequencySettings,
});
.select('channel_preferences, workflow_preferences, frequency_settings')
.eq('user_id', userId)
.maybeSingle();
if (error) {
console.error('Database error saving preferences (Novu disabled):', error);
throw error;
}
const novuEnabled = await this.isNovuEnabled();
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', {
// Update Novu preferences if enabled
if (novuEnabled) {
const { error: novuError } = await supabase.functions.invoke('update-novu-preferences', {
body: {
userId,
preferences,
preferences: validated,
},
});
if (error) {
console.error('Edge function error updating Novu preferences:', error);
throw error;
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 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 { 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,
const { data, error } = await supabase.functions.invoke('trigger-notification', {
body: payload
});
if (logError) {
console.error('Error inserting notification log:', logError);
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
}
};

View File

@@ -0,0 +1,78 @@
/**
* Notification Type Definitions
*
* Centralized types for notification system.
* Follows project patterns for type safety and validation.
*/
/**
* Channel preferences for receiving notifications
*/
export interface ChannelPreferences {
in_app: boolean;
email: boolean;
push: boolean;
sms: boolean;
}
/**
* Per-workflow notification preferences
*/
export interface WorkflowPreferences {
[workflowId: string]: boolean;
}
/**
* Notification frequency control settings
*/
export interface FrequencySettings {
digest: 'realtime' | 'hourly' | 'daily' | 'weekly';
max_per_hour: number;
}
/**
* Complete notification preferences structure
*/
export interface NotificationPreferences {
channelPreferences: ChannelPreferences;
workflowPreferences: WorkflowPreferences;
frequencySettings: FrequencySettings;
}
/**
* Notification template from database
*/
export interface NotificationTemplate {
id: string;
workflow_id: string;
novu_workflow_id: string | null;
name: string;
description: string | null;
category: string;
is_active: boolean;
created_at: string;
updated_at: string;
}
/**
* Subscriber data for Novu
*/
export interface SubscriberData {
subscriberId: string;
email?: string;
firstName?: string;
lastName?: string;
phone?: string;
avatar?: string;
data?: Record<string, any>;
}
/**
* Notification payload for triggering workflows
*/
export interface NotificationPayload {
workflowId: string;
subscriberId: string;
payload: Record<string, any>;
overrides?: Record<string, any>;
}