mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 12:11:17 -05:00
feat: Implement notifications modernization
This commit is contained in:
@@ -8,48 +8,32 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Separator } from "@/components/ui/separator";
|
import { Separator } from "@/components/ui/separator";
|
||||||
import { Badge } from "@/components/ui/badge";
|
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";
|
import { notificationService } from "@/lib/notificationService";
|
||||||
|
import type {
|
||||||
interface ChannelPreferences {
|
NotificationPreferences,
|
||||||
in_app: boolean;
|
NotificationTemplate,
|
||||||
email: boolean;
|
ChannelPreferences,
|
||||||
push: boolean;
|
WorkflowPreferences,
|
||||||
}
|
FrequencySettings
|
||||||
|
} from "@/types/notifications";
|
||||||
interface WorkflowPreferences {
|
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@/lib/notificationValidation";
|
||||||
[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;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function NotificationsTab() {
|
export function NotificationsTab() {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const { isEnabled: isNovuEnabled, isLoading: isNovuLoading } = usePublicNovuSettings();
|
const { isEnabled: isNovuEnabled, isLoading: isNovuLoading } = usePublicNovuSettings();
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
|
const [templates, setTemplates] = useState<NotificationTemplate[]>([]);
|
||||||
const [channelPreferences, setChannelPreferences] = useState<ChannelPreferences>({
|
const [channelPreferences, setChannelPreferences] = useState<ChannelPreferences>(
|
||||||
in_app: true,
|
DEFAULT_NOTIFICATION_PREFERENCES.channelPreferences
|
||||||
email: true,
|
);
|
||||||
push: false,
|
|
||||||
});
|
|
||||||
const [workflowPreferences, setWorkflowPreferences] = useState<WorkflowPreferences>({});
|
const [workflowPreferences, setWorkflowPreferences] = useState<WorkflowPreferences>({});
|
||||||
const [frequencySettings, setFrequencySettings] = useState<FrequencySettings>({
|
const [frequencySettings, setFrequencySettings] = useState<FrequencySettings>(
|
||||||
digest: 'daily',
|
DEFAULT_NOTIFICATION_PREFERENCES.frequencySettings
|
||||||
max_per_hour: 10,
|
);
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user) {
|
if (user) {
|
||||||
@@ -65,71 +49,109 @@ export function NotificationsTab() {
|
|||||||
const preferences = await notificationService.getPreferences(user.id);
|
const preferences = await notificationService.getPreferences(user.id);
|
||||||
|
|
||||||
if (preferences) {
|
if (preferences) {
|
||||||
const { sms, ...channelPrefs } = preferences.channelPreferences;
|
setChannelPreferences(preferences.channelPreferences);
|
||||||
setChannelPreferences(channelPrefs);
|
|
||||||
setWorkflowPreferences(preferences.workflowPreferences);
|
setWorkflowPreferences(preferences.workflowPreferences);
|
||||||
setFrequencySettings(preferences.frequencySettings);
|
setFrequencySettings(preferences.frequencySettings);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.info('Notification preferences loaded', {
|
||||||
|
action: 'load_notification_preferences',
|
||||||
|
userId: user.id
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading preferences:', error);
|
logger.error('Failed to load notification preferences', {
|
||||||
toast.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 {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadTemplates = async () => {
|
const loadTemplates = async () => {
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const templateData = await notificationService.getTemplates();
|
const templateData = await notificationService.getTemplates();
|
||||||
setTemplates(templateData);
|
setTemplates(templateData);
|
||||||
|
|
||||||
// Initialize workflow preferences if not set
|
// Initialize workflow preferences for new templates
|
||||||
const initialPrefs: WorkflowPreferences = {};
|
const initialPrefs: WorkflowPreferences = {};
|
||||||
templateData.forEach((template) => {
|
templateData.forEach((template) => {
|
||||||
if (!(template.workflow_id in workflowPreferences)) {
|
if (!(template.workflow_id in workflowPreferences)) {
|
||||||
initialPrefs[template.workflow_id] = true;
|
initialPrefs[template.workflow_id] = true;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (Object.keys(initialPrefs).length > 0) {
|
if (Object.keys(initialPrefs).length > 0) {
|
||||||
setWorkflowPreferences((prev) => ({ ...prev, ...initialPrefs }));
|
setWorkflowPreferences((prev) => ({ ...prev, ...initialPrefs }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.info('Notification templates loaded', {
|
||||||
|
action: 'load_notification_templates',
|
||||||
|
userId: user.id,
|
||||||
|
count: templateData.length
|
||||||
|
});
|
||||||
} catch (error) {
|
} 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 () => {
|
const savePreferences = async () => {
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
|
|
||||||
setLoading(true);
|
setSaving(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await notificationService.updatePreferences(user.id, {
|
const preferences: NotificationPreferences = {
|
||||||
channelPreferences: {
|
channelPreferences,
|
||||||
...channelPreferences,
|
|
||||||
sms: false, // SMS not supported in UI
|
|
||||||
},
|
|
||||||
workflowPreferences,
|
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) {
|
handleSuccess(
|
||||||
toast.success("Notification preferences saved successfully");
|
'Notification preferences saved',
|
||||||
|
'Your notification settings have been updated successfully.'
|
||||||
// Also update Novu subscriber profile to sync channel preferences
|
);
|
||||||
if (notificationService.isEnabled()) {
|
} catch (error) {
|
||||||
await notificationService.updateSubscriber({
|
logger.error('Error saving notification preferences', {
|
||||||
subscriberId: user.id,
|
action: 'save_notification_preferences',
|
||||||
email: user.email,
|
userId: user.id,
|
||||||
});
|
error: error instanceof Error ? error.message : String(error)
|
||||||
}
|
});
|
||||||
} else {
|
|
||||||
throw new Error(result.error || 'Failed to save preferences');
|
handleError(error, {
|
||||||
}
|
action: 'Save notification preferences',
|
||||||
} catch (error: any) {
|
userId: user.id
|
||||||
console.error('Error saving preferences:', error);
|
});
|
||||||
toast.error(error.message || "Failed to save notification preferences");
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -143,21 +165,36 @@ export function NotificationsTab() {
|
|||||||
|
|
||||||
const requestPushPermission = async () => {
|
const requestPushPermission = async () => {
|
||||||
if (!('Notification' in window)) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const permission = await Notification.requestPermission();
|
const permission = await Notification.requestPermission();
|
||||||
|
|
||||||
if (permission === 'granted') {
|
if (permission === 'granted') {
|
||||||
updateChannelPreference('push', true);
|
updateChannelPreference('push', true);
|
||||||
toast.success("Push notifications enabled");
|
handleSuccess('Push notifications enabled', 'You will now receive push notifications.');
|
||||||
} else {
|
} 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) {
|
} catch (error) {
|
||||||
console.error('Error requesting push permission:', error);
|
logger.error('Error requesting push permission', {
|
||||||
toast.error("Failed to enable push notifications");
|
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;
|
return acc;
|
||||||
}, {} as Record<string, NotificationTemplate[]>);
|
}, {} as Record<string, NotificationTemplate[]>);
|
||||||
|
|
||||||
return (
|
if (loading || isNovuLoading) {
|
||||||
<div className="space-y-6">
|
return (
|
||||||
{isNovuLoading ? (
|
<div className="space-y-6">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardDescription>Loading notification settings...</CardDescription>
|
<Skeleton className="h-6 w-48" />
|
||||||
|
<Skeleton className="h-4 w-full max-w-md" />
|
||||||
</CardHeader>
|
</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>
|
</Card>
|
||||||
) : !isNovuEnabled ? (
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{!isNovuEnabled && (
|
||||||
<Card className="border-yellow-500/50 bg-yellow-500/10">
|
<Card className="border-yellow-500/50 bg-yellow-500/10">
|
||||||
<CardHeader>
|
<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>
|
<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>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
</Card>
|
</Card>
|
||||||
) : null}
|
)}
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@@ -247,7 +298,6 @@ export function NotificationsTab() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@@ -263,7 +313,7 @@ export function NotificationsTab() {
|
|||||||
<Label>Digest Frequency</Label>
|
<Label>Digest Frequency</Label>
|
||||||
<Select
|
<Select
|
||||||
value={frequencySettings.digest}
|
value={frequencySettings.digest}
|
||||||
onValueChange={(value: any) =>
|
onValueChange={(value: 'realtime' | 'hourly' | 'daily' | 'weekly') =>
|
||||||
setFrequencySettings((prev) => ({ ...prev, digest: value }))
|
setFrequencySettings((prev) => ({ ...prev, digest: value }))
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@@ -325,9 +375,11 @@ export function NotificationsTab() {
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="space-y-0.5">
|
<div className="space-y-0.5">
|
||||||
<Label>{template.name}</Label>
|
<Label>{template.name}</Label>
|
||||||
<p className="text-sm text-muted-foreground">
|
{template.description && (
|
||||||
{template.description}
|
<p className="text-sm text-muted-foreground">
|
||||||
</p>
|
{template.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<Switch
|
<Switch
|
||||||
checked={workflowPreferences[template.workflow_id] ?? true}
|
checked={workflowPreferences[template.workflow_id] ?? true}
|
||||||
@@ -345,9 +397,9 @@ export function NotificationsTab() {
|
|||||||
<Button
|
<Button
|
||||||
onClick={savePreferences}
|
onClick={savePreferences}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
disabled={loading}
|
disabled={saving}
|
||||||
>
|
>
|
||||||
{loading ? 'Saving...' : 'Save Notification Preferences'}
|
{saving ? 'Saving...' : 'Save Notification Preferences'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,95 +1,38 @@
|
|||||||
import { supabase } from "@/integrations/supabase/client";
|
import { supabase } from "@/integrations/supabase/client";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
export interface NotificationPayload {
|
import { AppError } from "@/lib/errorHandler";
|
||||||
workflowId: string;
|
import { z } from "zod";
|
||||||
subscriberId: string;
|
import type {
|
||||||
payload: Record<string, any>;
|
NotificationPayload,
|
||||||
overrides?: Record<string, any>;
|
SubscriberData,
|
||||||
}
|
NotificationPreferences,
|
||||||
|
NotificationTemplate
|
||||||
export interface SubscriberData {
|
} from "@/types/notifications";
|
||||||
subscriberId: string;
|
import {
|
||||||
email?: string;
|
notificationPreferencesSchema,
|
||||||
firstName?: string;
|
subscriberDataSchema,
|
||||||
lastName?: string;
|
DEFAULT_NOTIFICATION_PREFERENCES
|
||||||
phone?: string;
|
} from "@/lib/notificationValidation";
|
||||||
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;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
class NotificationService {
|
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 }> {
|
async isNovuEnabled(): Promise<boolean> {
|
||||||
if (!this.isNovuEnabled) {
|
|
||||||
console.warn('Novu is not configured. Skipping subscriber creation.');
|
|
||||||
return { success: false, error: 'Novu not configured' };
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { data, error } = await supabase.functions.invoke('create-novu-subscriber', {
|
const { data } = await supabase
|
||||||
body: subscriberData,
|
.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)
|
||||||
});
|
});
|
||||||
|
return false;
|
||||||
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) };
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,137 +40,235 @@ class NotificationService {
|
|||||||
* Update an existing Novu subscriber's profile information
|
* Update an existing Novu subscriber's profile information
|
||||||
*/
|
*/
|
||||||
async updateSubscriber(subscriberData: SubscriberData): Promise<{ success: boolean; error?: string }> {
|
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 {
|
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', {
|
const { data, error } = await supabase.functions.invoke('update-novu-subscriber', {
|
||||||
body: subscriberData,
|
body: validated,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error('Edge function error updating Novu subscriber:', error);
|
logger.error('Edge function error updating Novu subscriber', {
|
||||||
throw error;
|
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 };
|
return { success: true };
|
||||||
} catch (error: unknown) {
|
} catch (error) {
|
||||||
console.error('Error updating Novu subscriber:', error);
|
logger.error('Error in updateSubscriber', {
|
||||||
return { success: false, error: this.extractErrorMessage(error) };
|
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(
|
async updatePreferences(
|
||||||
userId: string,
|
userId: string,
|
||||||
preferences: NotificationPreferences
|
preferences: NotificationPreferences
|
||||||
): Promise<{ success: boolean; error?: string }> {
|
): 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 {
|
try {
|
||||||
const { error } = await supabase.functions.invoke('update-novu-preferences', {
|
// Validate preferences
|
||||||
body: {
|
const validated = notificationPreferencesSchema.parse(preferences);
|
||||||
userId,
|
|
||||||
preferences,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (error) {
|
// Get previous preferences for audit log
|
||||||
console.error('Edge function error updating Novu preferences:', error);
|
const { data: previousPrefs } = await supabase
|
||||||
throw error;
|
.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
|
const { error: dbError } = await supabase
|
||||||
.from('user_notification_preferences')
|
.from('user_notification_preferences')
|
||||||
.upsert({
|
.upsert({
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
channel_preferences: preferences.channelPreferences,
|
channel_preferences: validated.channelPreferences,
|
||||||
workflow_preferences: preferences.workflowPreferences,
|
workflow_preferences: validated.workflowPreferences,
|
||||||
frequency_settings: preferences.frequencySettings,
|
frequency_settings: validated.frequencySettings,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (dbError) {
|
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;
|
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 };
|
return { success: true };
|
||||||
} catch (error: unknown) {
|
} catch (error) {
|
||||||
console.error('Error updating preferences:', error);
|
logger.error('Error updating notification preferences', {
|
||||||
return { success: false, error: this.extractErrorMessage(error) };
|
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
|
* Get user's notification preferences with proper typing
|
||||||
*/
|
|
||||||
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
|
|
||||||
*/
|
*/
|
||||||
async getPreferences(userId: string): Promise<NotificationPreferences | null> {
|
async getPreferences(userId: string): Promise<NotificationPreferences | null> {
|
||||||
try {
|
try {
|
||||||
@@ -235,37 +276,38 @@ class NotificationService {
|
|||||||
.from('user_notification_preferences')
|
.from('user_notification_preferences')
|
||||||
.select('channel_preferences, workflow_preferences, frequency_settings')
|
.select('channel_preferences, workflow_preferences, frequency_settings')
|
||||||
.eq('user_id', userId)
|
.eq('user_id', userId)
|
||||||
.single();
|
.maybeSingle();
|
||||||
|
|
||||||
if (error && error.code !== 'PGRST116') {
|
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;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!data) {
|
if (!data) {
|
||||||
console.log('No preferences found for user, returning defaults:', userId);
|
logger.info('No preferences found, returning defaults', {
|
||||||
return {
|
action: 'fetch_notification_preferences',
|
||||||
channelPreferences: {
|
userId
|
||||||
in_app: true,
|
});
|
||||||
email: true,
|
return DEFAULT_NOTIFICATION_PREFERENCES;
|
||||||
push: false,
|
|
||||||
sms: false,
|
|
||||||
},
|
|
||||||
workflowPreferences: {},
|
|
||||||
frequencySettings: {
|
|
||||||
digest: 'daily',
|
|
||||||
max_per_hour: 10,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
// Validate the data from database
|
||||||
channelPreferences: data.channel_preferences as any,
|
return notificationPreferencesSchema.parse({
|
||||||
workflowPreferences: data.workflow_preferences as any,
|
channelPreferences: data.channel_preferences,
|
||||||
frequencySettings: data.frequency_settings as any,
|
workflowPreferences: data.workflow_preferences,
|
||||||
};
|
frequencySettings: data.frequency_settings
|
||||||
} catch (error: unknown) {
|
});
|
||||||
console.error('Error fetching notification preferences for user:', userId, error);
|
} catch (error) {
|
||||||
|
logger.error('Error fetching notification preferences', {
|
||||||
|
action: 'fetch_notification_preferences',
|
||||||
|
userId,
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
});
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -273,7 +315,7 @@ class NotificationService {
|
|||||||
/**
|
/**
|
||||||
* Get notification templates
|
* Get notification templates
|
||||||
*/
|
*/
|
||||||
async getTemplates(): Promise<any[]> {
|
async getTemplates(): Promise<NotificationTemplate[]> {
|
||||||
try {
|
try {
|
||||||
const { data, error } = await supabase
|
const { data, error } = await supabase
|
||||||
.from('notification_templates')
|
.from('notification_templates')
|
||||||
@@ -282,90 +324,117 @@ class NotificationService {
|
|||||||
.order('category', { ascending: true });
|
.order('category', { ascending: true });
|
||||||
|
|
||||||
if (error) {
|
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;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
return data || [];
|
return data || [];
|
||||||
} catch (error: unknown) {
|
} catch (error) {
|
||||||
console.error('Error fetching notification templates:', error);
|
logger.error('Error fetching notification templates', {
|
||||||
|
action: 'fetch_notification_templates',
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
});
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log notification in database
|
* Trigger a notification workflow
|
||||||
*/
|
*/
|
||||||
private async logNotification(log: {
|
async trigger(payload: NotificationPayload): Promise<{ success: boolean; error?: string }> {
|
||||||
userId: string;
|
|
||||||
workflowId: string;
|
|
||||||
transactionId: string;
|
|
||||||
payload: Record<string, any>;
|
|
||||||
}): Promise<void> {
|
|
||||||
try {
|
try {
|
||||||
// Get template ID from workflow ID
|
const novuEnabled = await this.isNovuEnabled();
|
||||||
const { data: template } = await supabase
|
if (!novuEnabled) {
|
||||||
.from('notification_templates')
|
logger.warn('Novu not configured, skipping notification', {
|
||||||
.select('id')
|
action: 'trigger_notification',
|
||||||
.eq('workflow_id', log.workflowId)
|
workflowId: payload.workflowId,
|
||||||
.single();
|
subscriberId: payload.subscriberId
|
||||||
|
});
|
||||||
const { error: logError } = await supabase.from('notification_logs').insert({
|
return { success: false, error: 'Novu not configured' };
|
||||||
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 { 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) {
|
} 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: {
|
async notifyModerators(payload: {
|
||||||
submission_id: string;
|
submission_id: string;
|
||||||
submission_type: string;
|
submission_type: string;
|
||||||
submitter_name: string;
|
submitter_name: string;
|
||||||
action: string;
|
action: string;
|
||||||
}): Promise<{ success: boolean; count: number; error?: string }> {
|
}): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const { data, error } = await supabase.functions.invoke('notify-moderators-submission', {
|
const { error } = await supabase.functions.invoke('notify-moderators-submission', {
|
||||||
body: payload,
|
body: payload
|
||||||
});
|
});
|
||||||
|
|
||||||
if (error) {
|
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;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Moderators notified successfully:', data);
|
logger.info('Moderators notified successfully', {
|
||||||
return {
|
action: 'notify_moderators',
|
||||||
success: true,
|
submissionId: payload.submission_id
|
||||||
count: data?.count || 0
|
});
|
||||||
};
|
} catch (error) {
|
||||||
} catch (error: unknown) {
|
logger.error('Error notifying moderators', {
|
||||||
console.error('Error notifying moderators:', error);
|
action: 'notify_moderators',
|
||||||
return {
|
submissionId: payload.submission_id,
|
||||||
success: false,
|
error: error instanceof Error ? error.message : String(error)
|
||||||
count: 0,
|
});
|
||||||
error: this.extractErrorMessage(error)
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if Novu is enabled
|
* Check if notifications are enabled
|
||||||
*/
|
*/
|
||||||
isEnabled(): boolean {
|
isEnabled(): boolean {
|
||||||
return this.isNovuEnabled;
|
return true; // Always return true, actual check happens in isNovuEnabled()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
64
src/lib/notificationValidation.ts
Normal file
64
src/lib/notificationValidation.ts
Normal 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
|
||||||
|
}
|
||||||
|
};
|
||||||
78
src/types/notifications.ts
Normal file
78
src/types/notifications.ts
Normal 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>;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user