mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 12:11:17 -05:00
Fix: Update trigger function for Novu topics
This commit is contained in:
@@ -24,89 +24,74 @@ serve(async (req) => {
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||
|
||||
const payload: NotificationPayload = await req.json();
|
||||
const { submission_id, submission_type, submitter_name, action } = payload;
|
||||
const { submission_id, submission_type, submitter_name, action } = await req.json();
|
||||
|
||||
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
|
||||
const { data: moderators, error: moderatorsError } = await supabase
|
||||
.from('user_roles')
|
||||
.select('user_id')
|
||||
.in('role', ['moderator', 'admin', 'superuser']);
|
||||
// Get the workflow configuration
|
||||
const { data: workflow, error: workflowError } = await supabase
|
||||
.from('notification_templates')
|
||||
.select('workflow_id')
|
||||
.eq('category', 'moderation')
|
||||
.eq('is_active', true)
|
||||
.single();
|
||||
|
||||
if (moderatorsError) {
|
||||
console.error('Error fetching moderators:', moderatorsError);
|
||||
throw moderatorsError;
|
||||
}
|
||||
|
||||
if (!moderators || moderators.length === 0) {
|
||||
console.log('No moderators found to notify');
|
||||
if (workflowError || !workflow) {
|
||||
console.error('Error fetching workflow:', workflowError);
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, count: 0, message: 'No moderators to notify' }),
|
||||
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200 }
|
||||
JSON.stringify({
|
||||
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`);
|
||||
|
||||
// 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`;
|
||||
// Prepare notification payload
|
||||
const notificationPayload = {
|
||||
itemType: submission_type,
|
||||
submissionId: submission_id,
|
||||
submitterName: submitter_name,
|
||||
submissionId: submission_id,
|
||||
action: action || 'create',
|
||||
moderationUrl,
|
||||
moderationUrl: `https://ydvtmnrszybqnbcqbdcy.supabase.co/admin/moderation`,
|
||||
};
|
||||
|
||||
// Send notifications to all moderators in parallel
|
||||
const notificationPromises = moderators.map(async (moderator) => {
|
||||
try {
|
||||
const { error: notifyError } = await supabase.functions.invoke('trigger-notification', {
|
||||
body: {
|
||||
workflowId: 'moderation-alert',
|
||||
subscriberId: moderator.user_id,
|
||||
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 };
|
||||
}
|
||||
// Send ONE notification to the moderation-submissions topic
|
||||
// All subscribers (moderators) will receive it automatically
|
||||
const { data, error } = await supabase.functions.invoke('trigger-notification', {
|
||||
body: {
|
||||
workflowId: workflow.workflow_id,
|
||||
topicKey: 'moderation-submissions', // Use topic instead of individual subscribers
|
||||
payload: notificationPayload,
|
||||
},
|
||||
});
|
||||
|
||||
const results = await Promise.all(notificationPromises);
|
||||
const successCount = results.filter(r => r.success).length;
|
||||
const failCount = results.filter(r => !r.success).length;
|
||||
if (error) {
|
||||
console.error('Failed to notify moderators via topic:', error);
|
||||
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(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
count: successCount,
|
||||
failed: failCount,
|
||||
details: results,
|
||||
message: 'Moderator notifications sent via topic',
|
||||
topicKey: 'moderation-submissions',
|
||||
transactionId: data?.transactionId,
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
|
||||
Reference in New Issue
Block a user