mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 07:31:12 -05:00
feat: Implement moderator notifications
This commit is contained in:
130
supabase/functions/notify-moderators-submission/index.ts
Normal file
130
supabase/functions/notify-moderators-submission/index.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
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',
|
||||
};
|
||||
|
||||
interface NotificationPayload {
|
||||
submission_id: string;
|
||||
submission_type: string;
|
||||
submitter_name: string;
|
||||
action: string;
|
||||
}
|
||||
|
||||
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 payload: NotificationPayload = await req.json();
|
||||
const { submission_id, submission_type, submitter_name, action } = payload;
|
||||
|
||||
console.log('Notifying moderators about submission:', { submission_id, submission_type });
|
||||
|
||||
// Get all moderators, admins, and superusers
|
||||
const { data: moderators, error: moderatorsError } = await supabase
|
||||
.from('user_roles')
|
||||
.select('user_id')
|
||||
.in('role', ['moderator', 'admin', 'superuser']);
|
||||
|
||||
if (moderatorsError) {
|
||||
console.error('Error fetching moderators:', moderatorsError);
|
||||
throw moderatorsError;
|
||||
}
|
||||
|
||||
if (!moderators || moderators.length === 0) {
|
||||
console.log('No moderators found to notify');
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, count: 0, message: 'No moderators to notify' }),
|
||||
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
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`;
|
||||
const notificationPayload = {
|
||||
itemType: submission_type,
|
||||
submissionId: submission_id,
|
||||
submitterName: submitter_name,
|
||||
action: action || 'create',
|
||||
moderationUrl,
|
||||
};
|
||||
|
||||
// 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 };
|
||||
}
|
||||
});
|
||||
|
||||
const results = await Promise.all(notificationPromises);
|
||||
const successCount = results.filter(r => r.success).length;
|
||||
const failCount = results.filter(r => !r.success).length;
|
||||
|
||||
console.log(`Notification summary: ${successCount} sent, ${failCount} failed`);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
count: successCount,
|
||||
failed: failCount,
|
||||
details: results,
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error('Error in notify-moderators-submission:', error);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error.message,
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user