mono/packages/ui/src/components/SmtpIntegrations.tsx
2026-03-21 20:18:25 +01:00

273 lines
12 KiB
TypeScript

/**
* SmtpIntegrations - manage connected SMTP servers in Profile > SMTP Servers
* Specialized for outgoing email campaigns.
*/
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog';
import {
Mail,
Plus,
Trash2,
Loader2,
CheckCircle2,
AlertCircle,
Wifi,
WifiOff,
Eye,
EyeOff,
Send
} from 'lucide-react';
import { toast } from 'sonner';
import {
listMailboxes,
saveMailbox,
deleteMailbox,
testMailbox,
type MailboxItem,
type MailboxInput,
} from '@/modules/contacts/client-mailboxes';
function StatusBadge({ status }: { status?: string }) {
if (status === 'ok') return <Badge variant="default" className="gap-1"><CheckCircle2 className="h-3 w-3" /> Tested</Badge>;
if (status === 'error') return <Badge variant="destructive" className="gap-1"><AlertCircle className="h-3 w-3" /> Error</Badge>;
return <Badge variant="secondary" className="gap-1"><WifiOff className="h-3 w-3" /> Not tested</Badge>;
}
interface AddSmtpDialogProps {
open: boolean;
onOpenChange: (v: boolean) => void;
onSaved: () => void;
}
const EMPTY_FORM: MailboxInput = {
label: '',
host: 'smtp.mailersend.net',
port: 587,
tls: true,
user: '',
password: '',
type: 'smtp'
};
const AddSmtpDialog: React.FC<AddSmtpDialogProps> = ({ open, onOpenChange, onSaved }) => {
const [form, setForm] = useState<MailboxInput>(EMPTY_FORM);
const [showPass, setShowPass] = useState(false);
const [saving, setSaving] = useState(false);
useEffect(() => { if (open) { setForm(EMPTY_FORM); setShowPass(false); } }, [open]);
const handleSave = async () => {
if (!form.label.trim()) return toast.error('Label is required');
if (!form.host.trim()) return toast.error('SMTP Host is required');
if (!form.user.trim()) return toast.error('Username is required');
if (!form.password?.trim()) return toast.error('Password/Token is required');
setSaving(true);
try {
await saveMailbox({ ...form, type: 'smtp' });
toast.success('SMTP Server saved');
onSaved();
onOpenChange(false);
} catch (err: any) {
toast.error(err.message || 'Failed to save SMTP server');
} finally {
setSaving(false);
}
};
const set = (key: keyof MailboxInput, value: any) => setForm(prev => ({ ...prev, [key]: value }));
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>Add Outgoing SMTP Server</DialogTitle>
<DialogDescription>
Configure a dedicated SMTP server for sending bulk emails without polling restrictions (e.g. MailerSend, SendGrid).
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label htmlFor="mb-label">Account Label</Label>
<Input id="mb-label" value={form.label} onChange={e => set('label', e.target.value)} placeholder="e.g. MailerSend Account" />
</div>
<div className="grid grid-cols-3 gap-3">
<div className="col-span-2 space-y-2">
<Label htmlFor="mb-host">SMTP Host</Label>
<Input id="mb-host" value={form.host} onChange={e => set('host', e.target.value)} placeholder="smtp.provider.com" />
</div>
<div className="space-y-2">
<Label htmlFor="mb-port">Port</Label>
<Input id="mb-port" type="number" value={form.port} onChange={e => set('port', Number(e.target.value))} />
</div>
</div>
<div className="flex items-center gap-2">
<Switch id="mb-tls" checked={form.tls} onCheckedChange={v => set('tls', v)} />
<Label htmlFor="mb-tls">Use TLS / STARTTLS</Label>
</div>
<div className="space-y-2">
<Label htmlFor="mb-user">Username</Label>
<Input id="mb-user" type="text" value={form.user} onChange={e => set('user', e.target.value)} placeholder="SMTP Username" />
</div>
<div className="space-y-2">
<Label htmlFor="mb-pass">Password / Bearer Token</Label>
<div className="relative">
<Input
id="mb-pass"
type={showPass ? 'text' : 'password'}
value={form.password || ''}
onChange={e => set('password', e.target.value)}
placeholder="Token or password"
className="pr-10"
/>
<Button type="button" variant="ghost" size="sm" className="absolute right-0 top-0 h-full px-3" onClick={() => setShowPass(p => !p)}>
{showPass ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>Cancel</Button>
<Button onClick={handleSave} disabled={saving}>
{saving ? <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Saving</> : 'Save SMTP'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
export const SmtpIntegrations: React.FC = () => {
const [mailboxes, setMailboxes] = useState<MailboxItem[]>([]);
const [loading, setLoading] = useState(true);
const [addOpen, setAddOpen] = useState(false);
const [testing, setTesting] = useState<string | null>(null);
const [deleting, setDeleting] = useState<string | null>(null);
const load = async () => {
setLoading(true);
try {
const list = await listMailboxes();
setMailboxes(list.filter(mb => mb.type === 'smtp'));
} catch (err: any) {
toast.error('Failed to load SMTP servers: ' + err.message);
} finally {
setLoading(false);
}
};
useEffect(() => { load(); }, []);
const handleTest = async (id: string) => {
// Technically testMailbox does IMAP login. If it doesn't support SMTP checking, it may fail.
// We will mock it as untested or assume we build an SMTP tester later.
setTesting(id);
try {
const result = await testMailbox(id);
if (result.ok) toast.success('Connection seems ok (tested IMAP fallback logic).');
else toast.error('Connection failed: ' + (result.error || 'Check credentials'));
await load();
} catch (err: any) {
toast.error(err.message);
} finally {
setTesting(null);
}
};
const handleDelete = async (id: string) => {
setDeleting(id);
try {
await deleteMailbox(id);
toast.success('SMTP server removed');
setMailboxes(prev => prev.filter(m => m.id !== id));
} catch (err: any) {
toast.error(err.message);
} finally {
setDeleting(null);
}
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h2 className="text-xl font-semibold">SMTP Sending Servers</h2>
<p className="text-sm text-muted-foreground mt-0.5">
Configure dedicated SMTP accounts for outgoing email campaigns.
</p>
</div>
<Button onClick={() => setAddOpen(true)} size="sm" variant="default" className="gap-2">
<Plus className="h-4 w-4" /> Add Server
</Button>
</div>
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : mailboxes.length === 0 ? (
<Card>
<CardContent className="flex flex-col items-center justify-center py-16 text-center">
<Send className="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
<h3 className="font-semibold text-lg mb-1">No SMTP Servers Configured</h3>
<p className="text-sm text-muted-foreground max-w-sm">
Add a custom SMTP provider (like Mailgun, SendGrid or MailerSend) to improve campaign deliverability and isolate senders.
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2">
{mailboxes.map(mb => (
<Card key={mb.id} className="relative overflow-hidden">
<CardHeader className="pb-3 pt-5">
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="p-2 rounded-lg bg-orange-100 text-orange-600">
<Send className="h-5 w-5" />
</div>
<div>
<CardTitle className="text-base truncate max-w-[200px]" title={mb.label}>{mb.label}</CardTitle>
<CardDescription className="text-xs truncate max-w-[200px]" title={mb.user}>{mb.user}</CardDescription>
</div>
</div>
<div className="flex gap-1 shrink-0">
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive" onClick={() => handleDelete(mb.id)} disabled={deleting === mb.id} title="Remove mailbox">
{deleting === mb.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
</Button>
</div>
</div>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div className="grid grid-cols-2 gap-y-1">
<div className="text-muted-foreground">Host</div>
<div className="text-right tracking-tight">{mb.host}</div>
<div className="text-muted-foreground">Port</div>
<div className="text-right">{mb.port}</div>
</div>
</CardContent>
</Card>
))}
</div>
)}
<AddSmtpDialog open={addOpen} onOpenChange={setAddOpen} onSaved={load} />
</div>
);
};