mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 12:31: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 { 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 { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { createErrorResponse, sanitizeError } from '../_shared/errorSanitizer.ts';
|
|
||||||
|
|
||||||
interface MergeTicketsRequest {
|
interface MergeTicketsRequest {
|
||||||
primaryTicketId: string;
|
primaryTicketId: string;
|
||||||
@@ -18,273 +17,189 @@ interface MergeTicketsResponse {
|
|||||||
deletedTickets: string[];
|
deletedTickets: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||||
const tracking = startRequest();
|
// Parse request body
|
||||||
|
const { primaryTicketId, mergeTicketIds, mergeReason }: MergeTicketsRequest = await req.json();
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
// Validation
|
||||||
return new Response(null, { headers: corsHeaders });
|
if (!primaryTicketId || !mergeTicketIds || mergeTicketIds.length === 0) {
|
||||||
|
throw new Error('Invalid request: primaryTicketId and mergeTicketIds required');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
if (mergeTicketIds.includes(primaryTicketId)) {
|
||||||
const authHeader = req.headers.get('Authorization');
|
throw new Error('Cannot merge a ticket into itself');
|
||||||
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.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse request body
|
|
||||||
const { primaryTicketId, mergeTicketIds, mergeReason }: MergeTicketsRequest = await req.json();
|
|
||||||
|
|
||||||
// Validation
|
|
||||||
if (!primaryTicketId || !mergeTicketIds || mergeTicketIds.length === 0) {
|
|
||||||
throw new Error('Invalid request: primaryTicketId and mergeTicketIds required');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mergeTicketIds.includes(primaryTicketId)) {
|
|
||||||
throw new Error('Cannot merge a ticket into itself');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mergeTicketIds.length > 10) {
|
|
||||||
throw new Error('Maximum 10 tickets can be merged at once');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start transaction-like operations
|
|
||||||
const allTicketIds = [primaryTicketId, ...mergeTicketIds];
|
|
||||||
|
|
||||||
// Fetch all tickets
|
|
||||||
const { data: tickets, error: fetchError } = await supabase
|
|
||||||
.from('contact_submissions')
|
|
||||||
.select('id, ticket_number, admin_notes, merged_ticket_numbers')
|
|
||||||
.in('id', allTicketIds);
|
|
||||||
|
|
||||||
if (fetchError) throw fetchError;
|
|
||||||
if (!tickets || tickets.length !== allTicketIds.length) {
|
|
||||||
throw new Error('One or more tickets not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const primaryTicket = tickets.find(t => t.id === primaryTicketId);
|
|
||||||
const mergeTickets = tickets.filter(t => mergeTicketIds.includes(t.id));
|
|
||||||
|
|
||||||
if (!primaryTicket) {
|
|
||||||
throw new Error('Primary ticket not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if any ticket already has merged_ticket_numbers (prevent re-merging)
|
|
||||||
const alreadyMerged = tickets.find(t =>
|
|
||||||
t.merged_ticket_numbers && t.merged_ticket_numbers.length > 0
|
|
||||||
);
|
|
||||||
if (alreadyMerged) {
|
|
||||||
throw new Error(`Ticket ${alreadyMerged.ticket_number} has already been used in a merge`);
|
|
||||||
}
|
|
||||||
|
|
||||||
edgeLogger.info('Starting merge process', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
primaryTicket: primaryTicket.ticket_number,
|
|
||||||
mergeTicketCount: mergeTickets.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Step 1: Move all email threads to primary ticket
|
|
||||||
edgeLogger.info('Step 1: Moving email threads', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
fromTickets: mergeTickets.map(t => t.ticket_number)
|
|
||||||
});
|
|
||||||
|
|
||||||
const { data: movedThreads, error: moveError } = await supabase
|
|
||||||
.from('contact_email_threads')
|
|
||||||
.update({ submission_id: primaryTicketId })
|
|
||||||
.in('submission_id', mergeTicketIds)
|
|
||||||
.select('id');
|
|
||||||
|
|
||||||
if (moveError) throw moveError;
|
|
||||||
|
|
||||||
const threadsMovedCount = movedThreads?.length || 0;
|
|
||||||
|
|
||||||
edgeLogger.info('Threads moved successfully', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
threadsMovedCount
|
|
||||||
});
|
|
||||||
|
|
||||||
if (threadsMovedCount === 0) {
|
|
||||||
edgeLogger.warn('No email threads found to move', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
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) {
|
|
||||||
if (ticket.admin_notes) {
|
|
||||||
consolidatedNotes = consolidatedNotes.trim()
|
|
||||||
? `${consolidatedNotes}\n\n${ticket.admin_notes}`
|
|
||||||
: ticket.admin_notes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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')
|
|
||||||
.eq('submission_id', primaryTicketId);
|
|
||||||
|
|
||||||
if (statsError) throw statsError;
|
|
||||||
|
|
||||||
const outboundCount = threadStats?.filter(t => t.direction === 'outbound').length || 0;
|
|
||||||
const lastAdminResponse = threadStats
|
|
||||||
?.filter(t => t.direction === 'outbound')
|
|
||||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
|
|
||||||
const lastUserResponse = threadStats
|
|
||||||
?.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,
|
|
||||||
outboundCount,
|
|
||||||
lastAdminResponse,
|
|
||||||
lastUserResponse
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get merged ticket numbers
|
|
||||||
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({
|
|
||||||
admin_notes: consolidatedNotes,
|
|
||||||
response_count: outboundCount,
|
|
||||||
last_admin_response_at: lastAdminResponse || null,
|
|
||||||
merged_ticket_numbers: [
|
|
||||||
...(primaryTicket.merged_ticket_numbers || []),
|
|
||||||
...mergedTicketNumbers
|
|
||||||
],
|
|
||||||
updated_at: new Date().toISOString(),
|
|
||||||
})
|
|
||||||
.eq('id', primaryTicketId);
|
|
||||||
|
|
||||||
if (updateError) throw updateError;
|
|
||||||
|
|
||||||
edgeLogger.info('Primary ticket updated successfully', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
// 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()
|
|
||||||
.in('id', mergeTicketIds);
|
|
||||||
|
|
||||||
if (deleteError) throw deleteError;
|
|
||||||
|
|
||||||
edgeLogger.info('Merged tickets deleted successfully', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
// 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
|
|
||||||
action: 'merge_contact_tickets',
|
|
||||||
details: {
|
|
||||||
primary_ticket_id: primaryTicketId,
|
|
||||||
primary_ticket_number: primaryTicket.ticket_number,
|
|
||||||
merged_ticket_ids: mergeTicketIds,
|
|
||||||
merged_ticket_numbers: mergedTicketNumbers,
|
|
||||||
merge_reason: mergeReason || null,
|
|
||||||
threads_moved: threadsMovedCount,
|
|
||||||
merged_count: mergeTickets.length,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.info('Merge tickets completed successfully', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
primaryTicket: primaryTicket.ticket_number,
|
|
||||||
mergedCount: mergeTickets.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
const response: MergeTicketsResponse = {
|
|
||||||
success: true,
|
|
||||||
primaryTicketNumber: primaryTicket.ticket_number,
|
|
||||||
mergedCount: mergeTickets.length,
|
|
||||||
threadsConsolidated: threadsMovedCount,
|
|
||||||
deletedTickets: mergedTicketNumbers,
|
|
||||||
};
|
|
||||||
|
|
||||||
return new Response(JSON.stringify(response), {
|
|
||||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
||||||
status: 200,
|
|
||||||
});
|
|
||||||
|
|
||||||
} 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');
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
if (mergeTicketIds.length > 10) {
|
||||||
|
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];
|
||||||
|
|
||||||
|
// Fetch all tickets
|
||||||
|
const { data: tickets, error: fetchError } = await supabase
|
||||||
|
.from('contact_submissions')
|
||||||
|
.select('id, ticket_number, admin_notes, merged_ticket_numbers')
|
||||||
|
.in('id', allTicketIds);
|
||||||
|
|
||||||
|
if (fetchError) throw fetchError;
|
||||||
|
if (!tickets || tickets.length !== allTicketIds.length) {
|
||||||
|
throw new Error('One or more tickets not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const primaryTicket = tickets.find(t => t.id === primaryTicketId);
|
||||||
|
const mergeTickets = tickets.filter(t => mergeTicketIds.includes(t.id));
|
||||||
|
|
||||||
|
if (!primaryTicket) {
|
||||||
|
throw new Error('Primary ticket not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if any ticket already has merged_ticket_numbers
|
||||||
|
const alreadyMerged = tickets.find(t =>
|
||||||
|
t.merged_ticket_numbers && t.merged_ticket_numbers.length > 0
|
||||||
|
);
|
||||||
|
if (alreadyMerged) {
|
||||||
|
throw new Error(`Ticket ${alreadyMerged.ticket_number} has already been used in a merge`);
|
||||||
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'tickets_validated', {
|
||||||
|
primaryTicket: primaryTicket.ticket_number,
|
||||||
|
mergeTicketCount: mergeTickets.length
|
||||||
|
});
|
||||||
|
|
||||||
|
// Step 1: Move all email threads to primary ticket
|
||||||
|
addSpanEvent(span, 'moving_email_threads', {
|
||||||
|
fromTickets: mergeTickets.map(t => t.ticket_number)
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: movedThreads, error: moveError } = await supabase
|
||||||
|
.from('contact_email_threads')
|
||||||
|
.update({ submission_id: primaryTicketId })
|
||||||
|
.in('submission_id', mergeTicketIds)
|
||||||
|
.select('id');
|
||||||
|
|
||||||
|
if (moveError) throw moveError;
|
||||||
|
|
||||||
|
const threadsMovedCount = movedThreads?.length || 0;
|
||||||
|
|
||||||
|
addSpanEvent(span, 'threads_moved', { threadsMovedCount });
|
||||||
|
|
||||||
|
if (threadsMovedCount === 0) {
|
||||||
|
addSpanEvent(span, 'no_threads_found', { mergeTicketIds });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Consolidate admin notes
|
||||||
|
let consolidatedNotes = primaryTicket.admin_notes || '';
|
||||||
|
|
||||||
|
for (const ticket of mergeTickets) {
|
||||||
|
if (ticket.admin_notes) {
|
||||||
|
consolidatedNotes = consolidatedNotes.trim()
|
||||||
|
? `${consolidatedNotes}\n\n${ticket.admin_notes}`
|
||||||
|
: ticket.admin_notes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 3: Recalculate metadata from consolidated threads
|
||||||
|
const { data: threadStats, error: statsError } = await supabase
|
||||||
|
.from('contact_email_threads')
|
||||||
|
.select('direction, created_at')
|
||||||
|
.eq('submission_id', primaryTicketId);
|
||||||
|
|
||||||
|
if (statsError) throw statsError;
|
||||||
|
|
||||||
|
const outboundCount = threadStats?.filter(t => t.direction === 'outbound').length || 0;
|
||||||
|
const lastAdminResponse = threadStats
|
||||||
|
?.filter(t => t.direction === 'outbound')
|
||||||
|
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
|
||||||
|
const lastUserResponse = threadStats
|
||||||
|
?.filter(t => t.direction === 'inbound')
|
||||||
|
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
|
||||||
|
|
||||||
|
addSpanEvent(span, 'metadata_recalculated', {
|
||||||
|
outboundCount,
|
||||||
|
lastAdminResponse,
|
||||||
|
lastUserResponse
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get merged ticket numbers
|
||||||
|
const mergedTicketNumbers = mergeTickets.map(t => t.ticket_number);
|
||||||
|
|
||||||
|
// Step 4: Update primary ticket with consolidated data
|
||||||
|
const { error: updateError } = await supabase
|
||||||
|
.from('contact_submissions')
|
||||||
|
.update({
|
||||||
|
admin_notes: consolidatedNotes,
|
||||||
|
response_count: outboundCount,
|
||||||
|
last_admin_response_at: lastAdminResponse || null,
|
||||||
|
merged_ticket_numbers: [
|
||||||
|
...(primaryTicket.merged_ticket_numbers || []),
|
||||||
|
...mergedTicketNumbers
|
||||||
|
],
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.eq('id', primaryTicketId);
|
||||||
|
|
||||||
|
if (updateError) throw updateError;
|
||||||
|
|
||||||
|
addSpanEvent(span, 'primary_ticket_updated', { primaryTicket: primaryTicket.ticket_number });
|
||||||
|
|
||||||
|
// Step 5: Delete merged tickets
|
||||||
|
const { error: deleteError } = await supabase
|
||||||
|
.from('contact_submissions')
|
||||||
|
.delete()
|
||||||
|
.in('id', mergeTicketIds);
|
||||||
|
|
||||||
|
if (deleteError) throw deleteError;
|
||||||
|
|
||||||
|
addSpanEvent(span, 'merged_tickets_deleted', { count: mergeTicketIds.length });
|
||||||
|
|
||||||
|
// Step 6: Audit log
|
||||||
|
const { error: auditError } = await supabase.from('admin_audit_log').insert({
|
||||||
|
admin_user_id: user.id,
|
||||||
|
target_user_id: user.id,
|
||||||
|
action: 'merge_contact_tickets',
|
||||||
|
details: {
|
||||||
|
primary_ticket_id: primaryTicketId,
|
||||||
|
primary_ticket_number: primaryTicket.ticket_number,
|
||||||
|
merged_ticket_ids: mergeTicketIds,
|
||||||
|
merged_ticket_numbers: mergedTicketNumbers,
|
||||||
|
merge_reason: mergeReason || null,
|
||||||
|
threads_moved: threadsMovedCount,
|
||||||
|
merged_count: mergeTickets.length,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (auditError) {
|
||||||
|
addSpanEvent(span, 'audit_log_failed', { error: auditError.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'merge_completed', {
|
||||||
|
primaryTicket: primaryTicket.ticket_number,
|
||||||
|
mergedCount: mergeTickets.length
|
||||||
|
});
|
||||||
|
|
||||||
|
const response: MergeTicketsResponse = {
|
||||||
|
success: true,
|
||||||
|
primaryTicketNumber: primaryTicket.ticket_number,
|
||||||
|
mergedCount: mergeTickets.length,
|
||||||
|
threadsConsolidated: threadsMovedCount,
|
||||||
|
deletedTickets: mergedTicketNumbers,
|
||||||
|
};
|
||||||
|
|
||||||
|
return response;
|
||||||
|
};
|
||||||
|
|
||||||
|
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 { 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 { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||||
|
|
||||||
interface NotificationPayload {
|
interface NotificationPayload {
|
||||||
@@ -15,204 +15,166 @@ interface NotificationPayload {
|
|||||||
entityPreview: string;
|
entityPreview: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
if (req.method === 'OPTIONS') {
|
const payload: NotificationPayload = await req.json();
|
||||||
return new Response(null, { headers: corsHeaders });
|
|
||||||
|
addSpanEvent(span, 'processing_report_notification', {
|
||||||
|
reportId: payload.reportId,
|
||||||
|
reportType: payload.reportType,
|
||||||
|
reportedEntityType: payload.reportedEntityType
|
||||||
|
});
|
||||||
|
|
||||||
|
// Calculate relative time
|
||||||
|
const reportedAt = new Date(payload.reportedAt);
|
||||||
|
const now = new Date();
|
||||||
|
const diffMs = now.getTime() - reportedAt.getTime();
|
||||||
|
const diffMins = Math.floor(diffMs / 60000);
|
||||||
|
|
||||||
|
let relativeTime: string;
|
||||||
|
if (diffMins < 1) {
|
||||||
|
relativeTime = 'just now';
|
||||||
|
} else if (diffMins < 60) {
|
||||||
|
relativeTime = `${diffMins} minute${diffMins === 1 ? '' : 's'} ago`;
|
||||||
|
} else {
|
||||||
|
const diffHours = Math.floor(diffMins / 60);
|
||||||
|
relativeTime = `${diffHours} hour${diffHours === 1 ? '' : 's'} ago`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const tracking = startRequest('notify-moderators-report');
|
// Determine priority based on report type and age
|
||||||
|
let priority: string;
|
||||||
|
const criticalTypes = ['harassment', 'offensive'];
|
||||||
|
const isUrgent = diffMins < 5;
|
||||||
|
|
||||||
|
if (criticalTypes.includes(payload.reportType) || isUrgent) {
|
||||||
|
priority = 'high';
|
||||||
|
} else if (diffMins < 30) {
|
||||||
|
priority = 'medium';
|
||||||
|
} else {
|
||||||
|
priority = 'low';
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
// Fetch the workflow ID for report alerts
|
||||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
const { data: template, error: templateError } = await supabase
|
||||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
.from('notification_templates')
|
||||||
|
.select('workflow_id')
|
||||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
.eq('workflow_id', 'report-alert')
|
||||||
|
.eq('is_active', true)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
const payload: NotificationPayload = await req.json();
|
if (templateError) {
|
||||||
|
addSpanEvent(span, 'workflow_fetch_failed', { error: templateError.message });
|
||||||
edgeLogger.info('Processing report notification', {
|
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
|
||||||
action: 'notify_moderators_report',
|
}
|
||||||
reportId: payload.reportId,
|
|
||||||
reportType: payload.reportType,
|
|
||||||
reportedEntityType: payload.reportedEntityType,
|
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
|
||||||
|
|
||||||
// Calculate relative time
|
|
||||||
const reportedAt = new Date(payload.reportedAt);
|
|
||||||
const now = new Date();
|
|
||||||
const diffMs = now.getTime() - reportedAt.getTime();
|
|
||||||
const diffMins = Math.floor(diffMs / 60000);
|
|
||||||
|
|
||||||
let relativeTime: string;
|
|
||||||
if (diffMins < 1) {
|
|
||||||
relativeTime = 'just now';
|
|
||||||
} else if (diffMins < 60) {
|
|
||||||
relativeTime = `${diffMins} minute${diffMins === 1 ? '' : 's'} ago`;
|
|
||||||
} else {
|
|
||||||
const diffHours = Math.floor(diffMins / 60);
|
|
||||||
relativeTime = `${diffHours} hour${diffHours === 1 ? '' : 's'} ago`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine priority based on report type and age
|
|
||||||
let priority: string;
|
|
||||||
const criticalTypes = ['harassment', 'offensive'];
|
|
||||||
const isUrgent = diffMins < 5;
|
|
||||||
|
|
||||||
if (criticalTypes.includes(payload.reportType) || isUrgent) {
|
|
||||||
priority = 'high';
|
|
||||||
} else if (diffMins < 30) {
|
|
||||||
priority = 'medium';
|
|
||||||
} else {
|
|
||||||
priority = 'low';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch the workflow ID for report alerts
|
|
||||||
const { data: template, error: templateError } = await supabase
|
|
||||||
.from('notification_templates')
|
|
||||||
.select('workflow_id')
|
|
||||||
.eq('workflow_id', 'report-alert')
|
|
||||||
.eq('is_active', true)
|
|
||||||
.maybeSingle();
|
|
||||||
|
|
||||||
if (templateError) {
|
|
||||||
edgeLogger.error('Error fetching workflow', { action: 'notify_moderators_report', requestId: tracking.requestId, error: templateError });
|
|
||||||
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 });
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: false,
|
|
||||||
error: 'No active report-alert workflow configured',
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
||||||
status: 400,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch reported entity name
|
|
||||||
let reportedEntityName = 'Unknown';
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (payload.reportedEntityType === 'review') {
|
|
||||||
const { data: review } = await supabase
|
|
||||||
.from('reviews')
|
|
||||||
.select('ride:rides(name), park:parks(name)')
|
|
||||||
.eq('id', payload.reportedEntityId)
|
|
||||||
.maybeSingle();
|
|
||||||
|
|
||||||
reportedEntityName = review?.ride?.name || review?.park?.name || 'Review';
|
|
||||||
} else if (payload.reportedEntityType === 'profile') {
|
|
||||||
const { data: profile } = await supabase
|
|
||||||
.from('profiles')
|
|
||||||
.select('display_name, username')
|
|
||||||
.eq('user_id', payload.reportedEntityId)
|
|
||||||
.maybeSingle();
|
|
||||||
|
|
||||||
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')
|
|
||||||
.eq('submission_id', payload.reportedEntityId)
|
|
||||||
.eq('metadata_key', 'name')
|
|
||||||
.maybeSingle();
|
|
||||||
|
|
||||||
reportedEntityName = metadata?.metadata_value || 'Submission';
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
edgeLogger.warn('Could not fetch entity name', { action: 'notify_moderators_report', requestId: tracking.requestId, error });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build enhanced notification payload
|
|
||||||
const notificationPayload = {
|
|
||||||
baseUrl: 'https://www.thrillwiki.com',
|
|
||||||
reportId: payload.reportId,
|
|
||||||
reportType: payload.reportType,
|
|
||||||
reportedEntityType: payload.reportedEntityType,
|
|
||||||
reportedEntityId: payload.reportedEntityId,
|
|
||||||
reporterName: payload.reporterName,
|
|
||||||
reason: payload.reason,
|
|
||||||
entityPreview: payload.entityPreview,
|
|
||||||
reportedEntityName,
|
|
||||||
reportedAt: payload.reportedAt,
|
|
||||||
relativeTime,
|
|
||||||
priority,
|
|
||||||
};
|
|
||||||
|
|
||||||
edgeLogger.info('Triggering notification with payload', { action: 'notify_moderators_report', requestId: tracking.requestId });
|
|
||||||
|
|
||||||
// Invoke the trigger-notification function with retry
|
|
||||||
const result = await withEdgeRetry(
|
|
||||||
async () => {
|
|
||||||
const { data, error } = await supabase.functions.invoke(
|
|
||||||
'trigger-notification',
|
|
||||||
{
|
|
||||||
body: {
|
|
||||||
workflowId: template.workflow_id,
|
|
||||||
topicKey: 'moderation-reports',
|
|
||||||
payload: notificationPayload,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
const enhancedError = new Error(error.message || 'Notification trigger failed');
|
|
||||||
(enhancedError as any).status = error.status;
|
|
||||||
throw enhancedError;
|
|
||||||
}
|
|
||||||
|
|
||||||
return data;
|
|
||||||
},
|
|
||||||
{ maxAttempts: 3, baseDelay: 1000 },
|
|
||||||
tracking.requestId,
|
|
||||||
'trigger-report-notification'
|
|
||||||
);
|
|
||||||
|
|
||||||
edgeLogger.info('Notification triggered successfully', { action: 'notify_moderators_report', requestId: tracking.requestId, result });
|
|
||||||
|
|
||||||
endRequest(tracking, 200);
|
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
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);
|
|
||||||
|
|
||||||
|
if (!template) {
|
||||||
|
addSpanEvent(span, 'no_active_workflow', {});
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message,
|
error: 'No active report-alert workflow configured',
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
}),
|
||||||
{
|
{ status: 400 }
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500,
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
// Fetch reported entity name
|
||||||
|
let reportedEntityName = 'Unknown';
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (payload.reportedEntityType === 'review') {
|
||||||
|
const { data: review } = await supabase
|
||||||
|
.from('reviews')
|
||||||
|
.select('ride:rides(name), park:parks(name)')
|
||||||
|
.eq('id', payload.reportedEntityId)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
reportedEntityName = review?.ride?.name || review?.park?.name || 'Review';
|
||||||
|
} else if (payload.reportedEntityType === 'profile') {
|
||||||
|
const { data: profile } = await supabase
|
||||||
|
.from('profiles')
|
||||||
|
.select('display_name, username')
|
||||||
|
.eq('user_id', payload.reportedEntityId)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
reportedEntityName = profile?.display_name || profile?.username || 'User Profile';
|
||||||
|
} else if (payload.reportedEntityType === 'content_submission') {
|
||||||
|
const { data: metadata } = await supabase
|
||||||
|
.from('submission_metadata')
|
||||||
|
.select('metadata_value')
|
||||||
|
.eq('submission_id', payload.reportedEntityId)
|
||||||
|
.eq('metadata_key', 'name')
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
reportedEntityName = metadata?.metadata_value || 'Submission';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
addSpanEvent(span, 'entity_name_fetch_failed', {
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build enhanced notification payload
|
||||||
|
const notificationPayload = {
|
||||||
|
baseUrl: 'https://www.thrillwiki.com',
|
||||||
|
reportId: payload.reportId,
|
||||||
|
reportType: payload.reportType,
|
||||||
|
reportedEntityType: payload.reportedEntityType,
|
||||||
|
reportedEntityId: payload.reportedEntityId,
|
||||||
|
reporterName: payload.reporterName,
|
||||||
|
reason: payload.reason,
|
||||||
|
entityPreview: payload.entityPreview,
|
||||||
|
reportedEntityName,
|
||||||
|
reportedAt: payload.reportedAt,
|
||||||
|
relativeTime,
|
||||||
|
priority,
|
||||||
|
};
|
||||||
|
|
||||||
|
addSpanEvent(span, 'triggering_notification', {
|
||||||
|
workflowId: template.workflow_id,
|
||||||
|
priority
|
||||||
|
});
|
||||||
|
|
||||||
|
// Invoke the trigger-notification function with retry
|
||||||
|
const result = await withEdgeRetry(
|
||||||
|
async () => {
|
||||||
|
const { data, error } = await supabase.functions.invoke(
|
||||||
|
'trigger-notification',
|
||||||
|
{
|
||||||
|
body: {
|
||||||
|
workflowId: template.workflow_id,
|
||||||
|
topicKey: 'moderation-reports',
|
||||||
|
payload: notificationPayload,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
const enhancedError = new Error(error.message || 'Notification trigger failed');
|
||||||
|
(enhancedError as any).status = error.status;
|
||||||
|
throw enhancedError;
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
{ maxAttempts: 3, baseDelay: 1000 },
|
||||||
|
requestId,
|
||||||
|
'trigger-report-notification'
|
||||||
|
);
|
||||||
|
|
||||||
|
addSpanEvent(span, 'notification_sent', { transactionId: result?.transactionId });
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
transactionId: result?.transactionId,
|
||||||
|
payload: notificationPayload,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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 { 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 { 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';
|
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||||
|
|
||||||
interface NotificationPayload {
|
interface NotificationPayload {
|
||||||
@@ -16,275 +16,177 @@ interface NotificationPayload {
|
|||||||
is_escalated: boolean;
|
is_escalated: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
const tracking = startRequest();
|
const payload: NotificationPayload = await req.json();
|
||||||
|
const {
|
||||||
|
submission_id,
|
||||||
|
submission_type,
|
||||||
|
submitter_name,
|
||||||
|
action,
|
||||||
|
content_preview,
|
||||||
|
submitted_at,
|
||||||
|
has_photos,
|
||||||
|
item_count,
|
||||||
|
is_escalated
|
||||||
|
} = payload;
|
||||||
|
|
||||||
|
addSpanEvent(span, 'processing_moderator_notification', {
|
||||||
|
submission_id,
|
||||||
|
submission_type
|
||||||
|
});
|
||||||
|
|
||||||
|
// Calculate relative time and priority
|
||||||
|
const submittedDate = new Date(submitted_at);
|
||||||
|
const now = new Date();
|
||||||
|
const waitTimeMs = now.getTime() - submittedDate.getTime();
|
||||||
|
const waitTimeHours = waitTimeMs / (1000 * 60 * 60);
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
// Format relative time
|
||||||
return new Response(null, {
|
const relativeTime = (() => {
|
||||||
headers: {
|
const minutes = Math.floor(waitTimeMs / (1000 * 60));
|
||||||
...corsHeaders,
|
const hours = Math.floor(waitTimeMs / (1000 * 60 * 60));
|
||||||
'X-Request-ID': tracking.requestId
|
const days = Math.floor(waitTimeMs / (1000 * 60 * 60 * 24));
|
||||||
}
|
|
||||||
});
|
if (minutes < 1) return 'just now';
|
||||||
|
if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
|
||||||
|
if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
|
||||||
|
return `${days} day${days !== 1 ? 's' : ''} ago`;
|
||||||
|
})();
|
||||||
|
|
||||||
|
// Determine priority based on wait time
|
||||||
|
const priority = waitTimeHours >= 24 ? 'urgent' : 'normal';
|
||||||
|
|
||||||
|
// Get the moderation-alert workflow
|
||||||
|
const { data: workflow, error: workflowError } = await supabase
|
||||||
|
.from('notification_templates')
|
||||||
|
.select('workflow_id')
|
||||||
|
.eq('category', 'moderation')
|
||||||
|
.eq('is_active', true)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (workflowError || !workflow) {
|
||||||
|
addSpanEvent(span, 'workflow_fetch_failed', { error: workflowError?.message });
|
||||||
|
throw new Error('Workflow not found or not active');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// Generate idempotency key for duplicate prevention
|
||||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
const { data: keyData, error: keyError } = await supabase
|
||||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
.rpc('generate_notification_idempotency_key', {
|
||||||
|
p_notification_type: 'moderation_submission',
|
||||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
p_entity_id: submission_id,
|
||||||
|
p_recipient_id: '00000000-0000-0000-0000-000000000000',
|
||||||
const payload: NotificationPayload = await req.json();
|
p_event_data: { submission_type, action }
|
||||||
const {
|
|
||||||
submission_id,
|
|
||||||
submission_type,
|
|
||||||
submitter_name,
|
|
||||||
action,
|
|
||||||
content_preview,
|
|
||||||
submitted_at,
|
|
||||||
has_photos,
|
|
||||||
item_count,
|
|
||||||
is_escalated
|
|
||||||
} = payload;
|
|
||||||
|
|
||||||
edgeLogger.info('Notifying moderators about submission via topic', {
|
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
submission_id,
|
|
||||||
submission_type,
|
|
||||||
content_preview
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Calculate relative time and priority
|
const idempotencyKey = keyData || `mod_sub_${submission_id}_${Date.now()}`;
|
||||||
const submittedDate = new Date(submitted_at);
|
|
||||||
const now = new Date();
|
|
||||||
const waitTimeMs = now.getTime() - submittedDate.getTime();
|
|
||||||
const waitTimeHours = waitTimeMs / (1000 * 60 * 60);
|
|
||||||
|
|
||||||
// Format relative time
|
|
||||||
const relativeTime = (() => {
|
|
||||||
const minutes = Math.floor(waitTimeMs / (1000 * 60));
|
|
||||||
const hours = Math.floor(waitTimeMs / (1000 * 60 * 60));
|
|
||||||
const days = Math.floor(waitTimeMs / (1000 * 60 * 60 * 24));
|
|
||||||
|
|
||||||
if (minutes < 1) return 'just now';
|
|
||||||
if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
|
|
||||||
if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
|
|
||||||
return `${days} day${days !== 1 ? 's' : ''} ago`;
|
|
||||||
})();
|
|
||||||
|
|
||||||
// Determine priority based on wait time
|
|
||||||
const priority = waitTimeHours >= 24 ? 'urgent' : 'normal';
|
|
||||||
|
|
||||||
// Get the moderation-alert workflow
|
// Check for duplicate within 24h window
|
||||||
const { data: workflow, error: workflowError } = await supabase
|
const { data: existingLog, error: logCheckError } = await supabase
|
||||||
.from('notification_templates')
|
.from('notification_logs')
|
||||||
.select('workflow_id')
|
.select('id')
|
||||||
.eq('category', 'moderation')
|
.eq('idempotency_key', idempotencyKey)
|
||||||
.eq('is_active', true)
|
.gte('created_at', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())
|
||||||
.single();
|
.maybeSingle();
|
||||||
|
|
||||||
if (workflowError || !workflow) {
|
if (existingLog) {
|
||||||
const duration = endRequest(tracking);
|
// Duplicate detected
|
||||||
edgeLogger.error('Error fetching workflow', {
|
await supabase.from('notification_logs').update({
|
||||||
action: 'notify_moderators',
|
is_duplicate: true
|
||||||
requestId: tracking.requestId,
|
}).eq('id', existingLog.id);
|
||||||
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,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate idempotency key for duplicate prevention
|
addSpanEvent(span, 'duplicate_notification_prevented', {
|
||||||
const { data: keyData, error: keyError } = await supabase
|
idempotencyKey,
|
||||||
.rpc('generate_notification_idempotency_key', {
|
submission_id
|
||||||
p_notification_type: 'moderation_submission',
|
});
|
||||||
p_entity_id: submission_id,
|
|
||||||
p_recipient_id: '00000000-0000-0000-0000-000000000000', // Topic-based, use placeholder
|
|
||||||
p_event_data: { submission_type, action }
|
|
||||||
});
|
|
||||||
|
|
||||||
const idempotencyKey = keyData || `mod_sub_${submission_id}_${Date.now()}`;
|
return {
|
||||||
|
success: true,
|
||||||
// Check for duplicate within 24h window
|
message: 'Duplicate notification prevented',
|
||||||
const { data: existingLog, error: logCheckError } = await supabase
|
idempotencyKey,
|
||||||
.from('notification_logs')
|
|
||||||
.select('id')
|
|
||||||
.eq('idempotency_key', idempotencyKey)
|
|
||||||
.gte('created_at', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())
|
|
||||||
.maybeSingle();
|
|
||||||
|
|
||||||
if (existingLog) {
|
|
||||||
// Duplicate detected - log and skip
|
|
||||||
await supabase.from('notification_logs').update({
|
|
||||||
is_duplicate: true
|
|
||||||
}).eq('id', existingLog.id);
|
|
||||||
|
|
||||||
edgeLogger.info('Duplicate notification prevented', {
|
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
idempotencyKey,
|
|
||||||
submission_id
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
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,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 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', {
|
|
||||||
body: {
|
|
||||||
workflowId: workflow.workflow_id,
|
|
||||||
topicKey: 'moderation-submissions',
|
|
||||||
payload: notificationPayload,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
const enhancedError = new Error(error.message || 'Notification trigger failed');
|
|
||||||
(enhancedError as any).status = error.status;
|
|
||||||
throw enhancedError;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
},
|
|
||||||
{ maxAttempts: 3, baseDelay: 1000 },
|
|
||||||
tracking.requestId,
|
|
||||||
'trigger-submission-notification'
|
|
||||||
);
|
|
||||||
|
|
||||||
// Log notification in notification_logs with idempotency key
|
|
||||||
const { error: logError } = await supabase.from('notification_logs').insert({
|
|
||||||
user_id: '00000000-0000-0000-0000-000000000000', // Topic-based
|
|
||||||
notification_type: 'moderation_submission',
|
|
||||||
idempotency_key: idempotencyKey,
|
|
||||||
is_duplicate: false,
|
|
||||||
metadata: {
|
|
||||||
submission_id,
|
|
||||||
submission_type,
|
|
||||||
transaction_id: data?.transactionId
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
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
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
// Prepare enhanced notification payload
|
||||||
|
const notificationPayload = {
|
||||||
|
baseUrl: 'https://www.thrillwiki.com',
|
||||||
|
itemType: submission_type,
|
||||||
|
submitterName: submitter_name,
|
||||||
|
submissionId: submission_id,
|
||||||
|
action: action || 'create',
|
||||||
|
moderationUrl: 'https://www.thrillwiki.com/admin/moderation',
|
||||||
|
contentPreview: content_preview,
|
||||||
|
submittedAt: submitted_at,
|
||||||
|
relativeTime: relativeTime,
|
||||||
|
priority: priority,
|
||||||
|
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
|
||||||
|
const data = await withEdgeRetry(
|
||||||
|
async () => {
|
||||||
|
const { data: result, error } = await supabase.functions.invoke('trigger-notification', {
|
||||||
|
body: {
|
||||||
|
workflowId: workflow.workflow_id,
|
||||||
|
topicKey: 'moderation-submissions',
|
||||||
|
payload: notificationPayload,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
const enhancedError = new Error(error.message || 'Notification trigger failed');
|
||||||
|
(enhancedError as any).status = error.status;
|
||||||
|
throw enhancedError;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
{ maxAttempts: 3, baseDelay: 1000 },
|
||||||
|
requestId,
|
||||||
|
'trigger-submission-notification'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Log notification with idempotency key
|
||||||
|
const { error: logError } = await supabase.from('notification_logs').insert({
|
||||||
|
user_id: '00000000-0000-0000-0000-000000000000',
|
||||||
|
notification_type: 'moderation_submission',
|
||||||
|
idempotency_key: idempotencyKey,
|
||||||
|
is_duplicate: false,
|
||||||
|
metadata: {
|
||||||
|
submission_id,
|
||||||
|
submission_type,
|
||||||
|
transaction_id: data?.transactionId
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (logError) {
|
||||||
|
addSpanEvent(span, 'log_insertion_failed', { error: logError.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'notification_sent', {
|
||||||
|
transactionId: data?.transactionId,
|
||||||
|
topicKey: 'moderation-submissions'
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'Moderator notifications sent via topic',
|
||||||
|
topicKey: 'moderation-submissions',
|
||||||
|
transactionId: data?.transactionId,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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 { 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 { 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';
|
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||||
|
|
||||||
interface EscalationRequest {
|
interface EscalationRequest {
|
||||||
@@ -10,276 +10,219 @@ interface EscalationRequest {
|
|||||||
escalatedBy: string;
|
escalatedBy: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
const tracking = startRequest();
|
const { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
addSpanEvent(span, 'processing_escalation', { submissionId, escalatedBy });
|
||||||
return new Response(null, { headers: corsHeaders });
|
|
||||||
|
// Fetch submission details
|
||||||
|
const { data: submission, error: submissionError } = await supabase
|
||||||
|
.from('content_submissions')
|
||||||
|
.select('*, profiles:user_id(username, display_name, id)')
|
||||||
|
.eq('id', submissionId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (submissionError || !submission) {
|
||||||
|
throw new Error(`Failed to fetch submission: ${submissionError?.message || 'Not found'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// Fetch escalator details
|
||||||
const supabase = createClient(
|
const { data: escalator, error: escalatorError } = await supabase
|
||||||
Deno.env.get('SUPABASE_URL') ?? '',
|
.from('profiles')
|
||||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
.select('username, display_name')
|
||||||
);
|
.eq('user_id', escalatedBy)
|
||||||
|
.single();
|
||||||
|
|
||||||
const { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
|
if (escalatorError) {
|
||||||
|
addSpanEvent(span, 'escalator_profile_fetch_failed', { error: escalatorError.message });
|
||||||
|
}
|
||||||
|
|
||||||
edgeLogger.info('Processing escalation notification', {
|
// Fetch submission items count
|
||||||
requestId: tracking.requestId,
|
const { count: itemsCount, error: countError } = await supabase
|
||||||
submissionId,
|
.from('submission_items')
|
||||||
escalatedBy,
|
.select('*', { count: 'exact', head: true })
|
||||||
action: 'send_escalation'
|
.eq('submission_id', submissionId);
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch submission details
|
if (countError) {
|
||||||
const { data: submission, error: submissionError } = await supabase
|
addSpanEvent(span, 'items_count_fetch_failed', { error: countError.message });
|
||||||
.from('content_submissions')
|
}
|
||||||
.select('*, profiles:user_id(username, display_name, id)')
|
|
||||||
.eq('id', submissionId)
|
|
||||||
.single();
|
|
||||||
|
|
||||||
if (submissionError || !submission) {
|
// Prepare email content
|
||||||
throw new Error(`Failed to fetch submission: ${submissionError?.message || 'Not found'}`);
|
const escalatorName = escalator?.display_name || escalator?.username || 'Unknown User';
|
||||||
}
|
const submitterName = submission.profiles?.display_name || submission.profiles?.username || 'Unknown User';
|
||||||
|
const submissionType = submission.submission_type || 'Unknown';
|
||||||
|
const itemCount = itemsCount || 0;
|
||||||
|
|
||||||
// Fetch escalator details
|
const emailSubject = `🚨 Submission Escalated: ${submissionType} - ID: ${submissionId.substring(0, 8)}`;
|
||||||
const { data: escalator, error: escalatorError } = await supabase
|
|
||||||
.from('profiles')
|
const emailHtml = `
|
||||||
.select('username, display_name')
|
<!DOCTYPE html>
|
||||||
.eq('user_id', escalatedBy)
|
<html>
|
||||||
.single();
|
<head>
|
||||||
|
<style>
|
||||||
if (escalatorError) {
|
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
|
||||||
edgeLogger.error('Failed to fetch escalator profile', {
|
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
||||||
requestId: tracking.requestId,
|
.header { background-color: #ef4444; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
|
||||||
error: escalatorError.message,
|
.content { background-color: #f9fafb; padding: 20px; border: 1px solid #e5e7eb; }
|
||||||
escalatedBy
|
.info-row { margin: 10px 0; padding: 10px; background: white; border-radius: 4px; }
|
||||||
});
|
.label { font-weight: bold; color: #374151; }
|
||||||
}
|
.value { color: #1f2937; }
|
||||||
|
.reason { background-color: #fef3c7; padding: 15px; border-left: 4px solid #f59e0b; margin: 15px 0; }
|
||||||
// Fetch submission items count
|
.footer { text-align: center; padding: 20px; color: #6b7280; font-size: 14px; }
|
||||||
const { count: itemsCount, error: countError } = await supabase
|
.button { display: inline-block; padding: 12px 24px; background-color: #3b82f6; color: white; text-decoration: none; border-radius: 6px; margin: 15px 0; }
|
||||||
.from('submission_items')
|
</style>
|
||||||
.select('*', { count: 'exact', head: true })
|
</head>
|
||||||
.eq('submission_id', submissionId);
|
<body>
|
||||||
|
<div class="container">
|
||||||
if (countError) {
|
<div class="header">
|
||||||
edgeLogger.error('Failed to fetch items count', {
|
<h1 style="margin: 0;">⚠️ Submission Escalated</h1>
|
||||||
requestId: tracking.requestId,
|
<p style="margin: 5px 0 0 0;">Admin review required</p>
|
||||||
error: countError.message,
|
</div>
|
||||||
submissionId
|
|
||||||
});
|
<div class="content">
|
||||||
}
|
<div class="info-row">
|
||||||
|
<span class="label">Submission ID:</span>
|
||||||
// Prepare email content
|
<span class="value">${submissionId}</span>
|
||||||
const escalatorName = escalator?.display_name || escalator?.username || 'Unknown User';
|
|
||||||
const submitterName = submission.profiles?.display_name || submission.profiles?.username || 'Unknown User';
|
|
||||||
const submissionType = submission.submission_type || 'Unknown';
|
|
||||||
const itemCount = itemsCount || 0;
|
|
||||||
|
|
||||||
const emailSubject = `🚨 Submission Escalated: ${submissionType} - ID: ${submissionId.substring(0, 8)}`;
|
|
||||||
|
|
||||||
const emailHtml = `
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<style>
|
|
||||||
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
|
|
||||||
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
|
||||||
.header { background-color: #ef4444; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
|
|
||||||
.content { background-color: #f9fafb; padding: 20px; border: 1px solid #e5e7eb; }
|
|
||||||
.info-row { margin: 10px 0; padding: 10px; background: white; border-radius: 4px; }
|
|
||||||
.label { font-weight: bold; color: #374151; }
|
|
||||||
.value { color: #1f2937; }
|
|
||||||
.reason { background-color: #fef3c7; padding: 15px; border-left: 4px solid #f59e0b; margin: 15px 0; }
|
|
||||||
.footer { text-align: center; padding: 20px; color: #6b7280; font-size: 14px; }
|
|
||||||
.button { display: inline-block; padding: 12px 24px; background-color: #3b82f6; color: white; text-decoration: none; border-radius: 6px; margin: 15px 0; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="container">
|
|
||||||
<div class="header">
|
|
||||||
<h1 style="margin: 0;">⚠️ Submission Escalated</h1>
|
|
||||||
<p style="margin: 5px 0 0 0;">Admin review required</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="content">
|
<div class="info-row">
|
||||||
<div class="info-row">
|
<span class="label">Submission Type:</span>
|
||||||
<span class="label">Submission ID:</span>
|
<span class="value">${submissionType}</span>
|
||||||
<span class="value">${submissionId}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="info-row">
|
|
||||||
<span class="label">Submission Type:</span>
|
|
||||||
<span class="value">${submissionType}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="info-row">
|
|
||||||
<span class="label">Items Count:</span>
|
|
||||||
<span class="value">${itemCount}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="info-row">
|
|
||||||
<span class="label">Submitted By:</span>
|
|
||||||
<span class="value">${submitterName}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="info-row">
|
|
||||||
<span class="label">Escalated By:</span>
|
|
||||||
<span class="value">${escalatorName}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="reason">
|
|
||||||
<strong>📝 Escalation Reason:</strong>
|
|
||||||
<p style="margin: 10px 0 0 0;">${escalationReason}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="text-align: center;">
|
|
||||||
<a href="${Deno.env.get('SUPABASE_URL')?.replace('.supabase.co', '.lovable.app')}/admin" class="button">
|
|
||||||
Review Submission →
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="footer">
|
<div class="info-row">
|
||||||
<p>This is an automated notification from your moderation system.</p>
|
<span class="label">Items Count:</span>
|
||||||
<p>Please review and take appropriate action.</p>
|
<span class="value">${itemCount}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="info-row">
|
||||||
|
<span class="label">Submitted By:</span>
|
||||||
|
<span class="value">${submitterName}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="info-row">
|
||||||
|
<span class="label">Escalated By:</span>
|
||||||
|
<span class="value">${escalatorName}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="reason">
|
||||||
|
<strong>📝 Escalation Reason:</strong>
|
||||||
|
<p style="margin: 10px 0 0 0;">${escalationReason}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="text-align: center;">
|
||||||
|
<a href="${Deno.env.get('SUPABASE_URL')?.replace('.supabase.co', '.lovable.app')}/admin" class="button">
|
||||||
|
Review Submission →
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
`;
|
|
||||||
|
|
||||||
const emailText = `
|
|
||||||
SUBMISSION ESCALATED - Admin Review Required
|
|
||||||
|
|
||||||
Submission ID: ${submissionId}
|
|
||||||
Submission Type: ${submissionType}
|
|
||||||
Items Count: ${itemCount}
|
|
||||||
Submitted By: ${submitterName}
|
|
||||||
Escalated By: ${escalatorName}
|
|
||||||
|
|
||||||
Escalation Reason:
|
|
||||||
${escalationReason}
|
|
||||||
|
|
||||||
Please review this submission in the admin panel.
|
|
||||||
`;
|
|
||||||
|
|
||||||
// Send email via ForwardEmail API with retry
|
|
||||||
const forwardEmailApiKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
|
||||||
const adminEmail = Deno.env.get('ADMIN_EMAIL_ADDRESS');
|
|
||||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS');
|
|
||||||
|
|
||||||
if (!forwardEmailApiKey || !adminEmail || !fromEmail) {
|
|
||||||
throw new Error('Email configuration is incomplete. Please check environment variables.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const emailResult = await withEdgeRetry(
|
|
||||||
async () => {
|
|
||||||
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Authorization': 'Basic ' + btoa(forwardEmailApiKey + ':'),
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
from: fromEmail,
|
|
||||||
to: adminEmail,
|
|
||||||
subject: emailSubject,
|
|
||||||
html: emailHtml,
|
|
||||||
text: emailText,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!emailResponse.ok) {
|
|
||||||
let errorText;
|
|
||||||
try {
|
|
||||||
errorText = await emailResponse.text();
|
|
||||||
} catch (parseError) {
|
|
||||||
errorText = 'Unable to parse error response';
|
|
||||||
}
|
|
||||||
|
|
||||||
const error = new Error(`Failed to send email: ${emailResponse.status} - ${errorText}`);
|
<div class="footer">
|
||||||
(error as any).status = emailResponse.status;
|
<p>This is an automated notification from your moderation system.</p>
|
||||||
throw error;
|
<p>Please review and take appropriate action.</p>
|
||||||
}
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
|
|
||||||
const result = await emailResponse.json();
|
const emailText = `
|
||||||
return result;
|
SUBMISSION ESCALATED - Admin Review Required
|
||||||
},
|
|
||||||
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
|
|
||||||
tracking.requestId,
|
|
||||||
'send-escalation-email'
|
|
||||||
);
|
|
||||||
edgeLogger.info('Email sent successfully', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
emailId: emailResult.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update submission with notification status
|
|
||||||
const { error: updateError } = await supabase
|
|
||||||
.from('content_submissions')
|
|
||||||
.update({
|
|
||||||
escalated: true,
|
|
||||||
escalated_at: new Date().toISOString(),
|
|
||||||
escalated_by: escalatedBy,
|
|
||||||
escalation_reason: escalationReason
|
|
||||||
})
|
|
||||||
.eq('id', submissionId);
|
|
||||||
|
|
||||||
if (updateError) {
|
|
||||||
edgeLogger.error('Failed to update submission escalation status', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: updateError.message,
|
|
||||||
submissionId
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.info('Escalation notification sent', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
emailId: emailResult.id,
|
|
||||||
submissionId
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
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
|
Submission ID: ${submissionId}
|
||||||
const errorSpan = startSpan('send-escalation-notification-error', 'SERVER');
|
Submission Type: ${submissionType}
|
||||||
endSpan(errorSpan, 'error', error);
|
Items Count: ${itemCount}
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
Submitted By: ${submitterName}
|
||||||
return new Response(
|
Escalated By: ${escalatorName}
|
||||||
JSON.stringify({
|
|
||||||
error: error instanceof Error ? error.message : 'Unknown error occurred',
|
Escalation Reason:
|
||||||
details: 'Failed to send escalation notification',
|
${escalationReason}
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
Please review this submission in the admin panel.
|
||||||
{ status: 500, headers: {
|
`;
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
// Send email via ForwardEmail API with retry
|
||||||
'X-Request-ID': tracking.requestId
|
const forwardEmailApiKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||||
} }
|
const adminEmail = Deno.env.get('ADMIN_EMAIL_ADDRESS');
|
||||||
);
|
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS');
|
||||||
|
|
||||||
|
if (!forwardEmailApiKey || !adminEmail || !fromEmail) {
|
||||||
|
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', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Basic ' + btoa(forwardEmailApiKey + ':'),
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
from: fromEmail,
|
||||||
|
to: adminEmail,
|
||||||
|
subject: emailSubject,
|
||||||
|
html: emailHtml,
|
||||||
|
text: emailText,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!emailResponse.ok) {
|
||||||
|
let errorText;
|
||||||
|
try {
|
||||||
|
errorText = await emailResponse.text();
|
||||||
|
} catch {
|
||||||
|
errorText = 'Unable to parse error response';
|
||||||
|
}
|
||||||
|
|
||||||
|
const error = new Error(`Failed to send email: ${emailResponse.status} - ${errorText}`);
|
||||||
|
(error as any).status = emailResponse.status;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await emailResponse.json();
|
||||||
|
},
|
||||||
|
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
|
||||||
|
requestId,
|
||||||
|
'send-escalation-email'
|
||||||
|
);
|
||||||
|
|
||||||
|
addSpanEvent(span, 'email_sent', { emailId: emailResult.id });
|
||||||
|
|
||||||
|
// Update submission with escalation status
|
||||||
|
const { error: updateError } = await supabase
|
||||||
|
.from('content_submissions')
|
||||||
|
.update({
|
||||||
|
escalated: true,
|
||||||
|
escalated_at: new Date().toISOString(),
|
||||||
|
escalated_by: escalatedBy,
|
||||||
|
escalation_reason: escalationReason
|
||||||
|
})
|
||||||
|
.eq('id', submissionId);
|
||||||
|
|
||||||
|
if (updateError) {
|
||||||
|
addSpanEvent(span, 'submission_update_failed', { error: updateError.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'escalation_notification_complete', {
|
||||||
|
emailId: emailResult.id,
|
||||||
|
submissionId
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'Escalation notification sent successfully',
|
||||||
|
emailId: emailResult.id,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
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 { 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 { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
|
|
||||||
interface EmailRequest {
|
interface EmailRequest {
|
||||||
email: string;
|
email: string;
|
||||||
@@ -9,217 +9,131 @@ interface EmailRequest {
|
|||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { user, span, requestId }: EdgeFunctionContext) => {
|
||||||
const tracking = startRequest();
|
const { email, displayName, username }: EmailRequest = await req.json();
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
if (!email) {
|
||||||
return new Response(null, {
|
throw new Error('Email is required');
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
addSpanEvent(span, 'sending_password_email', { userId: user.id, email });
|
||||||
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();
|
const recipientName = displayName || username || 'there';
|
||||||
|
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
|
||||||
|
|
||||||
if (userError || !user) {
|
const emailHTML = `
|
||||||
const duration = endRequest(tracking);
|
<!DOCTYPE html>
|
||||||
edgeLogger.error('Authentication failed', {
|
<html>
|
||||||
action: 'send_password_email',
|
<head>
|
||||||
requestId: tracking.requestId,
|
<style>
|
||||||
duration
|
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
||||||
});
|
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
||||||
|
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
|
||||||
// Persist error to database
|
.content { background: white; padding: 30px; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
|
||||||
const authErrorSpan = startSpan('send-password-added-email-auth-error', 'SERVER');
|
.button { display: inline-block; background: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
|
||||||
endSpan(authErrorSpan, 'error', userError);
|
.security-notice { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }
|
||||||
logSpanToDatabase(authErrorSpan, tracking.requestId);
|
.footer { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e0e0e0; color: #666; font-size: 12px; }
|
||||||
throw new Error('Unauthorized');
|
ul { line-height: 1.8; }
|
||||||
}
|
</style>
|
||||||
|
</head>
|
||||||
const { email, displayName, username }: EmailRequest = await req.json();
|
<body>
|
||||||
|
<div class="container">
|
||||||
if (!email) {
|
<div class="header">
|
||||||
throw new Error('Email is required');
|
<h1>Password Successfully Added</h1>
|
||||||
}
|
|
||||||
|
|
||||||
edgeLogger.info('Sending password added email', {
|
|
||||||
action: 'send_password_email',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
email
|
|
||||||
});
|
|
||||||
|
|
||||||
const recipientName = displayName || username || 'there';
|
|
||||||
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
|
|
||||||
|
|
||||||
const emailHTML = `
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<style>
|
|
||||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
|
||||||
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
|
||||||
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
|
|
||||||
.content { background: white; padding: 30px; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
|
|
||||||
.button { display: inline-block; background: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
|
|
||||||
.security-notice { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }
|
|
||||||
.footer { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e0e0e0; color: #666; font-size: 12px; }
|
|
||||||
ul { line-height: 1.8; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="container">
|
|
||||||
<div class="header">
|
|
||||||
<h1>Password Successfully Added</h1>
|
|
||||||
</div>
|
|
||||||
<div class="content">
|
|
||||||
<p>Hi ${recipientName},</p>
|
|
||||||
|
|
||||||
<p>Great news! A password has been successfully added to your ThrillWiki account (<strong>${email}</strong>).</p>
|
|
||||||
|
|
||||||
<h3>✅ What This Means</h3>
|
|
||||||
<p>You now have an additional way to access your account. You can sign in using:</p>
|
|
||||||
<ul>
|
|
||||||
<li>Your email address and the password you just created</li>
|
|
||||||
<li>Any social login methods you've connected (Google, Discord, etc.)</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<h3>🔐 Complete Your Setup</h3>
|
|
||||||
<p><strong>Important:</strong> To complete your password setup, you need to confirm your email address.</p>
|
|
||||||
|
|
||||||
<ol style="padding-left: 20px; margin: 15px 0; line-height: 1.8;">
|
|
||||||
<li style="margin-bottom: 8px;">Check your inbox for a <strong>confirmation email</strong> from ThrillWiki</li>
|
|
||||||
<li style="margin-bottom: 8px;">Click the confirmation link in that email</li>
|
|
||||||
<li style="margin-bottom: 8px;">Return to the sign-in page and log in with your email and password</li>
|
|
||||||
</ol>
|
|
||||||
|
|
||||||
<a href="${siteUrl}/auth?email=${encodeURIComponent(email)}&message=complete-password-setup" class="button">
|
|
||||||
Go to Sign In Page
|
|
||||||
</a>
|
|
||||||
|
|
||||||
<p style="margin-top: 15px; font-size: 14px; color: #666;">
|
|
||||||
<strong>Note:</strong> You must confirm your email before you can sign in with your password.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div class="security-notice">
|
|
||||||
<strong>⚠️ Security Notice</strong><br>
|
|
||||||
If you didn't add a password to your account, please contact our support team immediately at <strong>support@thrillwiki.com</strong>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p>Thanks for being part of the ThrillWiki community!</p>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
Best regards,<br>
|
|
||||||
The ThrillWiki Team
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div class="footer">
|
|
||||||
<p>© ${new Date().getFullYear()} ThrillWiki. All rights reserved.</p>
|
|
||||||
<p>This is an automated security notification. Please do not reply to this email.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</body>
|
<div class="content">
|
||||||
</html>
|
<p>Hi ${recipientName},</p>
|
||||||
`;
|
|
||||||
|
<p>Great news! A password has been successfully added to your ThrillWiki account (<strong>${email}</strong>).</p>
|
||||||
|
|
||||||
|
<h3>✅ What This Means</h3>
|
||||||
|
<p>You now have an additional way to access your account. You can sign in using:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Your email address and the password you just created</li>
|
||||||
|
<li>Any social login methods you've connected (Google, Discord, etc.)</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3>🔐 Complete Your Setup</h3>
|
||||||
|
<p><strong>Important:</strong> To complete your password setup, you need to confirm your email address.</p>
|
||||||
|
|
||||||
|
<ol style="padding-left: 20px; margin: 15px 0; line-height: 1.8;">
|
||||||
|
<li style="margin-bottom: 8px;">Check your inbox for a <strong>confirmation email</strong> from ThrillWiki</li>
|
||||||
|
<li style="margin-bottom: 8px;">Click the confirmation link in that email</li>
|
||||||
|
<li style="margin-bottom: 8px;">Return to the sign-in page and log in with your email and password</li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
<a href="${siteUrl}/auth?email=${encodeURIComponent(email)}&message=complete-password-setup" class="button">
|
||||||
|
Go to Sign In Page
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<p style="margin-top: 15px; font-size: 14px; color: #666;">
|
||||||
|
<strong>Note:</strong> You must confirm your email before you can sign in with your password.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="security-notice">
|
||||||
|
<strong>⚠️ Security Notice</strong><br>
|
||||||
|
If you didn't add a password to your account, please contact our support team immediately at <strong>support@thrillwiki.com</strong>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p>Thanks for being part of the ThrillWiki community!</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Best regards,<br>
|
||||||
|
The ThrillWiki Team
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="footer">
|
||||||
|
<p>© ${new Date().getFullYear()} ThrillWiki. All rights reserved.</p>
|
||||||
|
<p>This is an automated security notification. Please do not reply to this email.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
|
|
||||||
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||||
|
|
||||||
if (!forwardEmailKey) {
|
if (!forwardEmailKey) {
|
||||||
edgeLogger.error('FORWARDEMAIL_API_KEY not configured', { requestId: tracking.requestId });
|
addSpanEvent(span, 'email_config_missing', {});
|
||||||
throw new Error('Email service not configured');
|
throw new Error('Email service not configured');
|
||||||
}
|
|
||||||
|
|
||||||
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
from: fromEmail,
|
|
||||||
to: email,
|
|
||||||
subject: 'Password Added to Your ThrillWiki Account',
|
|
||||||
html: emailHTML,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!emailResponse.ok) {
|
|
||||||
const errorText = await emailResponse.text();
|
|
||||||
edgeLogger.error('ForwardEmail API error', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
status: emailResponse.status,
|
|
||||||
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
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
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
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
from: fromEmail,
|
||||||
|
to: email,
|
||||||
|
subject: 'Password Added to Your ThrillWiki Account',
|
||||||
|
html: emailHTML,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!emailResponse.ok) {
|
||||||
|
const errorText = await emailResponse.text();
|
||||||
|
addSpanEvent(span, 'email_send_failed', {
|
||||||
|
status: emailResponse.status,
|
||||||
|
error: errorText
|
||||||
|
});
|
||||||
|
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'email_sent_successfully', { email });
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'Password addition email sent successfully',
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
serve(createEdgeFunction({
|
||||||
|
name: 'send-password-added-email',
|
||||||
|
requireAuth: true,
|
||||||
|
corsHeaders,
|
||||||
|
enableTracing: true,
|
||||||
|
logRequests: true,
|
||||||
|
}, handler));
|
||||||
|
|||||||
Reference in New Issue
Block a user