mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 15:51:12 -05:00
Migrate Phase 2 admin edges
Migrate five admin/moderator edge functions (merge-contact-tickets, send-escalation-notification, notify-moderators-report, notify-moderators-submission, send-password-added-email) to use createEdgeFunction wrapper. Remove manual CORS, auth, service-client setup, logging, and error handling. Implement handler with EdgeFunctionContext, apply appropriate wrapper config (requireAuth, requiredRoles/useServiceRole, corsEnabled, enableTracing, rateLimitTier). Replace edgeLogger with span events, maintain core business logic and retry/email integration patterns.
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
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';
|
||||
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
||||
import { createErrorResponse, sanitizeError } from '../_shared/errorSanitizer.ts';
|
||||
import { addSpanEvent } from '../_shared/logger.ts';
|
||||
|
||||
interface MergeTicketsRequest {
|
||||
primaryTicketId: string;
|
||||
@@ -18,56 +17,7 @@ interface MergeTicketsResponse {
|
||||
deletedTickets: string[];
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const authHeader = req.headers.get('Authorization');
|
||||
if (!authHeader) {
|
||||
throw new Error('Missing authorization header');
|
||||
}
|
||||
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
||||
{ global: { headers: { Authorization: authHeader } } }
|
||||
);
|
||||
|
||||
// Authenticate user
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser();
|
||||
if (authError || !user) {
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
edgeLogger.info('Merge tickets request started', {
|
||||
requestId: tracking.requestId,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
// Check if user has moderator/admin role
|
||||
const { data: hasRole, error: roleError } = await supabase.rpc('has_role', {
|
||||
_user_id: user.id,
|
||||
_role: 'moderator'
|
||||
});
|
||||
|
||||
const { data: isAdmin, error: adminError } = await supabase.rpc('has_role', {
|
||||
_user_id: user.id,
|
||||
_role: 'admin'
|
||||
});
|
||||
|
||||
const { data: isSuperuser, error: superuserError } = await supabase.rpc('has_role', {
|
||||
_user_id: user.id,
|
||||
_role: 'superuser'
|
||||
});
|
||||
|
||||
if (roleError || adminError || superuserError || (!hasRole && !isAdmin && !isSuperuser)) {
|
||||
throw new Error('Insufficient permissions. Moderator role required.');
|
||||
}
|
||||
|
||||
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||
// Parse request body
|
||||
const { primaryTicketId, mergeTicketIds, mergeReason }: MergeTicketsRequest = await req.json();
|
||||
|
||||
@@ -84,6 +34,11 @@ serve(async (req) => {
|
||||
throw new Error('Maximum 10 tickets can be merged at once');
|
||||
}
|
||||
|
||||
addSpanEvent(span, 'merge_tickets_started', {
|
||||
primaryTicketId,
|
||||
mergeCount: mergeTicketIds.length
|
||||
});
|
||||
|
||||
// Start transaction-like operations
|
||||
const allTicketIds = [primaryTicketId, ...mergeTicketIds];
|
||||
|
||||
@@ -105,7 +60,7 @@ serve(async (req) => {
|
||||
throw new Error('Primary ticket not found');
|
||||
}
|
||||
|
||||
// Check if any ticket already has merged_ticket_numbers (prevent re-merging)
|
||||
// Check if any ticket already has merged_ticket_numbers
|
||||
const alreadyMerged = tickets.find(t =>
|
||||
t.merged_ticket_numbers && t.merged_ticket_numbers.length > 0
|
||||
);
|
||||
@@ -113,15 +68,13 @@ serve(async (req) => {
|
||||
throw new Error(`Ticket ${alreadyMerged.ticket_number} has already been used in a merge`);
|
||||
}
|
||||
|
||||
edgeLogger.info('Starting merge process', {
|
||||
requestId: tracking.requestId,
|
||||
addSpanEvent(span, 'tickets_validated', {
|
||||
primaryTicket: primaryTicket.ticket_number,
|
||||
mergeTicketCount: mergeTickets.length,
|
||||
mergeTicketCount: mergeTickets.length
|
||||
});
|
||||
|
||||
// Step 1: Move all email threads to primary ticket
|
||||
edgeLogger.info('Step 1: Moving email threads', {
|
||||
requestId: tracking.requestId,
|
||||
addSpanEvent(span, 'moving_email_threads', {
|
||||
fromTickets: mergeTickets.map(t => t.ticket_number)
|
||||
});
|
||||
|
||||
@@ -135,21 +88,13 @@ serve(async (req) => {
|
||||
|
||||
const threadsMovedCount = movedThreads?.length || 0;
|
||||
|
||||
edgeLogger.info('Threads moved successfully', {
|
||||
requestId: tracking.requestId,
|
||||
threadsMovedCount
|
||||
});
|
||||
addSpanEvent(span, 'threads_moved', { threadsMovedCount });
|
||||
|
||||
if (threadsMovedCount === 0) {
|
||||
edgeLogger.warn('No email threads found to move', {
|
||||
requestId: tracking.requestId,
|
||||
mergeTicketIds
|
||||
});
|
||||
addSpanEvent(span, 'no_threads_found', { mergeTicketIds });
|
||||
}
|
||||
|
||||
// Step 2: Consolidate admin notes
|
||||
edgeLogger.info('Step 2: Consolidating admin notes', { requestId: tracking.requestId });
|
||||
|
||||
let consolidatedNotes = primaryTicket.admin_notes || '';
|
||||
|
||||
for (const ticket of mergeTickets) {
|
||||
@@ -161,8 +106,6 @@ serve(async (req) => {
|
||||
}
|
||||
|
||||
// Step 3: Recalculate metadata from consolidated threads
|
||||
edgeLogger.info('Step 3: Recalculating metadata from threads', { requestId: tracking.requestId });
|
||||
|
||||
const { data: threadStats, error: statsError } = await supabase
|
||||
.from('contact_email_threads')
|
||||
.select('direction, created_at')
|
||||
@@ -178,8 +121,7 @@ serve(async (req) => {
|
||||
?.filter(t => t.direction === 'inbound')
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
|
||||
|
||||
edgeLogger.info('Metadata recalculated', {
|
||||
requestId: tracking.requestId,
|
||||
addSpanEvent(span, 'metadata_recalculated', {
|
||||
outboundCount,
|
||||
lastAdminResponse,
|
||||
lastUserResponse
|
||||
@@ -189,8 +131,6 @@ serve(async (req) => {
|
||||
const mergedTicketNumbers = mergeTickets.map(t => t.ticket_number);
|
||||
|
||||
// Step 4: Update primary ticket with consolidated data
|
||||
edgeLogger.info('Step 4: Updating primary ticket', { requestId: tracking.requestId });
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('contact_submissions')
|
||||
.update({
|
||||
@@ -207,14 +147,9 @@ serve(async (req) => {
|
||||
|
||||
if (updateError) throw updateError;
|
||||
|
||||
edgeLogger.info('Primary ticket updated successfully', { requestId: tracking.requestId });
|
||||
addSpanEvent(span, 'primary_ticket_updated', { primaryTicket: primaryTicket.ticket_number });
|
||||
|
||||
// Step 5: Delete merged tickets
|
||||
edgeLogger.info('Step 5: Deleting merged tickets', {
|
||||
requestId: tracking.requestId,
|
||||
ticketsToDelete: mergeTicketIds.length
|
||||
});
|
||||
|
||||
const { error: deleteError } = await supabase
|
||||
.from('contact_submissions')
|
||||
.delete()
|
||||
@@ -222,14 +157,12 @@ serve(async (req) => {
|
||||
|
||||
if (deleteError) throw deleteError;
|
||||
|
||||
edgeLogger.info('Merged tickets deleted successfully', { requestId: tracking.requestId });
|
||||
addSpanEvent(span, 'merged_tickets_deleted', { count: mergeTicketIds.length });
|
||||
|
||||
// Step 6: Audit log
|
||||
edgeLogger.info('Step 6: Creating audit log', { requestId: tracking.requestId });
|
||||
|
||||
const { error: auditError } = await supabase.from('admin_audit_log').insert({
|
||||
admin_user_id: user.id,
|
||||
target_user_id: user.id, // No specific target user for this action
|
||||
target_user_id: user.id,
|
||||
action: 'merge_contact_tickets',
|
||||
details: {
|
||||
primary_ticket_id: primaryTicketId,
|
||||
@@ -243,20 +176,12 @@ serve(async (req) => {
|
||||
});
|
||||
|
||||
if (auditError) {
|
||||
edgeLogger.warn('Failed to create audit log for merge', {
|
||||
requestId: tracking.requestId,
|
||||
error: auditError.message,
|
||||
primaryTicket: primaryTicket.ticket_number
|
||||
});
|
||||
// Don't throw - merge already succeeded
|
||||
addSpanEvent(span, 'audit_log_failed', { error: auditError.message });
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Merge tickets completed successfully', {
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
addSpanEvent(span, 'merge_completed', {
|
||||
primaryTicket: primaryTicket.ticket_number,
|
||||
mergedCount: mergeTickets.length,
|
||||
mergedCount: mergeTickets.length
|
||||
});
|
||||
|
||||
const response: MergeTicketsResponse = {
|
||||
@@ -267,24 +192,14 @@ serve(async (req) => {
|
||||
deletedTickets: mergedTicketNumbers,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(response), {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
});
|
||||
return response;
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Merge tickets failed', {
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
});
|
||||
|
||||
// Persist error to database for monitoring
|
||||
const errorSpan = startSpan('merge-contact-tickets-error', 'SERVER');
|
||||
endSpan(errorSpan, 'error', error);
|
||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
||||
|
||||
return createErrorResponse(error, 500, corsHeaders, 'merge_contact_tickets');
|
||||
}
|
||||
});
|
||||
serve(createEdgeFunction({
|
||||
name: 'merge-contact-tickets',
|
||||
requireAuth: true,
|
||||
requiredRoles: ['superuser', 'admin', 'moderator'],
|
||||
corsHeaders,
|
||||
enableTracing: true,
|
||||
logRequests: true,
|
||||
}, handler));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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";
|
||||
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { addSpanEvent } from '../_shared/logger.ts';
|
||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||
|
||||
interface NotificationPayload {
|
||||
@@ -15,27 +15,13 @@ interface NotificationPayload {
|
||||
entityPreview: string;
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest('notify-moderators-report');
|
||||
|
||||
try {
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||
|
||||
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||
const payload: NotificationPayload = await req.json();
|
||||
|
||||
edgeLogger.info('Processing report notification', {
|
||||
action: 'notify_moderators_report',
|
||||
addSpanEvent(span, 'processing_report_notification', {
|
||||
reportId: payload.reportId,
|
||||
reportType: payload.reportType,
|
||||
reportedEntityType: payload.reportedEntityType,
|
||||
requestId: tracking.requestId
|
||||
reportedEntityType: payload.reportedEntityType
|
||||
});
|
||||
|
||||
// Calculate relative time
|
||||
@@ -76,21 +62,18 @@ serve(async (req) => {
|
||||
.maybeSingle();
|
||||
|
||||
if (templateError) {
|
||||
edgeLogger.error('Error fetching workflow', { action: 'notify_moderators_report', requestId: tracking.requestId, error: templateError });
|
||||
addSpanEvent(span, 'workflow_fetch_failed', { error: templateError.message });
|
||||
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
|
||||
}
|
||||
|
||||
if (!template) {
|
||||
edgeLogger.warn('No active report-alert workflow found', { action: 'notify_moderators_report', requestId: tracking.requestId });
|
||||
addSpanEvent(span, 'no_active_workflow', {});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'No active report-alert workflow configured',
|
||||
}),
|
||||
{
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 400,
|
||||
}
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -115,7 +98,6 @@ serve(async (req) => {
|
||||
|
||||
reportedEntityName = profile?.display_name || profile?.username || 'User Profile';
|
||||
} else if (payload.reportedEntityType === 'content_submission') {
|
||||
// Query submission_metadata table for the name instead of dropped content JSONB column
|
||||
const { data: metadata } = await supabase
|
||||
.from('submission_metadata')
|
||||
.select('metadata_value')
|
||||
@@ -126,7 +108,9 @@ serve(async (req) => {
|
||||
reportedEntityName = metadata?.metadata_value || 'Submission';
|
||||
}
|
||||
} catch (error) {
|
||||
edgeLogger.warn('Could not fetch entity name', { action: 'notify_moderators_report', requestId: tracking.requestId, error });
|
||||
addSpanEvent(span, 'entity_name_fetch_failed', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
}
|
||||
|
||||
// Build enhanced notification payload
|
||||
@@ -145,7 +129,10 @@ serve(async (req) => {
|
||||
priority,
|
||||
};
|
||||
|
||||
edgeLogger.info('Triggering notification with payload', { action: 'notify_moderators_report', requestId: tracking.requestId });
|
||||
addSpanEvent(span, 'triggering_notification', {
|
||||
workflowId: template.workflow_id,
|
||||
priority
|
||||
});
|
||||
|
||||
// Invoke the trigger-notification function with retry
|
||||
const result = await withEdgeRetry(
|
||||
@@ -170,49 +157,24 @@ serve(async (req) => {
|
||||
return data;
|
||||
},
|
||||
{ maxAttempts: 3, baseDelay: 1000 },
|
||||
tracking.requestId,
|
||||
requestId,
|
||||
'trigger-report-notification'
|
||||
);
|
||||
|
||||
edgeLogger.info('Notification triggered successfully', { action: 'notify_moderators_report', requestId: tracking.requestId, result });
|
||||
addSpanEvent(span, 'notification_sent', { transactionId: result?.transactionId });
|
||||
|
||||
endRequest(tracking, 200);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
return {
|
||||
success: true,
|
||||
transactionId: result?.transactionId,
|
||||
payload: notificationPayload,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error: any) {
|
||||
edgeLogger.error('Error in notify-moderators-report', { action: 'notify_moderators_report', requestId: tracking.requestId, error: error.message });
|
||||
};
|
||||
};
|
||||
|
||||
endRequest(tracking, 500, error.message);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error.message,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
serve(createEdgeFunction({
|
||||
name: 'notify-moderators-report',
|
||||
requireAuth: false,
|
||||
useServiceRole: true,
|
||||
corsHeaders,
|
||||
enableTracing: true,
|
||||
logRequests: true,
|
||||
}, handler));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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";
|
||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
||||
import { addSpanEvent } from '../_shared/logger.ts';
|
||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||
|
||||
interface NotificationPayload {
|
||||
@@ -16,24 +16,7 @@ interface NotificationPayload {
|
||||
is_escalated: boolean;
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'X-Request-ID': tracking.requestId
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||
|
||||
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||
const payload: NotificationPayload = await req.json();
|
||||
const {
|
||||
submission_id,
|
||||
@@ -47,12 +30,9 @@ serve(async (req) => {
|
||||
is_escalated
|
||||
} = payload;
|
||||
|
||||
edgeLogger.info('Notifying moderators about submission via topic', {
|
||||
action: 'notify_moderators',
|
||||
requestId: tracking.requestId,
|
||||
addSpanEvent(span, 'processing_moderator_notification', {
|
||||
submission_id,
|
||||
submission_type,
|
||||
content_preview
|
||||
submission_type
|
||||
});
|
||||
|
||||
// Calculate relative time and priority
|
||||
@@ -85,28 +65,8 @@ serve(async (req) => {
|
||||
.single();
|
||||
|
||||
if (workflowError || !workflow) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error fetching workflow', {
|
||||
action: 'notify_moderators',
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: workflowError
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Workflow not found or not active',
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 500,
|
||||
}
|
||||
);
|
||||
addSpanEvent(span, 'workflow_fetch_failed', { error: workflowError?.message });
|
||||
throw new Error('Workflow not found or not active');
|
||||
}
|
||||
|
||||
// Generate idempotency key for duplicate prevention
|
||||
@@ -114,7 +74,7 @@ serve(async (req) => {
|
||||
.rpc('generate_notification_idempotency_key', {
|
||||
p_notification_type: 'moderation_submission',
|
||||
p_entity_id: submission_id,
|
||||
p_recipient_id: '00000000-0000-0000-0000-000000000000', // Topic-based, use placeholder
|
||||
p_recipient_id: '00000000-0000-0000-0000-000000000000',
|
||||
p_event_data: { submission_type, action }
|
||||
});
|
||||
|
||||
@@ -129,62 +89,46 @@ serve(async (req) => {
|
||||
.maybeSingle();
|
||||
|
||||
if (existingLog) {
|
||||
// Duplicate detected - log and skip
|
||||
// Duplicate detected
|
||||
await supabase.from('notification_logs').update({
|
||||
is_duplicate: true
|
||||
}).eq('id', existingLog.id);
|
||||
|
||||
edgeLogger.info('Duplicate notification prevented', {
|
||||
action: 'notify_moderators',
|
||||
requestId: tracking.requestId,
|
||||
addSpanEvent(span, 'duplicate_notification_prevented', {
|
||||
idempotencyKey,
|
||||
submission_id
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
return {
|
||||
success: true,
|
||||
message: 'Duplicate notification prevented',
|
||||
idempotencyKey,
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
// Prepare enhanced notification payload
|
||||
const notificationPayload = {
|
||||
baseUrl: 'https://www.thrillwiki.com',
|
||||
// Basic info
|
||||
itemType: submission_type,
|
||||
submitterName: submitter_name,
|
||||
submissionId: submission_id,
|
||||
action: action || 'create',
|
||||
moderationUrl: 'https://www.thrillwiki.com/admin/moderation',
|
||||
|
||||
// Enhanced content
|
||||
contentPreview: content_preview,
|
||||
|
||||
// Timing information
|
||||
submittedAt: submitted_at,
|
||||
relativeTime: relativeTime,
|
||||
priority: priority,
|
||||
|
||||
// Additional metadata
|
||||
hasPhotos: has_photos,
|
||||
itemCount: item_count,
|
||||
isEscalated: is_escalated,
|
||||
};
|
||||
|
||||
addSpanEvent(span, 'triggering_notification', {
|
||||
workflowId: workflow.workflow_id,
|
||||
priority
|
||||
});
|
||||
|
||||
// Send ONE notification to the moderation-submissions topic with retry
|
||||
// All subscribers (moderators) will receive it automatically
|
||||
const data = await withEdgeRetry(
|
||||
async () => {
|
||||
const { data: result, error } = await supabase.functions.invoke('trigger-notification', {
|
||||
@@ -204,13 +148,13 @@ serve(async (req) => {
|
||||
return result;
|
||||
},
|
||||
{ maxAttempts: 3, baseDelay: 1000 },
|
||||
tracking.requestId,
|
||||
requestId,
|
||||
'trigger-submission-notification'
|
||||
);
|
||||
|
||||
// Log notification in notification_logs with idempotency key
|
||||
// Log notification with idempotency key
|
||||
const { error: logError } = await supabase.from('notification_logs').insert({
|
||||
user_id: '00000000-0000-0000-0000-000000000000', // Topic-based
|
||||
user_id: '00000000-0000-0000-0000-000000000000',
|
||||
notification_type: 'moderation_submission',
|
||||
idempotency_key: idempotencyKey,
|
||||
is_duplicate: false,
|
||||
@@ -222,69 +166,27 @@ serve(async (req) => {
|
||||
});
|
||||
|
||||
if (logError) {
|
||||
// Non-blocking - notification was sent successfully, log failure shouldn't fail the request
|
||||
edgeLogger.warn('Failed to log notification in notification_logs', {
|
||||
action: 'notify_moderators',
|
||||
requestId: tracking.requestId,
|
||||
error: logError.message,
|
||||
submissionId: submission_id
|
||||
});
|
||||
addSpanEvent(span, 'log_insertion_failed', { error: logError.message });
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Successfully notified all moderators via topic', {
|
||||
action: 'notify_moderators',
|
||||
requestId: tracking.requestId,
|
||||
traceId: tracking.traceId,
|
||||
duration,
|
||||
transactionId: data?.transactionId
|
||||
addSpanEvent(span, 'notification_sent', {
|
||||
transactionId: data?.transactionId,
|
||||
topicKey: 'moderation-submissions'
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
return {
|
||||
success: true,
|
||||
message: 'Moderator notifications sent via topic',
|
||||
topicKey: 'moderation-submissions',
|
||||
transactionId: data?.transactionId,
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
} catch (error: any) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error in notify-moderators-submission', {
|
||||
action: 'notify_moderators',
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: error.message
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
// Persist error to database for monitoring
|
||||
const errorSpan = startSpan('notify-moderators-submission-error', 'SERVER');
|
||||
endSpan(errorSpan, 'error', error);
|
||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error.message,
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
status: 500,
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
serve(createEdgeFunction({
|
||||
name: 'notify-moderators-submission',
|
||||
requireAuth: false,
|
||||
useServiceRole: true,
|
||||
corsHeaders,
|
||||
enableTracing: true,
|
||||
logRequests: true,
|
||||
}, handler));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
|
||||
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
||||
import { addSpanEvent } from '../_shared/logger.ts';
|
||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||
|
||||
interface EscalationRequest {
|
||||
@@ -10,27 +10,10 @@ interface EscalationRequest {
|
||||
escalatedBy: string;
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
||||
);
|
||||
|
||||
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||
const { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
|
||||
|
||||
edgeLogger.info('Processing escalation notification', {
|
||||
requestId: tracking.requestId,
|
||||
submissionId,
|
||||
escalatedBy,
|
||||
action: 'send_escalation'
|
||||
});
|
||||
addSpanEvent(span, 'processing_escalation', { submissionId, escalatedBy });
|
||||
|
||||
// Fetch submission details
|
||||
const { data: submission, error: submissionError } = await supabase
|
||||
@@ -51,11 +34,7 @@ serve(async (req) => {
|
||||
.single();
|
||||
|
||||
if (escalatorError) {
|
||||
edgeLogger.error('Failed to fetch escalator profile', {
|
||||
requestId: tracking.requestId,
|
||||
error: escalatorError.message,
|
||||
escalatedBy
|
||||
});
|
||||
addSpanEvent(span, 'escalator_profile_fetch_failed', { error: escalatorError.message });
|
||||
}
|
||||
|
||||
// Fetch submission items count
|
||||
@@ -65,11 +44,7 @@ serve(async (req) => {
|
||||
.eq('submission_id', submissionId);
|
||||
|
||||
if (countError) {
|
||||
edgeLogger.error('Failed to fetch items count', {
|
||||
requestId: tracking.requestId,
|
||||
error: countError.message,
|
||||
submissionId
|
||||
});
|
||||
addSpanEvent(span, 'items_count_fetch_failed', { error: countError.message });
|
||||
}
|
||||
|
||||
// Prepare email content
|
||||
@@ -175,6 +150,8 @@ serve(async (req) => {
|
||||
throw new Error('Email configuration is incomplete. Please check environment variables.');
|
||||
}
|
||||
|
||||
addSpanEvent(span, 'sending_escalation_email', { adminEmail });
|
||||
|
||||
const emailResult = await withEdgeRetry(
|
||||
async () => {
|
||||
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
||||
@@ -196,7 +173,7 @@ serve(async (req) => {
|
||||
let errorText;
|
||||
try {
|
||||
errorText = await emailResponse.text();
|
||||
} catch (parseError) {
|
||||
} catch {
|
||||
errorText = 'Unable to parse error response';
|
||||
}
|
||||
|
||||
@@ -205,19 +182,16 @@ serve(async (req) => {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const result = await emailResponse.json();
|
||||
return result;
|
||||
return await emailResponse.json();
|
||||
},
|
||||
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
|
||||
tracking.requestId,
|
||||
requestId,
|
||||
'send-escalation-email'
|
||||
);
|
||||
edgeLogger.info('Email sent successfully', {
|
||||
requestId: tracking.requestId,
|
||||
emailId: emailResult.id
|
||||
});
|
||||
|
||||
// Update submission with notification status
|
||||
addSpanEvent(span, 'email_sent', { emailId: emailResult.id });
|
||||
|
||||
// Update submission with escalation status
|
||||
const { error: updateError } = await supabase
|
||||
.from('content_submissions')
|
||||
.update({
|
||||
@@ -229,57 +203,26 @@ serve(async (req) => {
|
||||
.eq('id', submissionId);
|
||||
|
||||
if (updateError) {
|
||||
edgeLogger.error('Failed to update submission escalation status', {
|
||||
requestId: tracking.requestId,
|
||||
error: updateError.message,
|
||||
submissionId
|
||||
});
|
||||
addSpanEvent(span, 'submission_update_failed', { error: updateError.message });
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Escalation notification sent', {
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
addSpanEvent(span, 'escalation_notification_complete', {
|
||||
emailId: emailResult.id,
|
||||
submissionId
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
return {
|
||||
success: true,
|
||||
message: 'Escalation notification sent successfully',
|
||||
emailId: emailResult.id,
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{ headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
} }
|
||||
);
|
||||
} catch (error) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error in send-escalation-notification', {
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
// Persist error to database for monitoring
|
||||
const errorSpan = startSpan('send-escalation-notification-error', 'SERVER');
|
||||
endSpan(errorSpan, 'error', error);
|
||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||
details: 'Failed to send escalation notification',
|
||||
requestId: tracking.requestId
|
||||
}),
|
||||
{ status: 500, headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
} }
|
||||
);
|
||||
}
|
||||
});
|
||||
serve(createEdgeFunction({
|
||||
name: 'send-escalation-notification',
|
||||
requireAuth: false,
|
||||
useServiceRole: true,
|
||||
corsHeaders,
|
||||
enableTracing: true,
|
||||
logRequests: true,
|
||||
}, handler));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
||||
import { addSpanEvent } from '../_shared/logger.ts';
|
||||
|
||||
interface EmailRequest {
|
||||
email: string;
|
||||
@@ -9,58 +9,14 @@ interface EmailRequest {
|
||||
username?: string;
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'X-Request-ID': tracking.requestId
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const supabaseClient = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
||||
{
|
||||
global: {
|
||||
headers: { Authorization: req.headers.get('Authorization')! },
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const { data: { user }, error: userError } = await supabaseClient.auth.getUser();
|
||||
|
||||
if (userError || !user) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Authentication failed', {
|
||||
action: 'send_password_email',
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
});
|
||||
|
||||
// Persist error to database
|
||||
const authErrorSpan = startSpan('send-password-added-email-auth-error', 'SERVER');
|
||||
endSpan(authErrorSpan, 'error', userError);
|
||||
logSpanToDatabase(authErrorSpan, tracking.requestId);
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
const handler = async (req: Request, { user, span, requestId }: EdgeFunctionContext) => {
|
||||
const { email, displayName, username }: EmailRequest = await req.json();
|
||||
|
||||
if (!email) {
|
||||
throw new Error('Email is required');
|
||||
}
|
||||
|
||||
edgeLogger.info('Sending password added email', {
|
||||
action: 'send_password_email',
|
||||
requestId: tracking.requestId,
|
||||
userId: user.id,
|
||||
email
|
||||
});
|
||||
addSpanEvent(span, 'sending_password_email', { userId: user.id, email });
|
||||
|
||||
const recipientName = displayName || username || 'there';
|
||||
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
|
||||
@@ -139,7 +95,7 @@ serve(async (req) => {
|
||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||
|
||||
if (!forwardEmailKey) {
|
||||
edgeLogger.error('FORWARDEMAIL_API_KEY not configured', { requestId: tracking.requestId });
|
||||
addSpanEvent(span, 'email_config_missing', {});
|
||||
throw new Error('Email service not configured');
|
||||
}
|
||||
|
||||
@@ -159,67 +115,25 @@ serve(async (req) => {
|
||||
|
||||
if (!emailResponse.ok) {
|
||||
const errorText = await emailResponse.text();
|
||||
edgeLogger.error('ForwardEmail API error', {
|
||||
requestId: tracking.requestId,
|
||||
addSpanEvent(span, 'email_send_failed', {
|
||||
status: emailResponse.status,
|
||||
errorText
|
||||
error: errorText
|
||||
});
|
||||
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Password addition email sent successfully', {
|
||||
action: 'send_password_email',
|
||||
requestId: tracking.requestId,
|
||||
userId: user.id,
|
||||
email,
|
||||
duration
|
||||
});
|
||||
addSpanEvent(span, 'email_sent_successfully', { email });
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
return {
|
||||
success: true,
|
||||
message: 'Password addition email sent successfully',
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error in send-password-added-email function', {
|
||||
action: 'send_password_email',
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
});
|
||||
|
||||
// Persist error to database for monitoring
|
||||
const errorSpan = startSpan('send-password-added-email-error', 'SERVER');
|
||||
endSpan(errorSpan, 'error', error);
|
||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
serve(createEdgeFunction({
|
||||
name: 'send-password-added-email',
|
||||
requireAuth: true,
|
||||
corsHeaders,
|
||||
enableTracing: true,
|
||||
logRequests: true,
|
||||
}, handler));
|
||||
|
||||
Reference in New Issue
Block a user