mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 19: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 { 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,56 +17,7 @@ interface MergeTicketsResponse {
|
|||||||
deletedTickets: string[];
|
deletedTickets: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||||
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.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse request body
|
// Parse request body
|
||||||
const { primaryTicketId, mergeTicketIds, mergeReason }: MergeTicketsRequest = await req.json();
|
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');
|
throw new Error('Maximum 10 tickets can be merged at once');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'merge_tickets_started', {
|
||||||
|
primaryTicketId,
|
||||||
|
mergeCount: mergeTicketIds.length
|
||||||
|
});
|
||||||
|
|
||||||
// Start transaction-like operations
|
// Start transaction-like operations
|
||||||
const allTicketIds = [primaryTicketId, ...mergeTicketIds];
|
const allTicketIds = [primaryTicketId, ...mergeTicketIds];
|
||||||
|
|
||||||
@@ -105,7 +60,7 @@ serve(async (req) => {
|
|||||||
throw new Error('Primary ticket not found');
|
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 =>
|
const alreadyMerged = tickets.find(t =>
|
||||||
t.merged_ticket_numbers && t.merged_ticket_numbers.length > 0
|
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`);
|
throw new Error(`Ticket ${alreadyMerged.ticket_number} has already been used in a merge`);
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Starting merge process', {
|
addSpanEvent(span, 'tickets_validated', {
|
||||||
requestId: tracking.requestId,
|
|
||||||
primaryTicket: primaryTicket.ticket_number,
|
primaryTicket: primaryTicket.ticket_number,
|
||||||
mergeTicketCount: mergeTickets.length,
|
mergeTicketCount: mergeTickets.length
|
||||||
});
|
});
|
||||||
|
|
||||||
// Step 1: Move all email threads to primary ticket
|
// Step 1: Move all email threads to primary ticket
|
||||||
edgeLogger.info('Step 1: Moving email threads', {
|
addSpanEvent(span, 'moving_email_threads', {
|
||||||
requestId: tracking.requestId,
|
|
||||||
fromTickets: mergeTickets.map(t => t.ticket_number)
|
fromTickets: mergeTickets.map(t => t.ticket_number)
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -135,21 +88,13 @@ serve(async (req) => {
|
|||||||
|
|
||||||
const threadsMovedCount = movedThreads?.length || 0;
|
const threadsMovedCount = movedThreads?.length || 0;
|
||||||
|
|
||||||
edgeLogger.info('Threads moved successfully', {
|
addSpanEvent(span, 'threads_moved', { threadsMovedCount });
|
||||||
requestId: tracking.requestId,
|
|
||||||
threadsMovedCount
|
|
||||||
});
|
|
||||||
|
|
||||||
if (threadsMovedCount === 0) {
|
if (threadsMovedCount === 0) {
|
||||||
edgeLogger.warn('No email threads found to move', {
|
addSpanEvent(span, 'no_threads_found', { mergeTicketIds });
|
||||||
requestId: tracking.requestId,
|
|
||||||
mergeTicketIds
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 2: Consolidate admin notes
|
// Step 2: Consolidate admin notes
|
||||||
edgeLogger.info('Step 2: Consolidating admin notes', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
let consolidatedNotes = primaryTicket.admin_notes || '';
|
let consolidatedNotes = primaryTicket.admin_notes || '';
|
||||||
|
|
||||||
for (const ticket of mergeTickets) {
|
for (const ticket of mergeTickets) {
|
||||||
@@ -161,8 +106,6 @@ serve(async (req) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Step 3: Recalculate metadata from consolidated threads
|
// 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
|
const { data: threadStats, error: statsError } = await supabase
|
||||||
.from('contact_email_threads')
|
.from('contact_email_threads')
|
||||||
.select('direction, created_at')
|
.select('direction, created_at')
|
||||||
@@ -178,8 +121,7 @@ serve(async (req) => {
|
|||||||
?.filter(t => t.direction === 'inbound')
|
?.filter(t => t.direction === 'inbound')
|
||||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
|
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
|
||||||
|
|
||||||
edgeLogger.info('Metadata recalculated', {
|
addSpanEvent(span, 'metadata_recalculated', {
|
||||||
requestId: tracking.requestId,
|
|
||||||
outboundCount,
|
outboundCount,
|
||||||
lastAdminResponse,
|
lastAdminResponse,
|
||||||
lastUserResponse
|
lastUserResponse
|
||||||
@@ -189,8 +131,6 @@ serve(async (req) => {
|
|||||||
const mergedTicketNumbers = mergeTickets.map(t => t.ticket_number);
|
const mergedTicketNumbers = mergeTickets.map(t => t.ticket_number);
|
||||||
|
|
||||||
// Step 4: Update primary ticket with consolidated data
|
// Step 4: Update primary ticket with consolidated data
|
||||||
edgeLogger.info('Step 4: Updating primary ticket', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
const { error: updateError } = await supabase
|
const { error: updateError } = await supabase
|
||||||
.from('contact_submissions')
|
.from('contact_submissions')
|
||||||
.update({
|
.update({
|
||||||
@@ -207,14 +147,9 @@ serve(async (req) => {
|
|||||||
|
|
||||||
if (updateError) throw updateError;
|
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
|
// Step 5: Delete merged tickets
|
||||||
edgeLogger.info('Step 5: Deleting merged tickets', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
ticketsToDelete: mergeTicketIds.length
|
|
||||||
});
|
|
||||||
|
|
||||||
const { error: deleteError } = await supabase
|
const { error: deleteError } = await supabase
|
||||||
.from('contact_submissions')
|
.from('contact_submissions')
|
||||||
.delete()
|
.delete()
|
||||||
@@ -222,14 +157,12 @@ serve(async (req) => {
|
|||||||
|
|
||||||
if (deleteError) throw deleteError;
|
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
|
// Step 6: Audit log
|
||||||
edgeLogger.info('Step 6: Creating audit log', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
const { error: auditError } = await supabase.from('admin_audit_log').insert({
|
const { error: auditError } = await supabase.from('admin_audit_log').insert({
|
||||||
admin_user_id: user.id,
|
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',
|
action: 'merge_contact_tickets',
|
||||||
details: {
|
details: {
|
||||||
primary_ticket_id: primaryTicketId,
|
primary_ticket_id: primaryTicketId,
|
||||||
@@ -243,20 +176,12 @@ serve(async (req) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (auditError) {
|
if (auditError) {
|
||||||
edgeLogger.warn('Failed to create audit log for merge', {
|
addSpanEvent(span, 'audit_log_failed', { error: auditError.message });
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: auditError.message,
|
|
||||||
primaryTicket: primaryTicket.ticket_number
|
|
||||||
});
|
|
||||||
// Don't throw - merge already succeeded
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'merge_completed', {
|
||||||
edgeLogger.info('Merge tickets completed successfully', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
primaryTicket: primaryTicket.ticket_number,
|
primaryTicket: primaryTicket.ticket_number,
|
||||||
mergedCount: mergeTickets.length,
|
mergedCount: mergeTickets.length
|
||||||
});
|
});
|
||||||
|
|
||||||
const response: MergeTicketsResponse = {
|
const response: MergeTicketsResponse = {
|
||||||
@@ -267,24 +192,14 @@ serve(async (req) => {
|
|||||||
deletedTickets: mergedTicketNumbers,
|
deletedTickets: mergedTicketNumbers,
|
||||||
};
|
};
|
||||||
|
|
||||||
return new Response(JSON.stringify(response), {
|
return response;
|
||||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
};
|
||||||
status: 200,
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
serve(createEdgeFunction({
|
||||||
const duration = endRequest(tracking);
|
name: 'merge-contact-tickets',
|
||||||
edgeLogger.error('Merge tickets failed', {
|
requireAuth: true,
|
||||||
requestId: tracking.requestId,
|
requiredRoles: ['superuser', 'admin', 'moderator'],
|
||||||
duration,
|
corsHeaders,
|
||||||
error: error instanceof Error ? error.message : 'Unknown error',
|
enableTracing: true,
|
||||||
});
|
logRequests: true,
|
||||||
|
}, handler));
|
||||||
// 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');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -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,27 +15,13 @@ interface NotificationPayload {
|
|||||||
entityPreview: string;
|
entityPreview: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
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 payload: NotificationPayload = await req.json();
|
const payload: NotificationPayload = await req.json();
|
||||||
|
|
||||||
edgeLogger.info('Processing report notification', {
|
addSpanEvent(span, 'processing_report_notification', {
|
||||||
action: 'notify_moderators_report',
|
|
||||||
reportId: payload.reportId,
|
reportId: payload.reportId,
|
||||||
reportType: payload.reportType,
|
reportType: payload.reportType,
|
||||||
reportedEntityType: payload.reportedEntityType,
|
reportedEntityType: payload.reportedEntityType
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Calculate relative time
|
// Calculate relative time
|
||||||
@@ -76,21 +62,18 @@ serve(async (req) => {
|
|||||||
.maybeSingle();
|
.maybeSingle();
|
||||||
|
|
||||||
if (templateError) {
|
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}`);
|
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!template) {
|
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(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
error: 'No active report-alert workflow configured',
|
error: 'No active report-alert workflow configured',
|
||||||
}),
|
}),
|
||||||
{
|
{ status: 400 }
|
||||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
||||||
status: 400,
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +98,6 @@ serve(async (req) => {
|
|||||||
|
|
||||||
reportedEntityName = profile?.display_name || profile?.username || 'User Profile';
|
reportedEntityName = profile?.display_name || profile?.username || 'User Profile';
|
||||||
} else if (payload.reportedEntityType === 'content_submission') {
|
} else if (payload.reportedEntityType === 'content_submission') {
|
||||||
// Query submission_metadata table for the name instead of dropped content JSONB column
|
|
||||||
const { data: metadata } = await supabase
|
const { data: metadata } = await supabase
|
||||||
.from('submission_metadata')
|
.from('submission_metadata')
|
||||||
.select('metadata_value')
|
.select('metadata_value')
|
||||||
@@ -126,7 +108,9 @@ serve(async (req) => {
|
|||||||
reportedEntityName = metadata?.metadata_value || 'Submission';
|
reportedEntityName = metadata?.metadata_value || 'Submission';
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} 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
|
// Build enhanced notification payload
|
||||||
@@ -145,7 +129,10 @@ serve(async (req) => {
|
|||||||
priority,
|
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
|
// Invoke the trigger-notification function with retry
|
||||||
const result = await withEdgeRetry(
|
const result = await withEdgeRetry(
|
||||||
@@ -170,49 +157,24 @@ serve(async (req) => {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
{ maxAttempts: 3, baseDelay: 1000 },
|
{ maxAttempts: 3, baseDelay: 1000 },
|
||||||
tracking.requestId,
|
requestId,
|
||||||
'trigger-report-notification'
|
'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 {
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
transactionId: result?.transactionId,
|
transactionId: result?.transactionId,
|
||||||
payload: notificationPayload,
|
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);
|
serve(createEdgeFunction({
|
||||||
|
name: 'notify-moderators-report',
|
||||||
return new Response(
|
requireAuth: false,
|
||||||
JSON.stringify({
|
useServiceRole: true,
|
||||||
success: false,
|
corsHeaders,
|
||||||
error: error.message,
|
enableTracing: true,
|
||||||
requestId: tracking.requestId
|
logRequests: true,
|
||||||
}),
|
}, handler));
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -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,24 +16,7 @@ interface NotificationPayload {
|
|||||||
is_escalated: boolean;
|
is_escalated: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
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 payload: NotificationPayload = await req.json();
|
const payload: NotificationPayload = await req.json();
|
||||||
const {
|
const {
|
||||||
submission_id,
|
submission_id,
|
||||||
@@ -47,12 +30,9 @@ serve(async (req) => {
|
|||||||
is_escalated
|
is_escalated
|
||||||
} = payload;
|
} = payload;
|
||||||
|
|
||||||
edgeLogger.info('Notifying moderators about submission via topic', {
|
addSpanEvent(span, 'processing_moderator_notification', {
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
submission_id,
|
submission_id,
|
||||||
submission_type,
|
submission_type
|
||||||
content_preview
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Calculate relative time and priority
|
// Calculate relative time and priority
|
||||||
@@ -85,28 +65,8 @@ serve(async (req) => {
|
|||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (workflowError || !workflow) {
|
if (workflowError || !workflow) {
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'workflow_fetch_failed', { error: workflowError?.message });
|
||||||
edgeLogger.error('Error fetching workflow', {
|
throw new Error('Workflow not found or not active');
|
||||||
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,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate idempotency key for duplicate prevention
|
// Generate idempotency key for duplicate prevention
|
||||||
@@ -114,7 +74,7 @@ serve(async (req) => {
|
|||||||
.rpc('generate_notification_idempotency_key', {
|
.rpc('generate_notification_idempotency_key', {
|
||||||
p_notification_type: 'moderation_submission',
|
p_notification_type: 'moderation_submission',
|
||||||
p_entity_id: submission_id,
|
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 }
|
p_event_data: { submission_type, action }
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -129,62 +89,46 @@ serve(async (req) => {
|
|||||||
.maybeSingle();
|
.maybeSingle();
|
||||||
|
|
||||||
if (existingLog) {
|
if (existingLog) {
|
||||||
// Duplicate detected - log and skip
|
// Duplicate detected
|
||||||
await supabase.from('notification_logs').update({
|
await supabase.from('notification_logs').update({
|
||||||
is_duplicate: true
|
is_duplicate: true
|
||||||
}).eq('id', existingLog.id);
|
}).eq('id', existingLog.id);
|
||||||
|
|
||||||
edgeLogger.info('Duplicate notification prevented', {
|
addSpanEvent(span, 'duplicate_notification_prevented', {
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
submission_id
|
submission_id
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Duplicate notification prevented',
|
message: 'Duplicate notification prevented',
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
requestId: tracking.requestId,
|
};
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prepare enhanced notification payload
|
// Prepare enhanced notification payload
|
||||||
const notificationPayload = {
|
const notificationPayload = {
|
||||||
baseUrl: 'https://www.thrillwiki.com',
|
baseUrl: 'https://www.thrillwiki.com',
|
||||||
// Basic info
|
|
||||||
itemType: submission_type,
|
itemType: submission_type,
|
||||||
submitterName: submitter_name,
|
submitterName: submitter_name,
|
||||||
submissionId: submission_id,
|
submissionId: submission_id,
|
||||||
action: action || 'create',
|
action: action || 'create',
|
||||||
moderationUrl: 'https://www.thrillwiki.com/admin/moderation',
|
moderationUrl: 'https://www.thrillwiki.com/admin/moderation',
|
||||||
|
|
||||||
// Enhanced content
|
|
||||||
contentPreview: content_preview,
|
contentPreview: content_preview,
|
||||||
|
|
||||||
// Timing information
|
|
||||||
submittedAt: submitted_at,
|
submittedAt: submitted_at,
|
||||||
relativeTime: relativeTime,
|
relativeTime: relativeTime,
|
||||||
priority: priority,
|
priority: priority,
|
||||||
|
|
||||||
// Additional metadata
|
|
||||||
hasPhotos: has_photos,
|
hasPhotos: has_photos,
|
||||||
itemCount: item_count,
|
itemCount: item_count,
|
||||||
isEscalated: is_escalated,
|
isEscalated: is_escalated,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
addSpanEvent(span, 'triggering_notification', {
|
||||||
|
workflowId: workflow.workflow_id,
|
||||||
|
priority
|
||||||
|
});
|
||||||
|
|
||||||
// Send ONE notification to the moderation-submissions topic with retry
|
// Send ONE notification to the moderation-submissions topic with retry
|
||||||
// All subscribers (moderators) will receive it automatically
|
|
||||||
const data = await withEdgeRetry(
|
const data = await withEdgeRetry(
|
||||||
async () => {
|
async () => {
|
||||||
const { data: result, error } = await supabase.functions.invoke('trigger-notification', {
|
const { data: result, error } = await supabase.functions.invoke('trigger-notification', {
|
||||||
@@ -204,13 +148,13 @@ serve(async (req) => {
|
|||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
{ maxAttempts: 3, baseDelay: 1000 },
|
{ maxAttempts: 3, baseDelay: 1000 },
|
||||||
tracking.requestId,
|
requestId,
|
||||||
'trigger-submission-notification'
|
'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({
|
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',
|
notification_type: 'moderation_submission',
|
||||||
idempotency_key: idempotencyKey,
|
idempotency_key: idempotencyKey,
|
||||||
is_duplicate: false,
|
is_duplicate: false,
|
||||||
@@ -222,69 +166,27 @@ serve(async (req) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (logError) {
|
if (logError) {
|
||||||
// Non-blocking - notification was sent successfully, log failure shouldn't fail the request
|
addSpanEvent(span, 'log_insertion_failed', { error: logError.message });
|
||||||
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);
|
addSpanEvent(span, 'notification_sent', {
|
||||||
edgeLogger.info('Successfully notified all moderators via topic', {
|
transactionId: data?.transactionId,
|
||||||
action: 'notify_moderators',
|
topicKey: 'moderation-submissions'
|
||||||
requestId: tracking.requestId,
|
|
||||||
traceId: tracking.traceId,
|
|
||||||
duration,
|
|
||||||
transactionId: data?.transactionId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Moderator notifications sent via topic',
|
message: 'Moderator notifications sent via topic',
|
||||||
topicKey: 'moderation-submissions',
|
topicKey: 'moderation-submissions',
|
||||||
transactionId: data?.transactionId,
|
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
|
serve(createEdgeFunction({
|
||||||
const errorSpan = startSpan('notify-moderators-submission-error', 'SERVER');
|
name: 'notify-moderators-submission',
|
||||||
endSpan(errorSpan, 'error', error);
|
requireAuth: false,
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
useServiceRole: true,
|
||||||
|
corsHeaders,
|
||||||
return new Response(
|
enableTracing: true,
|
||||||
JSON.stringify({
|
logRequests: true,
|
||||||
success: false,
|
}, handler));
|
||||||
error: error.message,
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -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,27 +10,10 @@ interface EscalationRequest {
|
|||||||
escalatedBy: string;
|
escalatedBy: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
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 { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
|
const { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
|
||||||
|
|
||||||
edgeLogger.info('Processing escalation notification', {
|
addSpanEvent(span, 'processing_escalation', { submissionId, escalatedBy });
|
||||||
requestId: tracking.requestId,
|
|
||||||
submissionId,
|
|
||||||
escalatedBy,
|
|
||||||
action: 'send_escalation'
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch submission details
|
// Fetch submission details
|
||||||
const { data: submission, error: submissionError } = await supabase
|
const { data: submission, error: submissionError } = await supabase
|
||||||
@@ -51,11 +34,7 @@ serve(async (req) => {
|
|||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (escalatorError) {
|
if (escalatorError) {
|
||||||
edgeLogger.error('Failed to fetch escalator profile', {
|
addSpanEvent(span, 'escalator_profile_fetch_failed', { error: escalatorError.message });
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: escalatorError.message,
|
|
||||||
escalatedBy
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch submission items count
|
// Fetch submission items count
|
||||||
@@ -65,11 +44,7 @@ serve(async (req) => {
|
|||||||
.eq('submission_id', submissionId);
|
.eq('submission_id', submissionId);
|
||||||
|
|
||||||
if (countError) {
|
if (countError) {
|
||||||
edgeLogger.error('Failed to fetch items count', {
|
addSpanEvent(span, 'items_count_fetch_failed', { error: countError.message });
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: countError.message,
|
|
||||||
submissionId
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prepare email content
|
// Prepare email content
|
||||||
@@ -175,6 +150,8 @@ serve(async (req) => {
|
|||||||
throw new Error('Email configuration is incomplete. Please check environment variables.');
|
throw new Error('Email configuration is incomplete. Please check environment variables.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'sending_escalation_email', { adminEmail });
|
||||||
|
|
||||||
const emailResult = await withEdgeRetry(
|
const emailResult = await withEdgeRetry(
|
||||||
async () => {
|
async () => {
|
||||||
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
||||||
@@ -196,7 +173,7 @@ serve(async (req) => {
|
|||||||
let errorText;
|
let errorText;
|
||||||
try {
|
try {
|
||||||
errorText = await emailResponse.text();
|
errorText = await emailResponse.text();
|
||||||
} catch (parseError) {
|
} catch {
|
||||||
errorText = 'Unable to parse error response';
|
errorText = 'Unable to parse error response';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,19 +182,16 @@ serve(async (req) => {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await emailResponse.json();
|
return await emailResponse.json();
|
||||||
return result;
|
|
||||||
},
|
},
|
||||||
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
|
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
|
||||||
tracking.requestId,
|
requestId,
|
||||||
'send-escalation-email'
|
'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
|
const { error: updateError } = await supabase
|
||||||
.from('content_submissions')
|
.from('content_submissions')
|
||||||
.update({
|
.update({
|
||||||
@@ -229,57 +203,26 @@ serve(async (req) => {
|
|||||||
.eq('id', submissionId);
|
.eq('id', submissionId);
|
||||||
|
|
||||||
if (updateError) {
|
if (updateError) {
|
||||||
edgeLogger.error('Failed to update submission escalation status', {
|
addSpanEvent(span, 'submission_update_failed', { error: updateError.message });
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: updateError.message,
|
|
||||||
submissionId
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'escalation_notification_complete', {
|
||||||
edgeLogger.info('Escalation notification sent', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
emailId: emailResult.id,
|
emailId: emailResult.id,
|
||||||
submissionId
|
submissionId
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Escalation notification sent successfully',
|
message: 'Escalation notification sent successfully',
|
||||||
emailId: emailResult.id,
|
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
|
serve(createEdgeFunction({
|
||||||
const errorSpan = startSpan('send-escalation-notification-error', 'SERVER');
|
name: 'send-escalation-notification',
|
||||||
endSpan(errorSpan, 'error', error);
|
requireAuth: false,
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
useServiceRole: true,
|
||||||
return new Response(
|
corsHeaders,
|
||||||
JSON.stringify({
|
enableTracing: true,
|
||||||
error: error instanceof Error ? error.message : 'Unknown error occurred',
|
logRequests: true,
|
||||||
details: 'Failed to send escalation notification',
|
}, handler));
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
|
||||||
{ status: 500, headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
} }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -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,58 +9,14 @@ interface EmailRequest {
|
|||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { user, span, requestId }: EdgeFunctionContext) => {
|
||||||
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 { email, displayName, username }: EmailRequest = await req.json();
|
const { email, displayName, username }: EmailRequest = await req.json();
|
||||||
|
|
||||||
if (!email) {
|
if (!email) {
|
||||||
throw new Error('Email is required');
|
throw new Error('Email is required');
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Sending password added email', {
|
addSpanEvent(span, 'sending_password_email', { userId: user.id, email });
|
||||||
action: 'send_password_email',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
email
|
|
||||||
});
|
|
||||||
|
|
||||||
const recipientName = displayName || username || 'there';
|
const recipientName = displayName || username || 'there';
|
||||||
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
|
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';
|
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');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,67 +115,25 @@ serve(async (req) => {
|
|||||||
|
|
||||||
if (!emailResponse.ok) {
|
if (!emailResponse.ok) {
|
||||||
const errorText = await emailResponse.text();
|
const errorText = await emailResponse.text();
|
||||||
edgeLogger.error('ForwardEmail API error', {
|
addSpanEvent(span, 'email_send_failed', {
|
||||||
requestId: tracking.requestId,
|
|
||||||
status: emailResponse.status,
|
status: emailResponse.status,
|
||||||
errorText
|
error: errorText
|
||||||
});
|
});
|
||||||
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
|
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'email_sent_successfully', { email });
|
||||||
edgeLogger.info('Password addition email sent successfully', {
|
|
||||||
action: 'send_password_email',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
email,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Password addition email sent successfully',
|
message: 'Password addition email sent successfully',
|
||||||
requestId: tracking.requestId,
|
};
|
||||||
}),
|
};
|
||||||
{
|
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
} catch (error) {
|
serve(createEdgeFunction({
|
||||||
const duration = endRequest(tracking);
|
name: 'send-password-added-email',
|
||||||
edgeLogger.error('Error in send-password-added-email function', {
|
requireAuth: true,
|
||||||
action: 'send_password_email',
|
corsHeaders,
|
||||||
requestId: tracking.requestId,
|
enableTracing: true,
|
||||||
duration,
|
logRequests: true,
|
||||||
error: error instanceof Error ? error.message : 'Unknown error'
|
}, handler));
|
||||||
});
|
|
||||||
|
|
||||||
// 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
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
Reference in New Issue
Block a user