mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 10:31:13 -05:00
Approve database migration
This commit is contained in:
@@ -441,6 +441,65 @@ export type Database = {
|
||||
},
|
||||
]
|
||||
}
|
||||
contact_email_threads: {
|
||||
Row: {
|
||||
body_html: string | null
|
||||
body_text: string
|
||||
created_at: string
|
||||
direction: string
|
||||
from_email: string
|
||||
id: string
|
||||
in_reply_to: string | null
|
||||
message_id: string
|
||||
metadata: Json | null
|
||||
reference_chain: string[] | null
|
||||
sent_by: string | null
|
||||
subject: string
|
||||
submission_id: string
|
||||
to_email: string
|
||||
}
|
||||
Insert: {
|
||||
body_html?: string | null
|
||||
body_text: string
|
||||
created_at?: string
|
||||
direction: string
|
||||
from_email: string
|
||||
id?: string
|
||||
in_reply_to?: string | null
|
||||
message_id: string
|
||||
metadata?: Json | null
|
||||
reference_chain?: string[] | null
|
||||
sent_by?: string | null
|
||||
subject: string
|
||||
submission_id: string
|
||||
to_email: string
|
||||
}
|
||||
Update: {
|
||||
body_html?: string | null
|
||||
body_text?: string
|
||||
created_at?: string
|
||||
direction?: string
|
||||
from_email?: string
|
||||
id?: string
|
||||
in_reply_to?: string | null
|
||||
message_id?: string
|
||||
metadata?: Json | null
|
||||
reference_chain?: string[] | null
|
||||
sent_by?: string | null
|
||||
subject?: string
|
||||
submission_id?: string
|
||||
to_email?: string
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "contact_email_threads_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "contact_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
contact_rate_limits: {
|
||||
Row: {
|
||||
email: string
|
||||
@@ -471,12 +530,15 @@ export type Database = {
|
||||
email: string
|
||||
id: string
|
||||
ip_address_hash: string | null
|
||||
last_admin_response_at: string | null
|
||||
message: string
|
||||
name: string
|
||||
resolved_at: string | null
|
||||
resolved_by: string | null
|
||||
response_count: number | null
|
||||
status: string
|
||||
subject: string
|
||||
thread_id: string
|
||||
updated_at: string
|
||||
user_agent: string | null
|
||||
user_id: string | null
|
||||
@@ -489,12 +551,15 @@ export type Database = {
|
||||
email: string
|
||||
id?: string
|
||||
ip_address_hash?: string | null
|
||||
last_admin_response_at?: string | null
|
||||
message: string
|
||||
name: string
|
||||
resolved_at?: string | null
|
||||
resolved_by?: string | null
|
||||
response_count?: number | null
|
||||
status?: string
|
||||
subject: string
|
||||
thread_id: string
|
||||
updated_at?: string
|
||||
user_agent?: string | null
|
||||
user_id?: string | null
|
||||
@@ -507,12 +572,15 @@ export type Database = {
|
||||
email?: string
|
||||
id?: string
|
||||
ip_address_hash?: string | null
|
||||
last_admin_response_at?: string | null
|
||||
message?: string
|
||||
name?: string
|
||||
resolved_at?: string | null
|
||||
resolved_by?: string | null
|
||||
response_count?: number | null
|
||||
status?: string
|
||||
subject?: string
|
||||
thread_id?: string
|
||||
updated_at?: string
|
||||
user_agent?: string | null
|
||||
user_id?: string | null
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
@@ -10,6 +10,10 @@ import {
|
||||
Search,
|
||||
ChevronDown,
|
||||
AlertCircle,
|
||||
Send,
|
||||
ArrowUpRight,
|
||||
ArrowDownLeft,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -38,9 +42,14 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { useTheme } from '@/components/theme/ThemeProvider';
|
||||
import { useUserRole } from '@/hooks/useUserRole';
|
||||
import { handleError, handleSuccess } from '@/lib/errorHandler';
|
||||
import { logger } from '@/lib/logger';
|
||||
import { contactCategories } from '@/lib/contactValidation';
|
||||
import { invokeWithTracking } from '@/lib/edgeFunctionTracking';
|
||||
|
||||
interface ContactSubmission {
|
||||
id: string;
|
||||
@@ -57,15 +66,53 @@ interface ContactSubmission {
|
||||
admin_notes: string | null;
|
||||
resolved_at: string | null;
|
||||
resolved_by: string | null;
|
||||
thread_id: string;
|
||||
last_admin_response_at: string | null;
|
||||
response_count: number;
|
||||
}
|
||||
|
||||
interface EmailThread {
|
||||
id: string;
|
||||
created_at: string;
|
||||
message_id: string;
|
||||
from_email: string;
|
||||
to_email: string;
|
||||
subject: string;
|
||||
body_text: string;
|
||||
direction: 'inbound' | 'outbound';
|
||||
sent_by: string | null;
|
||||
}
|
||||
|
||||
export default function AdminContact() {
|
||||
const queryClient = useQueryClient();
|
||||
const { theme } = useTheme();
|
||||
const { isAdmin } = useUserRole();
|
||||
const [statusFilter, setStatusFilter] = useState<string>('all');
|
||||
const [categoryFilter, setCategoryFilter] = useState<string>('all');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectedSubmission, setSelectedSubmission] = useState<ContactSubmission | null>(null);
|
||||
const [adminNotes, setAdminNotes] = useState('');
|
||||
const [replyBody, setReplyBody] = useState('');
|
||||
const [showReplyForm, setShowReplyForm] = useState(false);
|
||||
const [emailThreads, setEmailThreads] = useState<EmailThread[]>([]);
|
||||
const [loadingThreads, setLoadingThreads] = useState(false);
|
||||
|
||||
// Admin-only access check
|
||||
if (!isAdmin()) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<Card className="max-w-md">
|
||||
<CardContent className="pt-6 text-center">
|
||||
<AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
|
||||
<h2 className="text-xl font-semibold mb-2">Access Denied</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Email response features are only available to administrators.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch contact submissions
|
||||
const { data: submissions, isLoading } = useQuery({
|
||||
@@ -101,6 +148,62 @@ export default function AdminContact() {
|
||||
},
|
||||
});
|
||||
|
||||
// Fetch email threads when submission selected
|
||||
useEffect(() => {
|
||||
if (selectedSubmission) {
|
||||
setLoadingThreads(true);
|
||||
supabase
|
||||
.from('contact_email_threads')
|
||||
.select('*')
|
||||
.eq('submission_id', selectedSubmission.id)
|
||||
.order('created_at', { ascending: true })
|
||||
.then(({ data, error }) => {
|
||||
if (error) {
|
||||
logger.error('Failed to fetch email threads', { error });
|
||||
setEmailThreads([]);
|
||||
} else {
|
||||
setEmailThreads((data as EmailThread[]) || []);
|
||||
}
|
||||
setLoadingThreads(false);
|
||||
});
|
||||
|
||||
setAdminNotes(selectedSubmission.admin_notes || '');
|
||||
setReplyBody('');
|
||||
setShowReplyForm(false);
|
||||
}
|
||||
}, [selectedSubmission]);
|
||||
|
||||
// Send reply mutation
|
||||
const sendReplyMutation = useMutation({
|
||||
mutationFn: async ({ submissionId, body }: { submissionId: string, body: string }) => {
|
||||
const { data, error } = await invokeWithTracking(
|
||||
'send-admin-email-reply',
|
||||
{ submissionId, replyBody: body },
|
||||
undefined
|
||||
);
|
||||
if (error) throw error;
|
||||
return data;
|
||||
},
|
||||
onSuccess: () => {
|
||||
handleSuccess('Reply Sent', 'Your email response has been sent successfully');
|
||||
setReplyBody('');
|
||||
setShowReplyForm(false);
|
||||
// Refetch threads
|
||||
if (selectedSubmission) {
|
||||
supabase
|
||||
.from('contact_email_threads')
|
||||
.select('*')
|
||||
.eq('submission_id', selectedSubmission.id)
|
||||
.order('created_at', { ascending: true })
|
||||
.then(({ data }) => setEmailThreads((data as EmailThread[]) || []));
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-contact-submissions'] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
handleError(error, { action: 'Send Email Reply' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update submission status
|
||||
const updateStatusMutation = useMutation({
|
||||
mutationFn: async ({
|
||||
@@ -172,6 +275,46 @@ export default function AdminContact() {
|
||||
return cat?.label || category;
|
||||
};
|
||||
|
||||
// Theme-aware EmailThreadItem component
|
||||
function EmailThreadItem({ thread }: { thread: EmailThread }) {
|
||||
const isOutbound = thread.direction === 'outbound';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`
|
||||
p-4 mb-3 rounded-lg border transition-all duration-200
|
||||
${isOutbound
|
||||
? 'bg-primary/5 border-primary/20 dark:bg-primary/10 dark:border-primary/30'
|
||||
: 'bg-muted/50 border-border dark:bg-muted/30 dark:border-border/50'
|
||||
}
|
||||
`}
|
||||
>
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{isOutbound ? (
|
||||
<ArrowUpRight className="h-4 w-4 text-primary" />
|
||||
) : (
|
||||
<ArrowDownLeft className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<span className="font-medium text-sm">
|
||||
{isOutbound ? 'Admin Reply' : thread.from_email}
|
||||
</span>
|
||||
{isOutbound && (
|
||||
<Badge variant="secondary" className="text-xs">Sent</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{format(new Date(thread.created_at), 'MMM d, yyyy h:mm a')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="text-sm leading-relaxed whitespace-pre-wrap break-words">
|
||||
{thread.body_text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const stats = {
|
||||
pending: submissions?.filter((s) => s.status === 'pending').length || 0,
|
||||
inProgress: submissions?.filter((s) => s.status === 'in_progress').length || 0,
|
||||
@@ -296,6 +439,11 @@ export default function AdminContact() {
|
||||
<h3 className="font-semibold text-lg">{submission.subject}</h3>
|
||||
{getStatusBadge(submission.status)}
|
||||
<Badge variant="outline">{getCategoryLabel(submission.category)}</Badge>
|
||||
{submission.response_count > 0 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
📧 {submission.response_count} {submission.response_count === 1 ? 'reply' : 'replies'}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-sm text-muted-foreground flex-wrap">
|
||||
<span className="flex items-center gap-1">
|
||||
@@ -306,6 +454,12 @@ export default function AdminContact() {
|
||||
<Clock className="h-3 w-3" />
|
||||
{format(new Date(submission.created_at), 'MMM d, yyyy h:mm a')}
|
||||
</span>
|
||||
{submission.last_admin_response_at && (
|
||||
<span className="flex items-center gap-1 text-primary">
|
||||
<ArrowUpRight className="h-3 w-3" />
|
||||
Last reply {format(new Date(submission.last_admin_response_at), 'MMM d')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm line-clamp-2">{submission.message}</p>
|
||||
</div>
|
||||
@@ -336,118 +490,187 @@ export default function AdminContact() {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
|
||||
{selectedSubmission && (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Mail className="h-5 w-5" />
|
||||
{selectedSubmission.subject}
|
||||
{selectedSubmission.response_count > 0 && (
|
||||
<Badge variant="secondary" className="ml-2 text-xs">
|
||||
📧 {selectedSubmission.response_count} {selectedSubmission.response_count === 1 ? 'reply' : 'replies'}
|
||||
</Badge>
|
||||
)}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Submitted {format(new Date(selectedSubmission.created_at), 'PPpp')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Tabs defaultValue="details" className="flex-1 overflow-hidden flex flex-col">
|
||||
<TabsList className="w-full justify-start">
|
||||
<TabsTrigger value="details" className="flex-1">
|
||||
Details
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="thread" className="flex-1">
|
||||
Email Thread ({emailThreads.length})
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="details" className="flex-1 overflow-y-auto">
|
||||
<div className="space-y-4 p-4">
|
||||
{/* Sender Info */}
|
||||
<div className="space-y-2">
|
||||
<Label>From</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{selectedSubmission.name}</span>
|
||||
<span className="text-muted-foreground">
|
||||
({selectedSubmission.email})
|
||||
</span>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Name</Label>
|
||||
<p className="mt-1">{selectedSubmission.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Email</Label>
|
||||
<p className="mt-1">{selectedSubmission.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category & Status */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Subject & Category */}
|
||||
<div className="space-y-2">
|
||||
<Label>Category</Label>
|
||||
<div>{getCategoryLabel(selectedSubmission.category)}</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Status</Label>
|
||||
<div>{getStatusBadge(selectedSubmission.status)}</div>
|
||||
<div className="mt-1">
|
||||
<Badge>{getCategoryLabel(selectedSubmission.category)}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Message */}
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<Label>Message</Label>
|
||||
<div className="p-4 bg-muted rounded-lg whitespace-pre-wrap">
|
||||
{selectedSubmission.message}
|
||||
</div>
|
||||
<ScrollArea className="h-40 mt-1 p-3 rounded-md border bg-muted/30">
|
||||
<p className="whitespace-pre-wrap text-sm">{selectedSubmission.message}</p>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Existing Admin Notes */}
|
||||
{selectedSubmission.admin_notes && (
|
||||
<div className="space-y-2">
|
||||
<Label>Previous Admin Notes</Label>
|
||||
<div className="p-4 bg-muted rounded-lg whitespace-pre-wrap">
|
||||
{selectedSubmission.admin_notes}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Admin Notes Input */}
|
||||
<div className="space-y-2">
|
||||
<Label>Add/Update Admin Notes</Label>
|
||||
{/* Admin Notes */}
|
||||
<div>
|
||||
<Label htmlFor="admin-notes">Admin Notes (Internal)</Label>
|
||||
<Textarea
|
||||
id="admin-notes"
|
||||
value={adminNotes}
|
||||
onChange={(e) => setAdminNotes(e.target.value)}
|
||||
placeholder="Add internal notes about this submission..."
|
||||
rows={4}
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => handleUpdateStatus('in_progress')}
|
||||
disabled={
|
||||
updateStatusMutation.isPending ||
|
||||
selectedSubmission.status === 'in_progress'
|
||||
}
|
||||
{/* Status Update */}
|
||||
<div className="flex items-center gap-4 pt-4 border-t">
|
||||
<div className="flex-1">
|
||||
<Label>Status</Label>
|
||||
<Select
|
||||
value={selectedSubmission.status}
|
||||
onValueChange={(value) => {
|
||||
handleUpdateStatus(value as 'pending' | 'in_progress' | 'resolved' | 'closed');
|
||||
}}
|
||||
>
|
||||
<Clock className="mr-2 h-4 w-4" />
|
||||
Mark In Progress
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="pending">Pending</SelectItem>
|
||||
<SelectItem value="in_progress">In Progress</SelectItem>
|
||||
<SelectItem value="resolved">Resolved</SelectItem>
|
||||
<SelectItem value="closed">Closed</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() => handleUpdateStatus(selectedSubmission.status)}
|
||||
disabled={updateStatusMutation.isPending}
|
||||
>
|
||||
{updateStatusMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Save Notes & Status
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="thread" className="flex-1 overflow-hidden flex flex-col">
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
{loadingThreads ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : emailThreads.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<Mail className="h-12 w-12 mx-auto mb-3 opacity-50" />
|
||||
<p>No email thread yet. Send the first reply below.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{emailThreads.map(thread => (
|
||||
<EmailThreadItem key={thread.id} thread={thread} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Reply Form */}
|
||||
<div className="border-t p-4 bg-background">
|
||||
{!showReplyForm ? (
|
||||
<Button
|
||||
onClick={() => setShowReplyForm(true)}
|
||||
className="w-full"
|
||||
variant="default"
|
||||
onClick={() => handleUpdateStatus('resolved')}
|
||||
disabled={
|
||||
updateStatusMutation.isPending ||
|
||||
selectedSubmission.status === 'resolved'
|
||||
}
|
||||
>
|
||||
<CheckCircle2 className="mr-2 h-4 w-4" />
|
||||
Mark Resolved
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
Reply via Email
|
||||
</Button>
|
||||
) : (
|
||||
<Card className="border-primary/20">
|
||||
<CardContent className="pt-4">
|
||||
<Label className="text-sm font-medium mb-2 block">
|
||||
Reply to {selectedSubmission.name} ({selectedSubmission.email})
|
||||
</Label>
|
||||
<Textarea
|
||||
value={replyBody}
|
||||
onChange={(e) => setReplyBody(e.target.value)}
|
||||
placeholder="Type your response here... (Min 10 characters)"
|
||||
rows={6}
|
||||
className="mb-3 resize-none"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={() => sendReplyMutation.mutate({
|
||||
submissionId: selectedSubmission.id,
|
||||
body: replyBody
|
||||
})}
|
||||
disabled={sendReplyMutation.isPending || replyBody.length < 10}
|
||||
className="flex-1"
|
||||
>
|
||||
{sendReplyMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Send Reply
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleUpdateStatus('closed')}
|
||||
disabled={
|
||||
updateStatusMutation.isPending ||
|
||||
selectedSubmission.status === 'closed'
|
||||
}
|
||||
onClick={() => {
|
||||
setShowReplyForm(false);
|
||||
setReplyBody('');
|
||||
}}
|
||||
disabled={sendReplyMutation.isPending}
|
||||
>
|
||||
<XCircle className="mr-2 h-4 w-4" />
|
||||
Close
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
asChild
|
||||
className="ml-auto"
|
||||
>
|
||||
<a href={`mailto:${selectedSubmission.email}`}>
|
||||
<Mail className="mr-2 h-4 w-4" />
|
||||
Email Sender
|
||||
</a>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
|
||||
@@ -53,3 +53,9 @@ verify_jwt = false
|
||||
|
||||
[functions.send-contact-message]
|
||||
verify_jwt = false
|
||||
|
||||
[functions.send-admin-email-reply]
|
||||
verify_jwt = true
|
||||
|
||||
[functions.receive-inbound-email]
|
||||
verify_jwt = false
|
||||
149
supabase/functions/receive-inbound-email/index.ts
Normal file
149
supabase/functions/receive-inbound-email/index.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
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 { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { createErrorResponse } from "../_shared/errorSanitizer.ts";
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
interface InboundEmailPayload {
|
||||
from: string;
|
||||
to: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
html?: string;
|
||||
messageId: string;
|
||||
inReplyTo?: string;
|
||||
references?: string[];
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
const handler = async (req: Request): Promise<Response> => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest();
|
||||
|
||||
try {
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
);
|
||||
|
||||
const payload: InboundEmailPayload = await req.json();
|
||||
const { from, to, subject, text, html, messageId, inReplyTo, references, headers } = payload;
|
||||
|
||||
edgeLogger.info('Inbound email received', {
|
||||
requestId: tracking.requestId,
|
||||
from,
|
||||
to,
|
||||
messageId
|
||||
});
|
||||
|
||||
// Extract thread ID from headers or inReplyTo
|
||||
const threadId = headers['X-Thread-ID'] ||
|
||||
(inReplyTo ? inReplyTo.replace(/<|>/g, '').split('@')[0] : null);
|
||||
|
||||
if (!threadId) {
|
||||
edgeLogger.warn('Email missing thread ID', {
|
||||
requestId: tracking.requestId,
|
||||
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();
|
||||
|
||||
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' }
|
||||
});
|
||||
}
|
||||
|
||||
// Verify sender email matches
|
||||
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 { error: insertError } = await supabase
|
||||
.from('contact_email_threads')
|
||||
.insert({
|
||||
submission_id: submission.id,
|
||||
message_id: messageId,
|
||||
in_reply_to: inReplyTo,
|
||||
reference_chain: references || [],
|
||||
from_email: senderEmail,
|
||||
to_email: to,
|
||||
subject,
|
||||
body_text: text,
|
||||
body_html: html,
|
||||
direction: 'inbound',
|
||||
metadata: {
|
||||
received_at: new Date().toISOString(),
|
||||
headers: headers
|
||||
}
|
||||
});
|
||||
|
||||
if (insertError) {
|
||||
edgeLogger.error('Failed to insert inbound email thread', {
|
||||
requestId: tracking.requestId,
|
||||
error: insertError
|
||||
});
|
||||
return createErrorResponse(insertError, 500, corsHeaders);
|
||||
}
|
||||
|
||||
// Update submission status if pending
|
||||
if (submission.status === 'pending') {
|
||||
await supabase
|
||||
.from('contact_submissions')
|
||||
.update({ status: 'in_progress' })
|
||||
.eq('id', submission.id);
|
||||
}
|
||||
|
||||
edgeLogger.info('Inbound email processed successfully', {
|
||||
requestId: tracking.requestId,
|
||||
submissionId: submission.id,
|
||||
duration: endRequest(tracking)
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
edgeLogger.error('Unexpected error in receive-inbound-email', {
|
||||
requestId: tracking.requestId,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
return createErrorResponse(error, 500, corsHeaders);
|
||||
}
|
||||
};
|
||||
|
||||
serve(handler);
|
||||
207
supabase/functions/send-admin-email-reply/index.ts
Normal file
207
supabase/functions/send-admin-email-reply/index.ts
Normal file
@@ -0,0 +1,207 @@
|
||||
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 { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
||||
import { createErrorResponse } from "../_shared/errorSanitizer.ts";
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
interface AdminReplyRequest {
|
||||
submissionId: string;
|
||||
replyBody: string;
|
||||
replySubject?: string;
|
||||
}
|
||||
|
||||
const handler = async (req: Request): Promise<Response> => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const tracking = startRequest();
|
||||
|
||||
try {
|
||||
const authHeader = req.headers.get('Authorization');
|
||||
if (!authHeader) {
|
||||
return createErrorResponse({ message: 'Unauthorized' }, 401, corsHeaders);
|
||||
}
|
||||
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_ANON_KEY')!,
|
||||
{ global: { headers: { Authorization: authHeader } } }
|
||||
);
|
||||
|
||||
const { data: { user }, error: userError } = await supabase.auth.getUser();
|
||||
if (userError || !user) {
|
||||
return createErrorResponse({ message: 'Unauthorized' }, 401, corsHeaders);
|
||||
}
|
||||
|
||||
// Verify admin role
|
||||
const { data: isAdmin, error: roleError } = await supabase
|
||||
.rpc('has_role', { _user_id: user.id, _role: 'admin' });
|
||||
|
||||
if (roleError || !isAdmin) {
|
||||
edgeLogger.warn('Non-admin attempted email reply', {
|
||||
requestId: tracking.requestId,
|
||||
userId: user.id
|
||||
});
|
||||
return createErrorResponse({ message: 'Admin access required' }, 403, corsHeaders);
|
||||
}
|
||||
|
||||
const body: AdminReplyRequest = await req.json();
|
||||
const { submissionId, replyBody, replySubject } = body;
|
||||
|
||||
if (!submissionId || !replyBody) {
|
||||
return createErrorResponse({ message: 'Missing required fields' }, 400, corsHeaders);
|
||||
}
|
||||
|
||||
if (replyBody.length < 10 || replyBody.length > 5000) {
|
||||
return createErrorResponse({
|
||||
message: 'Reply must be between 10 and 5000 characters'
|
||||
}, 400, corsHeaders);
|
||||
}
|
||||
|
||||
// Fetch submission
|
||||
const { data: submission, error: fetchError } = await supabase
|
||||
.from('contact_submissions')
|
||||
.select('id, email, name, subject, thread_id, response_count')
|
||||
.eq('id', submissionId)
|
||||
.single();
|
||||
|
||||
if (fetchError || !submission) {
|
||||
return createErrorResponse({ message: 'Submission not found' }, 404, corsHeaders);
|
||||
}
|
||||
|
||||
// Rate limiting: max 10 replies per hour
|
||||
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
|
||||
const { count } = await supabase
|
||||
.from('contact_email_threads')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('submission_id', submissionId)
|
||||
.eq('direction', 'outbound')
|
||||
.gte('created_at', oneHourAgo);
|
||||
|
||||
if (count && count >= 10) {
|
||||
return createErrorResponse({
|
||||
message: 'Rate limit exceeded. Max 10 replies per hour.'
|
||||
}, 429, corsHeaders);
|
||||
}
|
||||
|
||||
const messageId = `<${crypto.randomUUID()}@thrillwiki.com>`;
|
||||
const finalSubject = replySubject || `Re: ${submission.subject}`;
|
||||
|
||||
// Get previous message for threading
|
||||
const { data: previousMessages } = await supabase
|
||||
.from('contact_email_threads')
|
||||
.select('message_id')
|
||||
.eq('submission_id', submissionId)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1);
|
||||
|
||||
const inReplyTo = previousMessages?.[0]?.message_id || `<${submission.thread_id}@thrillwiki.com>`;
|
||||
|
||||
// Send email via ForwardEmail
|
||||
const forwardEmailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Basic ${btoa(Deno.env.get('FORWARDEMAIL_API_KEY') + ':')}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
from: 'ThrillWiki Admin <admin@thrillwiki.com>',
|
||||
to: `${submission.name} <${submission.email}>`,
|
||||
subject: finalSubject,
|
||||
text: replyBody,
|
||||
headers: {
|
||||
'Message-ID': messageId,
|
||||
'In-Reply-To': inReplyTo,
|
||||
'References': inReplyTo,
|
||||
'X-Thread-ID': submission.thread_id
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
if (!forwardEmailResponse.ok) {
|
||||
const errorText = await forwardEmailResponse.text();
|
||||
edgeLogger.error('ForwardEmail API error', {
|
||||
requestId: tracking.requestId,
|
||||
status: forwardEmailResponse.status,
|
||||
error: errorText
|
||||
});
|
||||
return createErrorResponse({ message: 'Failed to send email' }, 500, corsHeaders);
|
||||
}
|
||||
|
||||
// Insert email thread record
|
||||
const { error: insertError } = await supabase
|
||||
.from('contact_email_threads')
|
||||
.insert({
|
||||
submission_id: submissionId,
|
||||
message_id: messageId,
|
||||
in_reply_to: inReplyTo,
|
||||
reference_chain: [inReplyTo],
|
||||
from_email: 'admin@thrillwiki.com',
|
||||
to_email: submission.email,
|
||||
subject: finalSubject,
|
||||
body_text: replyBody,
|
||||
direction: 'outbound',
|
||||
sent_by: user.id,
|
||||
metadata: {
|
||||
admin_email: user.email,
|
||||
sent_at: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
if (insertError) {
|
||||
edgeLogger.error('Failed to insert email thread', {
|
||||
requestId: tracking.requestId,
|
||||
error: insertError
|
||||
});
|
||||
}
|
||||
|
||||
// Update submission
|
||||
await supabase
|
||||
.from('contact_submissions')
|
||||
.update({
|
||||
last_admin_response_at: new Date().toISOString(),
|
||||
response_count: (submission.response_count || 0) + 1,
|
||||
status: 'in_progress'
|
||||
})
|
||||
.eq('id', submissionId);
|
||||
|
||||
// Audit log
|
||||
await supabase
|
||||
.from('admin_audit_log')
|
||||
.insert({
|
||||
admin_user_id: user.id,
|
||||
target_user_id: user.id,
|
||||
action: 'send_contact_email_reply',
|
||||
details: {
|
||||
submission_id: submissionId,
|
||||
recipient: submission.email,
|
||||
subject: finalSubject
|
||||
}
|
||||
});
|
||||
|
||||
edgeLogger.info('Admin email reply sent successfully', {
|
||||
requestId: tracking.requestId,
|
||||
submissionId,
|
||||
duration: endRequest(tracking)
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, messageId }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
edgeLogger.error('Unexpected error in send-admin-email-reply', {
|
||||
requestId: tracking.requestId,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
return createErrorResponse(error, 500, corsHeaders);
|
||||
}
|
||||
};
|
||||
|
||||
serve(handler);
|
||||
@@ -0,0 +1,78 @@
|
||||
-- Add email threading support to contact submissions
|
||||
ALTER TABLE contact_submissions
|
||||
ADD COLUMN IF NOT EXISTS thread_id TEXT UNIQUE,
|
||||
ADD COLUMN IF NOT EXISTS last_admin_response_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS response_count INTEGER DEFAULT 0;
|
||||
|
||||
-- Generate thread_id for existing submissions
|
||||
UPDATE contact_submissions
|
||||
SET thread_id = 'thread_' || id::text
|
||||
WHERE thread_id IS NULL;
|
||||
|
||||
-- Make thread_id NOT NULL after backfill
|
||||
ALTER TABLE contact_submissions
|
||||
ALTER COLUMN thread_id SET NOT NULL;
|
||||
|
||||
-- Create index
|
||||
CREATE INDEX IF NOT EXISTS idx_contact_submissions_thread_id
|
||||
ON contact_submissions(thread_id);
|
||||
|
||||
-- Create contact_email_threads table
|
||||
CREATE TABLE IF NOT EXISTS contact_email_threads (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
submission_id UUID NOT NULL REFERENCES contact_submissions(id) ON DELETE CASCADE,
|
||||
|
||||
-- Email metadata
|
||||
message_id TEXT UNIQUE NOT NULL,
|
||||
in_reply_to TEXT,
|
||||
reference_chain TEXT[],
|
||||
|
||||
-- Email content
|
||||
from_email TEXT NOT NULL,
|
||||
to_email TEXT NOT NULL,
|
||||
subject TEXT NOT NULL,
|
||||
body_text TEXT NOT NULL,
|
||||
body_html TEXT,
|
||||
|
||||
-- Direction & sender tracking
|
||||
direction TEXT NOT NULL CHECK (direction IN ('inbound', 'outbound')),
|
||||
sent_by UUID REFERENCES auth.users(id),
|
||||
|
||||
-- Metadata
|
||||
metadata JSONB DEFAULT '{}'::jsonb,
|
||||
|
||||
CONSTRAINT valid_direction CHECK (
|
||||
(direction = 'outbound' AND sent_by IS NOT NULL) OR
|
||||
(direction = 'inbound' AND sent_by IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
-- Create indexes for performance
|
||||
CREATE INDEX IF NOT EXISTS idx_email_threads_submission ON contact_email_threads(submission_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_threads_message_id ON contact_email_threads(message_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_threads_created ON contact_email_threads(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_threads_direction ON contact_email_threads(direction);
|
||||
|
||||
-- Enable RLS
|
||||
ALTER TABLE contact_email_threads ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Admin-only read policy
|
||||
CREATE POLICY "Admins can view all email threads"
|
||||
ON contact_email_threads FOR SELECT
|
||||
TO authenticated
|
||||
USING (has_role(auth.uid(), 'admin'::app_role));
|
||||
|
||||
-- Admin-only write policy
|
||||
CREATE POLICY "Admins can insert email threads"
|
||||
ON contact_email_threads FOR INSERT
|
||||
TO authenticated
|
||||
WITH CHECK (has_role(auth.uid(), 'admin'::app_role));
|
||||
|
||||
-- Grant select to authenticated users (RLS will filter)
|
||||
GRANT SELECT ON contact_email_threads TO authenticated;
|
||||
GRANT INSERT ON contact_email_threads TO authenticated;
|
||||
|
||||
-- Add comment for documentation
|
||||
COMMENT ON TABLE contact_email_threads IS
|
||||
'Stores email thread history for contact form submissions. Admin-only access.';
|
||||
Reference in New Issue
Block a user