358 lines
16 KiB
TypeScript
358 lines
16 KiB
TypeScript
// VA-P23 · inbox list route (M09 Block F). Loader builds the VM server-side
|
|
// (read_own → only own mailboxes vs read_all; filters/search/keyset cursor in
|
|
// the DB layer); the action handles the bulk intents mark-read/mark-unread/
|
|
// archive (read state is mirrored back to the provider best-effort). Module
|
|
// off -> locked empty; missing email.read_own -> 404 (A.5.3).
|
|
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, useSearchParams, Form, Link, useSubmit } from "react-router";
|
|
import { useTranslation } from "react-i18next";
|
|
import {
|
|
buildEmailInboxListVM,
|
|
decodeInboxCursor,
|
|
encodeInboxCursor,
|
|
parseInboxFilters,
|
|
type EmailInboxListVM,
|
|
type EmailInboxRow,
|
|
type EmailLinkBadge,
|
|
} from "@hivegrid/view-models";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import {
|
|
canReadAllMailboxes,
|
|
canWriteEmail,
|
|
loadEmailInboxContext,
|
|
requireEmailRead,
|
|
requireEmailWrite,
|
|
} from "~/modules/emailInbox/routes/emailInboxAccess.server";
|
|
import { EMAIL_INBOX_MODULE_KEY, emailComposePath, emailInboxPath, emailMessagePath, emailSettingsPath, notFoundResponse } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
|
|
import {
|
|
bulkUpdateMessages,
|
|
getProviderMessageRefs,
|
|
listMailboxesForTenant,
|
|
listMailboxesForUser,
|
|
listMessagesForMailboxes,
|
|
} from "~/modules/emailInbox/db/emailInbox.db.server";
|
|
import { adapterForProvider, ensureFreshMailboxCreds, loadMailboxCreds } from "~/modules/emailInbox/services/MailboxConnectionService.server";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
|
|
const PAGE_SIZE = 50;
|
|
|
|
type LoaderData = { title: string; vm: EmailInboxListVM };
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { t } = await getTranslations(request);
|
|
const ctx = await loadEmailInboxContext({ request, params });
|
|
const tenantSlug = params.tenant ?? "";
|
|
const title = `${t("emailInbox.list.title")} | ${process.env.APP_NAME}`;
|
|
const url = new URL(request.url);
|
|
const filters = parseInboxFilters(url.searchParams);
|
|
|
|
if (!ctx.hasModule) {
|
|
return Response.json({
|
|
title,
|
|
vm: buildEmailInboxListVM({
|
|
rows: [],
|
|
filters,
|
|
mailboxOptions: [],
|
|
nextCursor: null,
|
|
canWrite: false,
|
|
composeHref: emailComposePath(tenantSlug),
|
|
settingsHref: emailSettingsPath(tenantSlug),
|
|
hasAnyMailbox: false,
|
|
}),
|
|
} satisfies LoaderData);
|
|
}
|
|
try {
|
|
requireEmailRead(ctx);
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
|
|
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
|
|
const mailboxById = new Map(mailboxes.map((m) => [m.id, m]));
|
|
const decodedCursor = decodeInboxCursor(url.searchParams.get("cursor"));
|
|
|
|
const pageRows = await listMessagesForMailboxes(ctx.tenantId, {
|
|
mailboxIds: mailboxes.map((m) => m.id),
|
|
onlyMailboxId: filters.mailboxId,
|
|
direction: filters.direction === "all" ? null : filters.direction,
|
|
linked: filters.linked === "all" ? null : filters.linked,
|
|
read: filters.read === "all" ? null : filters.read,
|
|
q: filters.q || null,
|
|
showArchived: filters.showArchived,
|
|
cursor: decodedCursor ? { sentAt: new Date(decodedCursor.sentAtIso), id: decodedCursor.id } : null,
|
|
take: PAGE_SIZE + 1,
|
|
});
|
|
const hasMore = pageRows.length > PAGE_SIZE;
|
|
const visible = hasMore ? pageRows.slice(0, PAGE_SIZE) : pageRows;
|
|
const last = visible.at(-1);
|
|
|
|
const rows: EmailInboxRow[] = visible.map((row) => {
|
|
const mailbox = mailboxById.get(row.mailboxId);
|
|
const links: EmailLinkBadge[] = [
|
|
...(row.matchedKontaktId ? [{ type: "kontakt" as const, id: row.matchedKontaktId, href: `/${tenantSlug}/contacts/${row.matchedKontaktId}` }] : []),
|
|
...(row.matchedLeadId ? [{ type: "lead" as const, id: row.matchedLeadId, href: `/${tenantSlug}/leads/${row.matchedLeadId}` }] : []),
|
|
...(row.matchedProjektId ? [{ type: "projekt" as const, id: row.matchedProjektId, href: `/${tenantSlug}/projects/${row.matchedProjektId}` }] : []),
|
|
];
|
|
return {
|
|
id: row.id,
|
|
detailHref: emailMessagePath(tenantSlug, row.id),
|
|
fromName: row.fromName,
|
|
fromAddress: row.fromAddress,
|
|
subject: row.subject,
|
|
snippet: row.snippet,
|
|
sentAt: row.sentAt.toISOString(),
|
|
direction: row.direction,
|
|
isRead: row.isRead,
|
|
hasAttachments: row.hasAttachments,
|
|
isNewsletter: row.isNewsletter,
|
|
mailbox: { id: row.mailboxId, emailAddress: mailbox?.emailAddress ?? "", provider: mailbox?.provider ?? "gmail" },
|
|
links,
|
|
};
|
|
});
|
|
|
|
const vm = buildEmailInboxListVM({
|
|
rows,
|
|
filters,
|
|
mailboxOptions: mailboxes.map((m) => ({ id: m.id, emailAddress: m.emailAddress })),
|
|
nextCursor: hasMore && last ? encodeInboxCursor(last.sentAt.toISOString(), last.id) : null,
|
|
canWrite: canWriteEmail(ctx),
|
|
composeHref: emailComposePath(tenantSlug),
|
|
settingsHref: emailSettingsPath(tenantSlug),
|
|
hasAnyMailbox: mailboxes.length > 0,
|
|
});
|
|
return Response.json({ title, vm } satisfies LoaderData);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
|
|
try {
|
|
requireEmailRead(ctx);
|
|
requireEmailWrite(ctx);
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
await validateCSRFToken(request);
|
|
const form = await request.formData();
|
|
const intent = String(form.get("intent") ?? "");
|
|
const messageIds = form.getAll("messageId").map(String).filter(Boolean);
|
|
if (messageIds.length === 0) {
|
|
return Response.json({ ok: true, updated: 0 });
|
|
}
|
|
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
|
|
const mailboxIds = mailboxes.map((m) => m.id);
|
|
const mailboxById = new Map(mailboxes.map((m) => [m.id, m]));
|
|
|
|
if (intent === "mark-read" || intent === "mark-unread") {
|
|
const isRead = intent === "mark-read";
|
|
const { count } = await bulkUpdateMessages(ctx.tenantId, mailboxIds, messageIds, { isRead });
|
|
// Mirror the read state back to the provider — best-effort (M09 Block F);
|
|
// a provider hiccup must not fail the bulk action.
|
|
const refs = await getProviderMessageRefs(ctx.tenantId, mailboxIds, messageIds);
|
|
const byMailbox = new Map<string, string[]>();
|
|
for (const ref of refs) {
|
|
byMailbox.set(ref.mailboxId, [...(byMailbox.get(ref.mailboxId) ?? []), ref.providerMessageId]);
|
|
}
|
|
for (const [mailboxId, providerIds] of byMailbox) {
|
|
const mailbox = mailboxById.get(mailboxId);
|
|
if (!mailbox) continue;
|
|
try {
|
|
const adapter = adapterForProvider(mailbox.provider);
|
|
const creds = await loadMailboxCreds(ctx.tenantId, mailboxId);
|
|
if (!creds) continue;
|
|
const fresh = await ensureFreshMailboxCreds(ctx.tenantId, mailboxId, mailbox.provider, creds);
|
|
for (const providerMessageId of providerIds) {
|
|
await adapter.markRead(fresh, providerMessageId, isRead).catch(() => undefined);
|
|
}
|
|
} catch {
|
|
// best-effort mirror
|
|
}
|
|
}
|
|
return Response.json({ ok: true, updated: count });
|
|
}
|
|
|
|
if (intent === "archive") {
|
|
// HiveGrid-side archive only — the provider mailbox stays untouched (M09 F).
|
|
const { count } = await bulkUpdateMessages(ctx.tenantId, mailboxIds, messageIds, { archived: true });
|
|
return Response.json({ ok: true, updated: count });
|
|
}
|
|
|
|
throw notFoundResponse();
|
|
};
|
|
|
|
function relativeOrAbsolute(iso: string, locale: string): string {
|
|
const date = new Date(iso);
|
|
const ageMs = Date.now() - date.getTime();
|
|
if (ageMs < 7 * 86_400_000) {
|
|
const days = Math.floor(ageMs / 86_400_000);
|
|
if (days === 0) return date.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });
|
|
return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(-days, "day");
|
|
}
|
|
return date.toLocaleDateString(locale);
|
|
}
|
|
|
|
export default function EmailInboxRoute() {
|
|
const { t, i18n } = useTranslation();
|
|
const rootData = useRootData();
|
|
const { vm } = useLoaderData<LoaderData>();
|
|
const [searchParams] = useSearchParams();
|
|
const submit = useSubmit();
|
|
|
|
if (vm.status !== "ready" || !vm.data) {
|
|
return <main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.email.inbox" />;
|
|
}
|
|
const { rows, filters, mailboxOptions, nextCursor, hasAnyMailbox, settingsHref, composeHref, canWrite } = vm.data;
|
|
|
|
const withParam = (key: string, value: string | null): string => {
|
|
const next = new URLSearchParams(searchParams);
|
|
next.delete("cursor");
|
|
if (value) next.set(key, value);
|
|
else next.delete(key);
|
|
return `?${next.toString()}`;
|
|
};
|
|
|
|
return (
|
|
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.email.inbox">
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<h1 className="text-foreground text-xl font-semibold">{t("emailInbox.list.title")}</h1>
|
|
<p className="text-muted-foreground mt-1 text-sm">{t("emailInbox.list.subtitle")}</p>
|
|
</div>
|
|
{canWrite && hasAnyMailbox && (
|
|
<Link to={composeHref} className="bg-theme-600 rounded-md px-4 py-2 text-sm font-medium text-white" data-ui-id="ui.email.inbox.compose">
|
|
{t("emailInbox.list.compose")}
|
|
</Link>
|
|
)}
|
|
</div>
|
|
|
|
{!hasAnyMailbox ? (
|
|
<div className="mt-10 text-center" data-ui-id="ui.email.inbox.noMailbox">
|
|
<p className="text-foreground font-medium">{t(vm.data.noMailboxHeadlineKey)}</p>
|
|
<p className="text-muted-foreground mt-1 text-sm">{t(vm.data.noMailboxBodyKey)}</p>
|
|
<Link to={settingsHref} className="text-theme-600 mt-3 inline-block text-sm underline">
|
|
{t("emailInbox.list.connectCta")}
|
|
</Link>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<Form method="get" className="mt-4 flex flex-wrap items-center gap-2" data-ui-id="ui.email.inbox.filters">
|
|
<input
|
|
type="search"
|
|
name="q"
|
|
defaultValue={filters.q}
|
|
placeholder={t("emailInbox.list.searchPlaceholder")}
|
|
className="border-border w-64 rounded-md border px-3 py-1.5 text-sm"
|
|
data-ui-id="ui.email.inbox.search"
|
|
/>
|
|
<select name="mailbox" defaultValue={filters.mailboxId ?? ""} className="border-border rounded-md border px-2 py-1.5 text-sm">
|
|
<option value="">{t("emailInbox.list.filter.allMailboxes")}</option>
|
|
{mailboxOptions.map((m) => (
|
|
<option key={m.id} value={m.id}>
|
|
{m.emailAddress}
|
|
</option>
|
|
))}
|
|
</select>
|
|
<select name="linked" defaultValue={filters.linked} className="border-border rounded-md border px-2 py-1.5 text-sm">
|
|
<option value="all">{t("emailInbox.list.filter.linkedAll")}</option>
|
|
<option value="linked">{t("emailInbox.list.filter.linked")}</option>
|
|
<option value="unlinked">{t("emailInbox.list.filter.unlinked")}</option>
|
|
</select>
|
|
<select name="read" defaultValue={filters.read} className="border-border rounded-md border px-2 py-1.5 text-sm">
|
|
<option value="all">{t("emailInbox.list.filter.readAll")}</option>
|
|
<option value="unread">{t("emailInbox.list.filter.unread")}</option>
|
|
<option value="read">{t("emailInbox.list.filter.read")}</option>
|
|
</select>
|
|
<button type="submit" className="border-border rounded-md border px-3 py-1.5 text-sm">
|
|
{t("emailInbox.list.applyFilters")}
|
|
</button>
|
|
</Form>
|
|
|
|
{rows.length === 0 ? (
|
|
<div className="mt-10 text-center" data-ui-id="ui.email.inbox.empty">
|
|
<p className="text-foreground font-medium">{t(vm.data.emptyHeadlineKey)}</p>
|
|
<p className="text-muted-foreground mt-1 text-sm">{t(vm.data.emptyBodyKey)}</p>
|
|
</div>
|
|
) : (
|
|
<Form
|
|
method="post"
|
|
onChange={(event) => {
|
|
// Bulk actions submit via the toolbar buttons; row checkboxes only select.
|
|
event.stopPropagation();
|
|
}}
|
|
>
|
|
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
|
{canWrite && (
|
|
<div className="mt-4 flex gap-2" data-ui-id="ui.email.inbox.bulk">
|
|
<button type="submit" name="intent" value="mark-read" className="border-border rounded-md border px-3 py-1 text-xs">
|
|
{t("emailInbox.list.bulk.markRead")}
|
|
</button>
|
|
<button type="submit" name="intent" value="mark-unread" className="border-border rounded-md border px-3 py-1 text-xs">
|
|
{t("emailInbox.list.bulk.markUnread")}
|
|
</button>
|
|
<button type="submit" name="intent" value="archive" className="border-border rounded-md border px-3 py-1 text-xs">
|
|
{t("emailInbox.list.bulk.archive")}
|
|
</button>
|
|
</div>
|
|
)}
|
|
<ul className="divide-border mt-2 divide-y" data-ui-id="ui.email.inbox.list">
|
|
{rows.map((row) => (
|
|
<li key={row.id} className="flex items-center gap-3 py-3" data-row-id={row.id} data-unread={!row.isRead}>
|
|
{canWrite && <input type="checkbox" name="messageId" value={row.id} aria-label={t("emailInbox.list.selectRow")} />}
|
|
<Link to={row.detailHref} className="min-w-0 flex-1">
|
|
<div className="flex items-baseline justify-between gap-3">
|
|
<p className={`truncate text-sm ${row.isRead ? "text-muted-foreground" : "text-foreground font-semibold"}`}>
|
|
{row.fromName ?? row.fromAddress}
|
|
{row.isNewsletter && (
|
|
<span className="border-border text-muted-foreground ml-2 rounded border px-1 text-[10px]">{t("emailInbox.list.newsletterBadge")}</span>
|
|
)}
|
|
</p>
|
|
<span className="text-muted-foreground shrink-0 text-xs">{relativeOrAbsolute(row.sentAt, i18n.language)}</span>
|
|
</div>
|
|
<p className={`truncate text-sm ${row.isRead ? "text-muted-foreground" : "text-foreground"}`}>
|
|
{row.subject ?? t("emailInbox.list.noSubject")}
|
|
{row.hasAttachments && <span className="ml-1">📎</span>}
|
|
</p>
|
|
<div className="flex items-center gap-2">
|
|
<p className="text-muted-foreground truncate text-xs">{row.snippet}</p>
|
|
{row.links.map((link) => (
|
|
<span key={`${link.type}:${link.id}`} className="border-border text-muted-foreground shrink-0 rounded border px-1 text-[10px]" data-link-type={link.type}>
|
|
{t(`emailInbox.list.linkBadge.${link.type}`)}
|
|
</span>
|
|
))}
|
|
</div>
|
|
</Link>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</Form>
|
|
)}
|
|
|
|
{nextCursor && (
|
|
<div className="mt-4 text-center">
|
|
<button
|
|
type="button"
|
|
className="border-border rounded-md border px-4 py-2 text-sm"
|
|
data-ui-id="ui.email.inbox.more"
|
|
onClick={() => {
|
|
const next = new URLSearchParams(searchParams);
|
|
next.set("cursor", nextCursor);
|
|
submit(next, { method: "get" });
|
|
}}
|
|
>
|
|
{t("emailInbox.list.loadMore")}
|
|
</button>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</main>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };
|