Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-04-17 22:53:27 +00:00
co-authored by renee-png
parent be07ab2fa3
commit c71f7dbd87
3 changed files with 398 additions and 0 deletions
+293
View File
@@ -0,0 +1,293 @@
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 { Loader2, Mail, Send, KeyRound } 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: "",
enabled: true,
notes: "",
};
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 load = async () => {
setLoading(true);
const { data } = await supabase
.from("smtp_settings")
.select("*")
.order("updated_at", { ascending: false })
.limit(1)
.maybeSingle();
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 ?? "",
enabled: data.enabled ?? true,
notes: data.notes ?? "",
});
}
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,
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}.`,
},
});
setTesting(false);
if (error || (data as any)?.error) {
toast.error("Send failed", {
description: (error as any)?.message || (data as any)?.error,
});
return;
}
toast.success(`Test email sent to ${testTo}`);
};
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="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>
</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>
);
}
+1
View File
@@ -15,6 +15,7 @@ const TABS = [
{ to: "/settings/fees", label: "Fee schedule" },
{ to: "/settings/workflow", label: "Collections workflow" },
{ to: "/settings/workflows", label: "Task workflows" },
{ to: "/settings/smtp", label: "Email (SMTP)" },
];
function SettingsLayout() {
+104
View File
@@ -0,0 +1,104 @@
// Send an email via the firm's configured SMTP server.
// Uses denomailer (SMTP client for Deno).
import { SMTPClient } from "https://deno.land/x/denomailer@1.6.0/mod.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.49.4";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type",
};
interface SendBody {
to: string | string[];
subject: string;
html?: string;
text?: string;
cc?: string | string[];
bcc?: string | string[];
replyTo?: string;
test?: boolean;
}
Deno.serve(async (req) => {
if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
try {
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
return json({ error: "Missing authorization" }, 401);
}
const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
const anonKey = Deno.env.get("SUPABASE_ANON_KEY")!;
const serviceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
// Verify caller is authenticated
const userClient = createClient(supabaseUrl, anonKey, {
global: { headers: { Authorization: authHeader } },
});
const { data: userData, error: userErr } = await userClient.auth.getUser();
if (userErr || !userData.user) return json({ error: "Unauthorized" }, 401);
const admin = createClient(supabaseUrl, serviceKey);
// Load latest enabled SMTP settings
const { data: settings, error: setErr } = await admin
.from("smtp_settings")
.select("*")
.eq("enabled", true)
.order("updated_at", { ascending: false })
.limit(1)
.maybeSingle();
if (setErr) return json({ error: setErr.message }, 500);
if (!settings) return json({ error: "No SMTP settings configured" }, 400);
const password = Deno.env.get("SMTP_PASSWORD") ?? "";
if (!password) return json({ error: "SMTP_PASSWORD secret not set" }, 400);
const body = (await req.json()) as SendBody;
if (!body.to || !body.subject) {
return json({ error: "to and subject are required" }, 400);
}
const client = new SMTPClient({
connection: {
hostname: settings.host,
port: settings.port,
tls: !!settings.secure,
auth: settings.username
? { username: settings.username, password }
: undefined,
},
});
const fromAddr = settings.from_name
? `${settings.from_name} <${settings.from_email}>`
: settings.from_email;
await client.send({
from: fromAddr,
to: body.to,
cc: body.cc,
bcc: body.bcc,
replyTo: body.replyTo ?? settings.reply_to ?? undefined,
subject: body.subject,
content: body.text ?? "auto",
html: body.html,
});
await client.close();
return json({ ok: true });
} catch (e) {
console.error("send-smtp-email error", e);
return json({ error: e instanceof Error ? e.message : String(e) }, 500);
}
});
function json(data: unknown, status = 200) {
return new Response(JSON.stringify(data), {
status,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}