Modified by www.SourceFiles.app

This commit is contained in:
2026-08-07 04:13:12 +00:00
parent ef71239759
commit d705da8d3a
-689
View File
@@ -1,689 +0,0 @@
import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { Button } from "@/components/ui/button";
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 {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Mail,
Inbox,
Loader2,
Paperclip,
RefreshCw,
Reply,
Send,
Settings,
Trash2,
AlertTriangle,
} from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import {
getMailSetup,
getAttachment,
getMessage,
listFolders,
listMessages,
myMailboxStatus,
removeUserMailbox,
saveMailSettings,
sendMail,
setUserMailbox,
type MailSettings,
} from "@/lib/mail.functions";
export const Route = createFileRoute("/_authenticated/mail")({
head: () => ({ meta: [{ title: "Mail — School Portal" }] }),
component: MailPage,
});
const fmt = (iso: string | null) =>
iso ? new Date(iso).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }) : "—";
function MailPage() {
const { roles } = useAuth();
const isAdmin = roles.includes("admin");
const qc = useQueryClient();
const [folder, setFolder] = useState("INBOX");
const [openUid, setOpenUid] = useState<number | null>(null);
const [composing, setComposing] = useState<null | {
to: string;
subject: string;
inReplyTo: string | null;
references: string | null;
}>(null);
const [setupOpen, setSetupOpen] = useState(false);
const status = useQuery({
queryKey: ["mail-status"],
queryFn: () => myMailboxStatus({}),
});
const folders = useQuery({
queryKey: ["mail-folders"],
enabled: !!status.data?.email,
queryFn: () => listFolders({}),
retry: false,
});
const messages = useQuery({
queryKey: ["mail-messages", folder],
enabled: !!status.data?.email,
queryFn: () => listMessages({ data: { folder, limit: 40 } }),
retry: false,
});
if (status.isLoading) {
return (
<div className="p-8 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading mail…
</div>
);
}
// Nothing set up yet: tell the admin what to do, and tell everyone else who to ask.
if (!status.data?.email) {
return (
<div className="p-8 max-w-2xl">
<h1 className="text-2xl font-semibold flex items-center gap-2">
<Mail className="h-6 w-6 text-primary" /> Mail
</h1>
<div className="bg-card border rounded-lg p-6 mt-6 space-y-3">
{!status.data?.serverConfigured ? (
<>
<div className="font-medium">The mail server isn't configured yet.</div>
<p className="text-sm text-muted-foreground">
{isAdmin
? "Enter your provider's IMAP and SMTP details, then give each staff member their mailbox login."
: "An administrator needs to set up the school mail server before you can use this page."}
</p>
</>
) : (
<>
<div className="font-medium">You don't have a mailbox yet.</div>
<p className="text-sm text-muted-foreground">
The mail server is configured, but no mailbox has been assigned to your account.
{isAdmin ? " Assign one below." : " Ask an administrator to set one up."}
</p>
</>
)}
{isAdmin && (
<Button onClick={() => setSetupOpen(true)}>
<Settings className="h-4 w-4 mr-1" /> Mail setup
</Button>
)}
</div>
{setupOpen && (
<MailSetupDialog
onClose={() => {
setSetupOpen(false);
qc.invalidateQueries({ queryKey: ["mail-status"] });
}}
/>
)}
</div>
);
}
const err = (messages.error ?? folders.error) as Error | undefined;
return (
<div className="p-6 md:p-8">
<div className="flex items-center justify-between flex-wrap gap-2">
<div>
<h1 className="text-2xl font-semibold flex items-center gap-2">
<Mail className="h-6 w-6 text-primary" /> Mail
</h1>
<p className="text-muted-foreground text-sm mt-1">{status.data.email}</p>
</div>
<div className="flex gap-2">
<Button
size="sm"
variant="outline"
onClick={() => qc.invalidateQueries({ queryKey: ["mail-messages", folder] })}
disabled={messages.isFetching}
>
<RefreshCw className={`h-4 w-4 mr-1 ${messages.isFetching ? "animate-spin" : ""}`} />{" "}
Refresh
</Button>
<Button
size="sm"
onClick={() => setComposing({ to: "", subject: "", inReplyTo: null, references: null })}
>
<Send className="h-4 w-4 mr-1" /> Compose
</Button>
{isAdmin && (
<Button size="sm" variant="ghost" onClick={() => setSetupOpen(true)}>
<Settings className="h-4 w-4" />
</Button>
)}
</div>
</div>
{err && (
<div className="mt-4 border rounded-md p-3 flex items-start gap-2 text-sm">
<AlertTriangle className="h-4 w-4 text-destructive shrink-0 mt-0.5" />
<div>
<div className="font-medium">Couldn't reach the mail server</div>
<div className="text-muted-foreground text-xs mt-0.5">{err.message}</div>
</div>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-[200px_1fr] gap-4 mt-6">
<div className="bg-card border rounded-lg p-2 h-fit">
{(folders.data ?? [{ path: "INBOX", name: "Inbox", specialUse: null }]).map((f) => (
<button
key={f.path}
onClick={() => {
setFolder(f.path);
setOpenUid(null);
}}
className={`w-full text-left px-3 py-1.5 rounded-md text-sm flex items-center gap-2 ${
folder === f.path ? "bg-primary text-primary-foreground" : "hover:bg-muted"
}`}
>
<Inbox className="h-3.5 w-3.5 shrink-0" />
<span className="truncate">{f.name}</span>
</button>
))}
</div>
<div className="min-w-0">
{messages.isLoading ? (
<div className="bg-card border rounded-lg p-6 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading messages…
</div>
) : (messages.data?.messages ?? []).length === 0 ? (
<div className="bg-card border rounded-lg p-6 text-sm text-muted-foreground">
No messages in this folder.
</div>
) : (
<div className="bg-card border rounded-lg divide-y">
{(messages.data?.messages ?? []).map((m) => (
<button
key={m.uid}
onClick={() => setOpenUid(m.uid)}
className="w-full text-left p-3 hover:bg-muted/40 flex gap-3 items-start"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className={`truncate text-sm ${m.seen ? "" : "font-semibold"}`}>
{m.from || "(unknown sender)"}
</span>
{!m.seen && (
<Badge variant="default" className="h-4 px-1 text-[10px]">
New
</Badge>
)}
{m.hasAttachments && (
<Paperclip className="h-3 w-3 text-muted-foreground shrink-0" />
)}
</div>
<div className={`truncate text-sm ${m.seen ? "text-muted-foreground" : ""}`}>
{m.subject}
</div>
</div>
<span className="text-xs text-muted-foreground shrink-0">{fmt(m.date)}</span>
</button>
))}
</div>
)}
{messages.data ? (
<p className="text-xs text-muted-foreground mt-2">
Showing {messages.data.messages.length} of {messages.data.total} in{" "}
{messages.data.folder}.
</p>
) : null}
</div>
</div>
{openUid !== null && (
<MessageDialog
folder={folder}
uid={openUid}
onClose={() => {
setOpenUid(null);
qc.invalidateQueries({ queryKey: ["mail-messages", folder] });
}}
onReply={(c) => {
setOpenUid(null);
setComposing(c);
}}
/>
)}
{composing && <ComposeDialog initial={composing} onClose={() => setComposing(null)} />}
{setupOpen && (
<MailSetupDialog
onClose={() => {
setSetupOpen(false);
qc.invalidateQueries({ queryKey: ["mail-status"] });
}}
/>
)}
</div>
);
}
function MessageDialog({
folder,
uid,
onClose,
onReply,
}: {
folder: string;
uid: number;
onClose: () => void;
onReply: (c: {
to: string;
subject: string;
inReplyTo: string | null;
references: string | null;
}) => void;
}) {
const { data, isLoading, error } = useQuery({
queryKey: ["mail-message", folder, uid],
queryFn: () => getMessage({ data: { folder, uid } }),
retry: false,
});
const download = async (filename: string) => {
try {
const a = await getAttachment({ data: { folder, uid, filename } });
const bytes = Uint8Array.from(atob(a.base64), (ch) => ch.charCodeAt(0));
const url = URL.createObjectURL(new Blob([bytes], { type: a.contentType }));
const el = document.createElement("a");
el.href = url;
el.download = a.filename;
el.click();
URL.revokeObjectURL(url);
} catch (e) {
toast.error((e as Error).message);
}
};
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-3xl max-h-[85vh] overflow-auto">
<DialogHeader>
<DialogTitle className="pr-8">{data?.subject ?? "Message"}</DialogTitle>
</DialogHeader>
{isLoading && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading…
</div>
)}
{error && <p className="text-sm text-destructive">{(error as Error).message}</p>}
{data && (
<div className="space-y-3">
<div className="text-sm space-y-0.5 border-b pb-2">
<div>
<span className="text-muted-foreground">From:</span> {data.from}
</div>
<div>
<span className="text-muted-foreground">To:</span> {data.to}
</div>
{data.cc && (
<div>
<span className="text-muted-foreground">Cc:</span> {data.cc}
</div>
)}
<div className="text-xs text-muted-foreground">{fmt(data.date)}</div>
</div>
{data.attachments.length > 0 && (
<div className="flex flex-wrap gap-2">
{data.attachments.map((a) => (
<Button
key={a.filename}
size="sm"
variant="outline"
onClick={() => download(a.filename)}
>
<Paperclip className="h-3.5 w-3.5 mr-1" /> {a.filename}
<span className="text-xs text-muted-foreground ml-1">
{(a.size / 1024).toFixed(0)} KB
</span>
</Button>
))}
</div>
)}
{/* Remote HTML is deliberately not rendered — an <iframe> or
dangerouslySetInnerHTML here would execute sender-controlled
markup and leak read receipts via tracking pixels. */}
<pre className="text-sm whitespace-pre-wrap break-words font-sans">
{data.text || "(no plain-text body)"}
</pre>
{!data.text && data.html && (
<p className="text-xs text-muted-foreground">
This message is HTML-only. It is shown as text for safety.
</p>
)}
<Button
size="sm"
onClick={() =>
onReply({
to: data.from,
subject: data.subject.startsWith("Re:") ? data.subject : `Re: ${data.subject}`,
inReplyTo: data.messageId,
references: [data.references, data.messageId].filter(Boolean).join(" ") || null,
})
}
>
<Reply className="h-4 w-4 mr-1" /> Reply
</Button>
</div>
)}
</DialogContent>
</Dialog>
);
}
function ComposeDialog({
initial,
onClose,
}: {
initial: { to: string; subject: string; inReplyTo: string | null; references: string | null };
onClose: () => void;
}) {
const [to, setTo] = useState(initial.to);
const [cc, setCc] = useState("");
const [subject, setSubject] = useState(initial.subject);
const [body, setBody] = useState("");
const send = useMutation({
mutationFn: () =>
sendMail({
data: {
to,
cc,
subject,
body,
inReplyTo: initial.inReplyTo,
references: initial.references,
},
}),
onSuccess: () => {
toast.success("Message sent");
onClose();
},
onError: (e: Error) => toast.error(e.message),
});
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{initial.inReplyTo ? "Reply" : "New message"}</DialogTitle>
</DialogHeader>
<div className="space-y-3">
<div>
<Label className="text-xs">To</Label>
<Input
value={to}
onChange={(e) => setTo(e.target.value)}
placeholder="name@example.com"
/>
</div>
<div>
<Label className="text-xs">Cc</Label>
<Input value={cc} onChange={(e) => setCc(e.target.value)} />
</div>
<div>
<Label className="text-xs">Subject</Label>
<Input value={subject} onChange={(e) => setSubject(e.target.value)} />
</div>
<div>
<Label className="text-xs">Message</Label>
<Textarea rows={10} value={body} onChange={(e) => setBody(e.target.value)} />
</div>
<div className="flex gap-2">
<Button onClick={() => send.mutate()} disabled={!to || send.isPending}>
{send.isPending ? "Sending…" : "Send"}
</Button>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
</div>
</div>
</DialogContent>
</Dialog>
);
}
// ── Admin setup: server details + per-user mailbox provisioning ──────────────
function MailSetupDialog({ onClose }: { onClose: () => void }) {
const qc = useQueryClient();
const setup = useQuery({
queryKey: ["mail-setup"],
queryFn: () => getMailSetup({}),
retry: false,
});
const [s, setS] = useState<MailSettings | null>(null);
const current: MailSettings = s ??
setup.data?.settings ?? {
imap_host: "",
imap_port: 993,
imap_secure: true,
smtp_host: "",
smtp_port: 587,
smtp_secure: false,
};
const [box, setBox] = useState({ userId: "", email: "", password: "" });
const saveSettings = useMutation({
mutationFn: () => saveMailSettings({ data: current }),
onSuccess: () => {
toast.success("Mail server saved");
qc.invalidateQueries({ queryKey: ["mail-setup"] });
qc.invalidateQueries({ queryKey: ["mail-status"] });
},
onError: (e: Error) => toast.error(e.message),
});
const assign = useMutation({
mutationFn: () => setUserMailbox({ data: box }),
onSuccess: () => {
toast.success("Mailbox verified and saved");
setBox({ userId: "", email: "", password: "" });
qc.invalidateQueries({ queryKey: ["mail-setup"] });
qc.invalidateQueries({ queryKey: ["mail-status"] });
},
onError: (e: Error) => toast.error(e.message),
});
const remove = useMutation({
mutationFn: (userId: string) => removeUserMailbox({ data: { userId } }),
onSuccess: () => {
toast.success("Mailbox removed");
qc.invalidateQueries({ queryKey: ["mail-setup"] });
qc.invalidateQueries({ queryKey: ["mail-status"] });
},
onError: (e: Error) => toast.error(e.message),
});
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-auto">
<DialogHeader>
<DialogTitle>Mail setup</DialogTitle>
<DialogDescription>
One mail server for the school, with a separate mailbox login per staff member.
</DialogDescription>
</DialogHeader>
{setup.error && (
<p className="text-sm text-destructive">{(setup.error as Error).message}</p>
)}
{setup.data && !setup.data.keyConfigured && (
<div className="border rounded-md p-3 flex items-start gap-2 text-xs">
<AlertTriangle className="h-4 w-4 text-destructive shrink-0 mt-0.5" />
<span>
<strong>MAIL_CRED_KEY is not set on the server.</strong> Mailbox passwords are sealed
with it, so assigning a mailbox will fail until it exists. Generate one with{" "}
<code>openssl rand -base64 32</code> and add it to <code>.env.secret</code>.
</span>
</div>
)}
<div className="space-y-3">
<div className="font-medium text-sm">Server</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<div className="md:col-span-2">
<Label className="text-xs">IMAP host</Label>
<Input
value={current.imap_host}
onChange={(e) => setS({ ...current, imap_host: e.target.value })}
placeholder="imap.provider.com"
/>
</div>
<div>
<Label className="text-xs">IMAP port</Label>
<Input
inputMode="numeric"
value={String(current.imap_port)}
onChange={(e) => setS({ ...current, imap_port: Number(e.target.value) || 0 })}
/>
</div>
</div>
<div className="flex items-center justify-between max-w-sm">
<Label className="text-xs">IMAP uses TLS on connect (port 993)</Label>
<Switch
checked={current.imap_secure}
onCheckedChange={(v) => setS({ ...current, imap_secure: v })}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<div className="md:col-span-2">
<Label className="text-xs">SMTP host</Label>
<Input
value={current.smtp_host}
onChange={(e) => setS({ ...current, smtp_host: e.target.value })}
placeholder="smtp.provider.com"
/>
</div>
<div>
<Label className="text-xs">SMTP port</Label>
<Input
inputMode="numeric"
value={String(current.smtp_port)}
onChange={(e) => setS({ ...current, smtp_port: Number(e.target.value) || 0 })}
/>
</div>
</div>
<div className="flex items-center justify-between max-w-sm">
<Label className="text-xs">SMTP uses TLS on connect (465; off = STARTTLS on 587)</Label>
<Switch
checked={current.smtp_secure}
onCheckedChange={(v) => setS({ ...current, smtp_secure: v })}
/>
</div>
<Button
size="sm"
onClick={() => saveSettings.mutate()}
disabled={!current.imap_host || !current.smtp_host || saveSettings.isPending}
>
{saveSettings.isPending ? "Saving…" : "Save server settings"}
</Button>
</div>
<div className="border-t pt-4 space-y-3">
<div className="font-medium text-sm">Mailboxes</div>
<div className="border rounded-lg divide-y">
{(setup.data?.mailboxes ?? []).map((m) => (
<div key={m.user_id} className="p-3 flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-sm font-medium truncate">{m.full_name || m.email}</div>
<div className="text-xs text-muted-foreground truncate">
{m.email}
{m.last_verified_at ? ` · verified ${fmt(m.last_verified_at)}` : ""}
</div>
</div>
<Button
size="sm"
variant="ghost"
onClick={() => {
if (
confirm(
`Remove the mailbox for ${m.email}? Their mail is not deleted — the portal just stops connecting to it.`,
)
)
remove.mutate(m.user_id);
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
{(setup.data?.mailboxes ?? []).length === 0 && (
<div className="p-3 text-sm text-muted-foreground">No mailboxes assigned yet.</div>
)}
</div>
<div className="border rounded-md p-3 space-y-2">
<div className="text-sm font-medium">Assign a mailbox</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-2">
<Select value={box.userId} onValueChange={(v) => setBox({ ...box, userId: v })}>
<SelectTrigger>
<SelectValue placeholder="Staff member" />
</SelectTrigger>
<SelectContent>
{(setup.data?.staff ?? []).map((u) => (
<SelectItem key={u.id} value={u.id}>
{u.full_name || u.email}
</SelectItem>
))}
</SelectContent>
</Select>
<Input
placeholder="mailbox@school.org"
value={box.email}
onChange={(e) => setBox({ ...box, email: e.target.value })}
/>
<Input
type="password"
placeholder="Mailbox password"
value={box.password}
onChange={(e) => setBox({ ...box, password: e.target.value })}
/>
</div>
<p className="text-xs text-muted-foreground">
The password is checked against the IMAP server before it is stored, then sealed with
AES-256-GCM. It is never sent back to any browser, including yours.
</p>
<Button
size="sm"
onClick={() => assign.mutate()}
disabled={!box.userId || !box.email || !box.password || assign.isPending}
>
{assign.isPending ? "Verifying…" : "Verify & save mailbox"}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
);
}