Files
mylegal-stage-law/src/routes/settings.smtp.tsx
T
2026-04-18 00:53:41 +00:00

386 lines
13 KiB
TypeScript

import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/auth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Loader2, Mail, Send, KeyRound, History } from "lucide-react";
import { toast } from "sonner";
export const Route = createFileRoute("/settings/smtp")({
component: SmtpSettingsPage,
});
const EMPTY = {
host: "",
port: "587",
secure: false,
username: "",
from_email: "",
from_name: "",
reply_to: "",
default_bcc: "",
enabled: true,
notes: "",
};
interface EmailLog {
id: string;
sent_at: string;
to_addresses: string[];
bcc_addresses: string[];
subject: string;
status: string;
error_message: string | null;
context: string | null;
}
function SmtpSettingsPage() {
const { user, isAdmin } = useAuth();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [recordId, setRecordId] = useState<string | null>(null);
const [form, setForm] = useState({ ...EMPTY });
const [testTo, setTestTo] = useState("");
const [logs, setLogs] = useState<EmailLog[]>([]);
const load = async () => {
setLoading(true);
const [settingsRes, logsRes] = await Promise.all([
supabase
.from("smtp_settings")
.select("*")
.order("updated_at", { ascending: false })
.limit(1)
.maybeSingle(),
supabase
.from("email_logs")
.select("id, sent_at, to_addresses, bcc_addresses, subject, status, error_message, context")
.order("sent_at", { ascending: false })
.limit(25),
]);
const data = settingsRes.data;
if (data) {
setRecordId(data.id);
setForm({
host: data.host ?? "",
port: String(data.port ?? 587),
secure: !!data.secure,
username: data.username ?? "",
from_email: data.from_email ?? "",
from_name: data.from_name ?? "",
reply_to: data.reply_to ?? "",
default_bcc: (data as any).default_bcc ?? "",
enabled: data.enabled ?? true,
notes: data.notes ?? "",
});
}
setLogs((logsRes.data as EmailLog[]) ?? []);
setLoading(false);
};
useEffect(() => {
if (isAdmin) load();
else setLoading(false);
}, [isAdmin]);
const update = (k: keyof typeof EMPTY, v: string | boolean) =>
setForm((f) => ({ ...f, [k]: v }));
const save = async () => {
if (!form.host || !form.from_email) {
toast.error("Host and From email are required");
return;
}
setSaving(true);
const payload = {
host: form.host.trim(),
port: parseInt(form.port, 10) || 587,
secure: form.secure,
username: form.username || null,
from_email: form.from_email.trim(),
from_name: form.from_name || null,
reply_to: form.reply_to || null,
default_bcc: form.default_bcc.trim() || null,
enabled: form.enabled,
notes: form.notes || null,
updated_by: user?.id,
};
const { error } = recordId
? await supabase.from("smtp_settings").update(payload).eq("id", recordId)
: await supabase.from("smtp_settings").insert(payload);
setSaving(false);
if (error) {
toast.error("Could not save", { description: error.message });
return;
}
toast.success("SMTP settings saved");
load();
};
const sendTest = async () => {
if (!testTo) {
toast.error("Enter a test recipient email");
return;
}
setTesting(true);
const { data, error } = await supabase.functions.invoke("send-smtp-email", {
body: {
to: testTo,
subject: "SMTP test from your firm CRM",
html: `<p>This is a test email sent from <strong>${form.from_email}</strong> via <code>${form.host}:${form.port}</code>.</p><p>If you received this, your SMTP settings are working.</p>`,
text: `Test email from ${form.from_email} via ${form.host}:${form.port}.`,
test: true,
context: "smtp_test",
},
});
setTesting(false);
if (error || (data as any)?.error) {
toast.error("Send failed", {
description: (error as any)?.message || (data as any)?.error,
});
load();
return;
}
toast.success(`Test email sent to ${testTo}`);
load();
};
if (!isAdmin) {
return (
<div className="text-sm text-muted-foreground py-8">
Only administrators can manage SMTP settings.
</div>
);
}
if (loading) {
return (
<div className="flex justify-center py-16">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="space-y-6 max-w-3xl">
<Card className="border-border/60">
<CardHeader>
<CardTitle className="font-serif text-base flex items-center gap-2">
<Mail className="h-4 w-4 text-muted-foreground" /> SMTP server
</CardTitle>
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<Field label="SMTP host *">
<Input
value={form.host}
onChange={(e) => update("host", e.target.value)}
placeholder="smtp.gmail.com"
/>
</Field>
<Field label="Port *">
<Input
type="number"
value={form.port}
onChange={(e) => update("port", e.target.value)}
placeholder="587"
/>
</Field>
<Field label="Username">
<Input
value={form.username}
onChange={(e) => update("username", e.target.value)}
placeholder="user@yourdomain.com"
/>
</Field>
<div className="space-y-1.5">
<Label className="text-xs">Password</Label>
<div className="flex items-center gap-2 h-9 px-3 rounded-md border bg-muted/30 text-xs text-muted-foreground">
<KeyRound className="h-3.5 w-3.5" />
Stored securely as the <code>SMTP_PASSWORD</code> secret.
</div>
</div>
<div className="sm:col-span-2 flex items-center justify-between rounded-md border p-3">
<div>
<div className="text-sm font-medium">Use TLS / SSL</div>
<div className="text-xs text-muted-foreground">
Enable for port 465 (implicit TLS). Leave off for 587 (STARTTLS).
</div>
</div>
<Switch
checked={form.secure}
onCheckedChange={(v) => update("secure", v)}
/>
</div>
</CardContent>
</Card>
<Card className="border-border/60">
<CardHeader>
<CardTitle className="font-serif text-base">Sender identity</CardTitle>
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<Field label="From email *">
<Input
type="email"
value={form.from_email}
onChange={(e) => update("from_email", e.target.value)}
placeholder="notifications@yourfirm.com"
/>
</Field>
<Field label="From name">
<Input
value={form.from_name}
onChange={(e) => update("from_name", e.target.value)}
placeholder="Your Firm"
/>
</Field>
<Field label="Reply-to (optional)" className="sm:col-span-2">
<Input
type="email"
value={form.reply_to}
onChange={(e) => update("reply_to", e.target.value)}
/>
</Field>
<Field label="Default BCC (optional)" className="sm:col-span-2">
<Input
value={form.default_bcc}
onChange={(e) => update("default_bcc", e.target.value)}
placeholder="archive@yourfirm.com, partner@yourfirm.com"
/>
<p className="text-xs text-muted-foreground mt-1">
Every outbound email will be silently BCC'd to these addresses (comma-separated).
</p>
</Field>
<Field label="Notes" className="sm:col-span-2">
<Textarea
rows={2}
value={form.notes}
onChange={(e) => update("notes", e.target.value)}
/>
</Field>
<div className="sm:col-span-2 flex items-center justify-between rounded-md border p-3">
<div>
<div className="text-sm font-medium">Enabled</div>
<div className="text-xs text-muted-foreground">
Disable to stop the system from sending email.
</div>
</div>
<Switch
checked={form.enabled}
onCheckedChange={(v) => update("enabled", v)}
/>
</div>
</CardContent>
</Card>
<div className="flex justify-end">
<Button onClick={save} disabled={saving}>
{saving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Save SMTP settings
</Button>
</div>
<Card className="border-border/60">
<CardHeader>
<CardTitle className="font-serif text-base flex items-center gap-2">
<Send className="h-4 w-4 text-muted-foreground" /> Send a test email
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col sm:flex-row gap-2">
<Input
type="email"
placeholder="recipient@example.com"
value={testTo}
onChange={(e) => setTestTo(e.target.value)}
className="flex-1"
/>
<Button onClick={sendTest} disabled={testing || !recordId}>
{testing ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Send className="h-4 w-4 mr-2" />
)}
Send test
</Button>
</CardContent>
</Card>
<Card className="border-border/60">
<CardHeader>
<CardTitle className="font-serif text-base flex items-center gap-2">
<History className="h-4 w-4 text-muted-foreground" /> Recent email log
</CardTitle>
</CardHeader>
<CardContent>
{logs.length === 0 ? (
<p className="text-sm text-muted-foreground">No emails sent yet.</p>
) : (
<div className="space-y-2">
{logs.map((log) => (
<div
key={log.id}
className="flex items-start justify-between gap-3 p-2 rounded-md border text-sm"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium truncate">{log.subject}</span>
<Badge
variant={log.status === "sent" ? "secondary" : "destructive"}
className="text-[10px] uppercase"
>
{log.status}
</Badge>
{log.context && (
<span className="text-[10px] text-muted-foreground">
{log.context}
</span>
)}
</div>
<div className="text-xs text-muted-foreground mt-0.5 truncate">
To: {log.to_addresses.join(", ") || "—"}
{log.bcc_addresses.length > 0 && (
<> · BCC: {log.bcc_addresses.join(", ")}</>
)}
</div>
{log.error_message && (
<div className="text-xs text-destructive mt-0.5 truncate">
{log.error_message}
</div>
)}
</div>
<div className="text-xs text-muted-foreground whitespace-nowrap">
{new Date(log.sent_at).toLocaleString()}
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
);
}
function Field({
label,
className,
children,
}: {
label: string;
className?: string;
children: React.ReactNode;
}) {
return (
<div className={`space-y-1.5 ${className ?? ""}`}>
<Label className="text-xs">{label}</Label>
{children}
</div>
);
}