Fix: Update trigger function for Novu topics

This commit is contained in:
gpt-engineer-app[bot]
2025-10-12 18:21:07 +00:00
parent 825584d9b6
commit c482f2aa66
2 changed files with 127 additions and 63 deletions

View File

@@ -24,89 +24,74 @@ serve(async (req) => {
const supabase = createClient(supabaseUrl, supabaseServiceKey); const supabase = createClient(supabaseUrl, supabaseServiceKey);
const payload: NotificationPayload = await req.json(); const { submission_id, submission_type, submitter_name, action } = await req.json();
const { submission_id, submission_type, submitter_name, action } = payload;
console.log('Notifying moderators about submission:', { submission_id, submission_type }); console.log('Notifying moderators about submission:', { submission_id, submission_type, submitter_name, action });
// Get all moderators, admins, and superusers // Get the workflow configuration
const { data: moderators, error: moderatorsError } = await supabase const { data: workflow, error: workflowError } = await supabase
.from('user_roles') .from('notification_templates')
.select('user_id') .select('workflow_id')
.in('role', ['moderator', 'admin', 'superuser']); .eq('category', 'moderation')
.eq('is_active', true)
.single();
if (moderatorsError) { if (workflowError || !workflow) {
console.error('Error fetching moderators:', moderatorsError); console.error('Error fetching workflow:', workflowError);
throw moderatorsError;
}
if (!moderators || moderators.length === 0) {
console.log('No moderators found to notify');
return new Response( return new Response(
JSON.stringify({ success: true, count: 0, message: 'No moderators to notify' }), JSON.stringify({
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200 } success: false,
error: 'Workflow not found or not active'
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
); );
} }
console.log(`Found ${moderators.length} moderators to notify`); // Prepare notification payload
// Get the moderation-alert template
const { data: template } = await supabase
.from('notification_templates')
.select('workflow_id')
.eq('workflow_id', 'moderation-alert')
.single();
if (!template) {
console.warn('moderation-alert workflow not configured in notification_templates');
}
// Prepare notification data
const moderationUrl = `${supabaseUrl.replace('.supabase.co', '')}/admin/moderation`;
const notificationPayload = { const notificationPayload = {
itemType: submission_type, itemType: submission_type,
submissionId: submission_id,
submitterName: submitter_name, submitterName: submitter_name,
submissionId: submission_id,
action: action || 'create', action: action || 'create',
moderationUrl, moderationUrl: `https://ydvtmnrszybqnbcqbdcy.supabase.co/admin/moderation`,
}; };
// Send notifications to all moderators in parallel // Send ONE notification to the moderation-submissions topic
const notificationPromises = moderators.map(async (moderator) => { // All subscribers (moderators) will receive it automatically
try { const { data, error } = await supabase.functions.invoke('trigger-notification', {
const { error: notifyError } = await supabase.functions.invoke('trigger-notification', { body: {
body: { workflowId: workflow.workflow_id,
workflowId: 'moderation-alert', topicKey: 'moderation-submissions', // Use topic instead of individual subscribers
subscriberId: moderator.user_id, payload: notificationPayload,
payload: notificationPayload, },
},
});
if (notifyError) {
console.error(`Failed to notify moderator ${moderator.user_id}:`, notifyError);
return { success: false, userId: moderator.user_id, error: notifyError };
}
console.log(`Successfully notified moderator ${moderator.user_id}`);
return { success: true, userId: moderator.user_id };
} catch (error) {
console.error(`Exception notifying moderator ${moderator.user_id}:`, error);
return { success: false, userId: moderator.user_id, error };
}
}); });
const results = await Promise.all(notificationPromises); if (error) {
const successCount = results.filter(r => r.success).length; console.error('Failed to notify moderators via topic:', error);
const failCount = results.filter(r => !r.success).length; return new Response(
JSON.stringify({
success: false,
error: 'Failed to send notification to topic',
details: error.message
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
);
}
console.log(`Notification summary: ${successCount} sent, ${failCount} failed`); console.log('Successfully notified all moderators via topic:', data);
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
success: true, success: true,
count: successCount, message: 'Moderator notifications sent via topic',
failed: failCount, topicKey: 'moderation-submissions',
details: results, transactionId: data?.transactionId,
}), }),
{ {
headers: { ...corsHeaders, 'Content-Type': 'application/json' }, headers: { ...corsHeaders, 'Content-Type': 'application/json' },

View File

@@ -0,0 +1,79 @@
-- Create function to sync moderator role changes to Novu topics
CREATE OR REPLACE FUNCTION public.sync_moderator_novu_topic()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
function_url text;
anon_key text;
action_type text;
BEGIN
-- Only process moderator, admin, and superuser roles
IF (TG_OP = 'INSERT' AND NEW.role IN ('moderator', 'admin', 'superuser')) OR
(TG_OP = 'DELETE' AND OLD.role IN ('moderator', 'admin', 'superuser')) THEN
-- Build the function URL
function_url := 'https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/manage-moderator-topic';
-- Use the public anon key
anon_key := 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4';
-- Determine action type
action_type := CASE
WHEN TG_OP = 'INSERT' THEN 'add'
WHEN TG_OP = 'DELETE' THEN 'remove'
END;
-- Call edge function asynchronously to add/remove from Novu topics
PERFORM net.http_post(
url := function_url,
headers := jsonb_build_object(
'Content-Type', 'application/json',
'Authorization', 'Bearer ' || anon_key,
'apikey', anon_key
),
body := jsonb_build_object(
'userId', CASE WHEN TG_OP = 'INSERT' THEN NEW.user_id ELSE OLD.user_id END,
'action', action_type
)
);
RAISE LOG 'Triggered Novu topic sync for user % with action %',
CASE WHEN TG_OP = 'INSERT' THEN NEW.user_id ELSE OLD.user_id END,
action_type;
END IF;
RETURN COALESCE(NEW, OLD);
EXCEPTION
WHEN OTHERS THEN
-- Log error but don't fail the role change
RAISE WARNING 'Failed to sync moderator to Novu topic: %', SQLERRM;
RETURN COALESCE(NEW, OLD);
END;
$$;
-- Create trigger for role insertions
DROP TRIGGER IF EXISTS sync_moderator_novu_topic_on_insert ON public.user_roles;
CREATE TRIGGER sync_moderator_novu_topic_on_insert
AFTER INSERT ON public.user_roles
FOR EACH ROW
EXECUTE FUNCTION public.sync_moderator_novu_topic();
-- Create trigger for role deletions
DROP TRIGGER IF EXISTS sync_moderator_novu_topic_on_delete ON public.user_roles;
CREATE TRIGGER sync_moderator_novu_topic_on_delete
AFTER DELETE ON public.user_roles
FOR EACH ROW
EXECUTE FUNCTION public.sync_moderator_novu_topic();
-- Add comments
COMMENT ON FUNCTION public.sync_moderator_novu_topic() IS
'Automatically adds or removes users from Novu moderation topics when moderator-level roles are granted or revoked';
COMMENT ON TRIGGER sync_moderator_novu_topic_on_insert ON public.user_roles IS
'Adds users to Novu moderation topics when they receive moderator, admin, or superuser roles';
COMMENT ON TRIGGER sync_moderator_novu_topic_on_delete ON public.user_roles IS
'Removes users from Novu moderation topics when their moderator, admin, or superuser roles are revoked';