Refactor: Handle direct emails to admin

This commit is contained in:
gpt-engineer-app[bot]
2025-10-28 20:36:12 +00:00
parent 375db2e7d8
commit 41a3dcd02f

View File

@@ -47,19 +47,90 @@ const handler = async (req: Request): Promise<Response> => {
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' }
});
}
// Extract ticket number from thread_id (handles multiple formats)
// Formats: "TW-100000.uuid", "ticket-TW-100000", "TW-100000"
// Find or create submission
let submission = null;
let submissionError = null;
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;
@@ -69,10 +140,6 @@ const handler = async (req: Request): Promise<Response> => {
ticketNumber
});
// Find submission by thread_id or ticket_number
let submission = null;
let submissionError = null;
// Strategy 1: Try exact thread_id match
const { data: submissionByThreadId, error: error1 } = await supabase
.from('contact_submissions')
@@ -127,7 +194,7 @@ const handler = async (req: Request): Promise<Response> => {
});
}
// Verify sender email matches
// 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', {
@@ -140,14 +207,16 @@ const handler = async (req: Request): Promise<Response> => {
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,
@@ -157,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
}
});