Compare commits

..

2 Commits

Author SHA1 Message Date
gpt-engineer-app[bot]
41a3dcd02f Refactor: Handle direct emails to admin 2025-10-28 20:36:12 +00:00
gpt-engineer-app[bot]
375db2e7d8 Fix thread ID matching for email replies 2025-10-28 20:29:14 +00:00
2 changed files with 164 additions and 42 deletions

View File

@@ -44,59 +44,179 @@ const handler = async (req: Request): Promise<Response> => {
});
// Extract thread ID from headers or inReplyTo
const threadId = headers['X-Thread-ID'] ||
(inReplyTo ? inReplyTo.replace(/<|>/g, '').split('@')[0] : null);
let threadId = headers['X-Thread-ID'] ||
(inReplyTo ? inReplyTo.replace(/<|>/g, '').split('@')[0] : null);
if (!threadId) {
edgeLogger.warn('Email missing thread ID', {
// If no thread ID, this is a NEW direct email (not a reply)
const isNewEmail = !threadId;
if (isNewEmail) {
edgeLogger.info('New direct email received (no thread ID)', {
requestId: tracking.requestId,
from,
subject,
messageId
});
return new Response(JSON.stringify({ success: false, reason: 'no_thread_id' }), {
status: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
});
}
// Find submission by thread_id
const { data: submission, error: submissionError } = await supabase
.from('contact_submissions')
.select('id, email, status')
.eq('thread_id', threadId)
.single();
// Find or create submission
let submission = null;
let submissionError = null;
if (submissionError || !submission) {
edgeLogger.warn('Submission not found for thread ID', {
requestId: tracking.requestId,
threadId
});
return new Response(JSON.stringify({ success: false, reason: 'submission_not_found' }), {
status: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
});
}
if (isNewEmail) {
// Extract sender email
const senderEmail = from.match(/<(.+)>/)?.[1] || from;
const senderName = from.match(/^(.+?)\s*</)?.[1]?.trim() || senderEmail.split('@')[0];
// Check for existing submission from this email in last 5 minutes (avoid duplicates)
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000).toISOString();
const { data: existingRecent } = await supabase
.from('contact_submissions')
.select('id, ticket_number, thread_id, email')
.eq('email', senderEmail.toLowerCase())
.eq('subject', subject || '(No Subject)')
.gte('created_at', fiveMinutesAgo)
.maybeSingle();
if (existingRecent) {
// Use existing recent submission (duplicate email)
submission = existingRecent;
threadId = existingRecent.thread_id;
edgeLogger.info('Using existing recent submission', {
requestId: tracking.requestId,
submissionId: existingRecent.id,
ticketNumber: existingRecent.ticket_number
});
} else {
// Create new contact submission
const { data: newSubmission, error: createError } = await supabase
.from('contact_submissions')
.insert({
name: senderName,
email: senderEmail.toLowerCase(),
subject: subject || '(No Subject)',
message: text || html || '(Empty message)',
category: 'general',
status: 'pending',
user_agent: 'Email Client',
ip_address_hash: null
})
.select('id, ticket_number, email, status')
.single();
if (createError || !newSubmission) {
edgeLogger.error('Failed to create submission from direct email', {
requestId: tracking.requestId,
error: createError
});
return createErrorResponse(createError, 500, corsHeaders);
}
submission = newSubmission;
threadId = `${newSubmission.ticket_number}.${newSubmission.id}`;
// Update thread_id
await supabase
.from('contact_submissions')
.update({ thread_id: threadId })
.eq('id', newSubmission.id);
edgeLogger.info('Created new submission from direct email', {
requestId: tracking.requestId,
submissionId: newSubmission.id,
ticketNumber: newSubmission.ticket_number,
threadId
});
}
} else {
// EXISTING LOGIC: Find submission by thread_id or ticket_number
const ticketMatch = threadId.match(/(?:ticket-)?(TW-\d+)/i);
const ticketNumber = ticketMatch ? ticketMatch[1] : null;
// Verify sender email matches
const senderEmail = from.match(/<(.+)>/)?.[1] || from;
if (senderEmail.toLowerCase() !== submission.email.toLowerCase()) {
edgeLogger.warn('Sender email mismatch', {
edgeLogger.info('Thread ID extracted', {
requestId: tracking.requestId,
expected: submission.email,
received: senderEmail
});
return new Response(JSON.stringify({ success: false, reason: 'email_mismatch' }), {
status: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
rawThreadId: threadId,
ticketNumber
});
// Strategy 1: Try exact thread_id match
const { data: submissionByThreadId, error: error1 } = await supabase
.from('contact_submissions')
.select('id, email, status, ticket_number')
.eq('thread_id', threadId)
.maybeSingle();
if (submissionByThreadId) {
submission = submissionByThreadId;
} else if (ticketNumber) {
// Strategy 2: Try ticket_number match
const { data: submissionByTicket, error: error2 } = await supabase
.from('contact_submissions')
.select('id, email, status, ticket_number, thread_id')
.eq('ticket_number', ticketNumber)
.maybeSingle();
if (submissionByTicket) {
submission = submissionByTicket;
// Update thread_id if it's null or in old format
if (!submissionByTicket.thread_id || submissionByTicket.thread_id !== threadId) {
await supabase
.from('contact_submissions')
.update({ thread_id: threadId })
.eq('id', submissionByTicket.id);
edgeLogger.info('Updated submission thread_id', {
requestId: tracking.requestId,
submissionId: submissionByTicket.id,
oldThreadId: submissionByTicket.thread_id,
newThreadId: threadId
});
}
} else {
submissionError = error2;
}
} else {
submissionError = error1;
}
if (submissionError || !submission) {
edgeLogger.warn('Submission not found for thread ID', {
requestId: tracking.requestId,
threadId,
ticketNumber,
error: submissionError
});
return new Response(JSON.stringify({ success: false, reason: 'submission_not_found' }), {
status: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
});
}
// Verify sender email matches (only for existing submissions)
const senderEmail = from.match(/<(.+)>/)?.[1] || from;
if (senderEmail.toLowerCase() !== submission.email.toLowerCase()) {
edgeLogger.warn('Sender email mismatch', {
requestId: tracking.requestId,
expected: submission.email,
received: senderEmail
});
return new Response(JSON.stringify({ success: false, reason: 'email_mismatch' }), {
status: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
});
}
}
// Insert email thread record
const senderEmail = from.match(/<(.+)>/)?.[1] || from;
const { error: insertError } = await supabase
.from('contact_email_threads')
.insert({
submission_id: submission.id,
message_id: messageId,
in_reply_to: inReplyTo,
in_reply_to: inReplyTo || null,
reference_chain: references || [],
from_email: senderEmail,
to_email: to,
@@ -106,7 +226,8 @@ const handler = async (req: Request): Promise<Response> => {
direction: 'inbound',
metadata: {
received_at: new Date().toISOString(),
headers: headers
headers: headers,
is_new_ticket: isNewEmail
}
});

View File

@@ -232,6 +232,13 @@ const handler = async (req: Request): Promise<Response> => {
}
});
// Update thread_id with Message-ID format (always, not just when email is sent)
const threadId = `${ticketNumber}.${submission.id}`;
await supabase
.from('contact_submissions')
.update({ thread_id: threadId })
.eq('id', submission.id);
if (forwardEmailKey) {
// Send admin notification
fetch('https://api.forwardemail.net/v1/emails', {
@@ -302,12 +309,6 @@ The ThrillWiki Team`,
}).catch(err => {
edgeLogger.error('Failed to send confirmation email', { requestId, error: err.message });
});
// Update thread_id with ticket number
await supabase
.from('contact_submissions')
.update({ thread_id: `ticket-${ticketNumber}` })
.eq('id', submission.id);
}
const duration = Date.now() - startTime;