feat: Implement Novu notification system

This commit is contained in:
gpt-engineer-app[bot]
2025-10-01 12:26:12 +00:00
parent cae084964e
commit e2f0df22cc
13 changed files with 1407 additions and 253 deletions

View File

@@ -0,0 +1,64 @@
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { Novu } from "npm:@novu/node@2.0.2";
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
try {
const novuApiKey = Deno.env.get('NOVU_API_KEY');
if (!novuApiKey) {
throw new Error('NOVU_API_KEY is not configured');
}
const novu = new Novu(novuApiKey, {
backendUrl: Deno.env.get('VITE_NOVU_API_URL') || 'https://api.novu.co',
});
const { subscriberId, email, firstName, lastName, phone, avatar, data } = await req.json();
console.log('Creating Novu subscriber:', { subscriberId, email });
const subscriber = await novu.subscribers.identify(subscriberId, {
email,
firstName,
lastName,
phone,
avatar,
data,
});
console.log('Subscriber created successfully:', subscriber.data);
return new Response(
JSON.stringify({
success: true,
subscriberId: subscriber.data._id,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error: any) {
console.error('Error creating Novu subscriber:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
);
}
});

View File

@@ -0,0 +1,106 @@
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
try {
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);
const event = await req.json();
console.log('Received Novu webhook event:', event.type);
// Handle different webhook events
switch (event.type) {
case 'notification.sent':
await handleNotificationSent(supabase, event);
break;
case 'notification.delivered':
await handleNotificationDelivered(supabase, event);
break;
case 'notification.read':
await handleNotificationRead(supabase, event);
break;
case 'notification.failed':
await handleNotificationFailed(supabase, event);
break;
default:
console.log('Unhandled event type:', event.type);
}
return new Response(
JSON.stringify({ success: true }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error: any) {
console.error('Error processing webhook:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
);
}
});
async function handleNotificationSent(supabase: any, event: any) {
const { transactionId, channel } = event.data;
await supabase
.from('notification_logs')
.update({ status: 'sent' })
.eq('novu_transaction_id', transactionId);
}
async function handleNotificationDelivered(supabase: any, event: any) {
const { transactionId } = event.data;
await supabase
.from('notification_logs')
.update({
status: 'delivered',
delivered_at: new Date().toISOString(),
})
.eq('novu_transaction_id', transactionId);
}
async function handleNotificationRead(supabase: any, event: any) {
const { transactionId } = event.data;
await supabase
.from('notification_logs')
.update({
read_at: new Date().toISOString(),
})
.eq('novu_transaction_id', transactionId);
}
async function handleNotificationFailed(supabase: any, event: any) {
const { transactionId, error } = event.data;
await supabase
.from('notification_logs')
.update({
status: 'failed',
error_message: error,
})
.eq('novu_transaction_id', transactionId);
}

View File

@@ -0,0 +1,63 @@
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { Novu } from "npm:@novu/node@2.0.2";
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
try {
const novuApiKey = Deno.env.get('NOVU_API_KEY');
if (!novuApiKey) {
throw new Error('NOVU_API_KEY is not configured');
}
const novu = new Novu(novuApiKey, {
backendUrl: Deno.env.get('VITE_NOVU_API_URL') || 'https://api.novu.co',
});
const { workflowId, subscriberId, payload, overrides } = await req.json();
console.log('Triggering notification:', { workflowId, subscriberId });
const result = await novu.trigger(workflowId, {
to: {
subscriberId,
},
payload,
overrides,
});
console.log('Notification triggered successfully:', result.data);
return new Response(
JSON.stringify({
success: true,
transactionId: result.data.transactionId,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error: any) {
console.error('Error triggering notification:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
);
}
});

View File

@@ -0,0 +1,88 @@
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { Novu } from "npm:@novu/node@2.0.2";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
try {
const novuApiKey = Deno.env.get('NOVU_API_KEY');
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
if (!novuApiKey) {
throw new Error('NOVU_API_KEY is not configured');
}
const novu = new Novu(novuApiKey, {
backendUrl: Deno.env.get('VITE_NOVU_API_URL') || 'https://api.novu.co',
});
const supabase = createClient(supabaseUrl, supabaseServiceKey);
const { userId, preferences } = await req.json();
console.log('Updating preferences for user:', userId);
// Get Novu subscriber ID from database
const { data: prefData, error: prefError } = await supabase
.from('user_notification_preferences')
.select('novu_subscriber_id')
.eq('user_id', userId)
.single();
if (prefError || !prefData?.novu_subscriber_id) {
throw new Error('Novu subscriber not found');
}
const subscriberId = prefData.novu_subscriber_id;
// Update channel preferences in Novu
const channelPrefs = preferences.channelPreferences;
await novu.subscribers.updatePreference(
subscriberId,
{
enabled: true,
channels: {
email: channelPrefs.email,
sms: channelPrefs.sms,
in_app: channelPrefs.in_app,
push: channelPrefs.push,
},
}
);
console.log('Preferences updated successfully');
return new Response(
JSON.stringify({
success: true,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error: any) {
console.error('Error updating Novu preferences:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
);
}
});