// 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(); 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(); const [searchParams] = useSearchParams(); const submit = useSubmit(); if (vm.status !== "ready" || !vm.data) { return
; } 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 (

{t("emailInbox.list.title")}

{t("emailInbox.list.subtitle")}

{canWrite && hasAnyMailbox && ( {t("emailInbox.list.compose")} )}
{!hasAnyMailbox ? (

{t(vm.data.noMailboxHeadlineKey)}

{t(vm.data.noMailboxBodyKey)}

{t("emailInbox.list.connectCta")}
) : ( <>
{rows.length === 0 ? (

{t(vm.data.emptyHeadlineKey)}

{t(vm.data.emptyBodyKey)}

) : (
{ // Bulk actions submit via the toolbar buttons; row checkboxes only select. event.stopPropagation(); }} > {rootData.csrf && } {canWrite && (
)}
    {rows.map((row) => (
  • {canWrite && }

    {row.fromName ?? row.fromAddress} {row.isNewsletter && ( {t("emailInbox.list.newsletterBadge")} )}

    {relativeOrAbsolute(row.sentAt, i18n.language)}

    {row.subject ?? t("emailInbox.list.noSubject")} {row.hasAttachments && ๐Ÿ“Ž}

    {row.snippet}

    {row.links.map((link) => ( {t(`emailInbox.list.linkBadge.${link.type}`)} ))}
  • ))}
)} {nextCursor && (
)} )}
); } export function ErrorBoundary() { return ; } export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };