251 lines
9.8 KiB
TypeScript
251 lines
9.8 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, useActionData, useLoaderData, useNavigate, useSearchParams, useSubmit } from "react-router";
|
|
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 {
|
|
EmailInboxListPage,
|
|
type EmailInboxAppliedFilters,
|
|
type EmailInboxBulkIntent,
|
|
} from "~/components/screens/email-inbox/EmailInboxListPage";
|
|
import {
|
|
canReadAllMailboxes,
|
|
canWriteEmail,
|
|
loadEmailInboxContext,
|
|
requireEmailRead,
|
|
requireEmailWrite,
|
|
} from "~/modules/emailInbox/routes/emailInboxAccess.server";
|
|
import { EMAIL_INBOX_MODULE_KEY, emailComposePath, 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";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
|
|
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: false, intent, 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, intent, 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,
|
|
intent,
|
|
messageKey: count === 1 ? "emailInbox.toast.messageArchived" : "emailInbox.toast.messagesArchived",
|
|
updated: count,
|
|
});
|
|
}
|
|
|
|
throw notFoundResponse();
|
|
};
|
|
|
|
/** AK-UI-01: the route only wires loader/action — the interim screen renders the UI (AD-28). */
|
|
export default function EmailInboxRoute() {
|
|
const rootData = useRootData();
|
|
const { vm } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
|
|
useSaveToast(actionData, { intents: ["archive"] });
|
|
const [searchParams] = useSearchParams();
|
|
const submit = useSubmit();
|
|
const navigate = useNavigate();
|
|
|
|
const applyFilters = (filters: EmailInboxAppliedFilters): void => {
|
|
const next = new URLSearchParams(searchParams);
|
|
next.delete("cursor");
|
|
const setOrDelete = (key: string, value: string | null): void => {
|
|
if (value) next.set(key, value);
|
|
else next.delete(key);
|
|
};
|
|
setOrDelete("q", filters.q.trim() || null);
|
|
setOrDelete("mailbox", filters.mailboxId);
|
|
setOrDelete("linked", filters.linked === "all" ? null : filters.linked);
|
|
setOrDelete("read", filters.read === "all" ? null : filters.read);
|
|
void submit(next, { method: "get" });
|
|
};
|
|
|
|
const runBulk = (intent: EmailInboxBulkIntent, messageIds: readonly string[]): void => {
|
|
const form = new FormData();
|
|
if (rootData.csrf) form.set("csrf", rootData.csrf);
|
|
form.set("intent", intent);
|
|
for (const id of messageIds) form.append("messageId", id);
|
|
void submit(form, { method: "post" });
|
|
};
|
|
|
|
const loadMore = (cursor: string): void => {
|
|
const next = new URLSearchParams(searchParams);
|
|
next.set("cursor", cursor);
|
|
void submit(next, { method: "get" });
|
|
};
|
|
|
|
return (
|
|
<EmailInboxListPage
|
|
vm={vm}
|
|
actions={{
|
|
onApplyFilters: applyFilters,
|
|
onBulk: runBulk,
|
|
onLoadMore: loadMore,
|
|
onCompose: () => void navigate(vm.data?.composeHref ?? "."),
|
|
onOpenSettings: () => void navigate(vm.data?.settingsHref ?? "."),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };
|