Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/app.$tenant/emails.$id.tsx
2026-07-08 16:15:37 +02:00

378 lines
17 KiB
TypeScript

// VA-P23 · message/thread detail route (M09 Block F detail). The loader
// sanitizes every body SERVER-SIDE (dompurify + external-image blocking with
// the "Bilder laden" opt-in via ?images=1) and builds the thread VM. Actions:
// link override (set/clear — manual wins, audited as email_match_changed +
// activity), attachment import into v1-Files, read toggle. Visibility follows
// read_own/read_all (mailbox set); a miss is a 404 (A.5.3).
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, useSearchParams, Form, Link } from "react-router";
import { useTranslation } from "react-i18next";
import { logActivity } from "@hivegrid/activity";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import {
buildEmailMessageDetailVM,
emailMatchSourceKey,
summarizeAddresses,
type EmailAttachmentVM,
type EmailLinkBadge,
type EmailMessageDetailVM,
type EmailThreadMessageVM,
} 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, notFoundResponse } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
import {
bulkUpdateMessages,
getMessageForMailboxes,
listImportedAttachmentFiles,
listMailboxesForTenant,
listMailboxesForUser,
listThreadMessages,
setMessageMatchOverride,
} from "~/modules/emailInbox/db/emailInbox.db.server";
import { EmailAttachmentError, importAttachmentToFiles, listProviderAttachments } from "~/modules/emailInbox/services/EmailAttachmentService.server";
import { renderPlainTextAsHtml, sanitizeEmailHtml } from "~/modules/emailInbox/services/emailHtmlSanitizer";
import ServerError from "~/components/ui/errors/ServerError";
type LoaderData = { title: string; vm: EmailMessageDetailVM };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
try {
requireEmailRead(ctx);
} catch {
throw notFoundResponse();
}
const tenantSlug = params.tenant ?? "";
const messageId = params.id ?? "";
const allowExternalImages = new URL(request.url).searchParams.get("images") === "1";
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
const mailboxIds = mailboxes.map((m) => m.id);
const message = await getMessageForMailboxes(ctx.tenantId, mailboxIds, messageId);
if (!message) {
throw notFoundResponse();
}
const mailbox = mailboxes.find((m) => m.id === message.mailboxId);
const threadRows = message.providerThreadId
? await listThreadMessages(ctx.tenantId, mailboxIds, message.providerThreadId)
: [message];
const thread: EmailThreadMessageVM[] = threadRows.map((row) => {
const rawHtml = row.bodyHtml ?? (row.bodyText ? renderPlainTextAsHtml(row.bodyText) : "");
const sanitized = row.bodyHtml ? sanitizeEmailHtml(rawHtml, { allowExternalImages }) : { html: rawHtml, blockedImageCount: 0 };
return {
id: row.id,
direction: row.direction,
fromName: row.fromName,
fromAddress: row.fromAddress,
toSummary: summarizeAddresses(row.toAddresses),
ccSummary: summarizeAddresses(row.ccAddresses) || null,
subject: row.subject,
safeBodyHtml: sanitized.html,
blockedImageCount: sanitized.blockedImageCount,
sentAt: row.sentAt.toISOString(),
isRead: row.isRead,
isFocused: row.id === message.id,
collapsedByDefault: row.id !== message.id,
};
});
// Attachments: provider metadata (live) merged with already-imported Files.
const imported = await listImportedAttachmentFiles(ctx.tenantId, message.id);
const providerAttachments = message.hasAttachments && mailbox
? await listProviderAttachments({ tenantId: ctx.tenantId, mailboxId: message.mailboxId, provider: mailbox.provider, providerMessageId: message.providerMessageId })
: [];
const importedByRole = new Map(imported.map((f) => [f.displayName, f.fileId]));
const attachments: EmailAttachmentVM[] = providerAttachments.map((a) => {
const importedFileId = importedByRole.get(a.filename) ?? null;
return {
attachmentId: a.attachmentId,
filename: a.filename,
sizeBytes: a.sizeBytes,
importedFileId,
downloadHref: importedFileId ? `/${tenantSlug}/files/${importedFileId}` : null,
};
});
const links: EmailLinkBadge[] = [
...(message.matchedKontaktId ? [{ type: "kontakt" as const, id: message.matchedKontaktId, href: `/${tenantSlug}/contacts/${message.matchedKontaktId}` }] : []),
...(message.matchedLeadId ? [{ type: "lead" as const, id: message.matchedLeadId, href: `/${tenantSlug}/leads/${message.matchedLeadId}` }] : []),
...(message.matchedProjektId ? [{ type: "projekt" as const, id: message.matchedProjektId, href: `/${tenantSlug}/projects/${message.matchedProjektId}` }] : []),
];
const vm = buildEmailMessageDetailVM({
focusedId: message.id,
subject: message.subject,
mailbox: { emailAddress: mailbox?.emailAddress ?? "", provider: mailbox?.provider ?? "gmail" },
thread,
attachments,
match: {
links,
confidence: message.matchConfidence,
sourceKey: emailMatchSourceKey(message.matchConfidence),
isManual: message.manualOverrideAt !== null,
},
canWrite: canWriteEmail(ctx),
replyHref: `${emailComposePath(tenantSlug)}?replyTo=${message.id}`,
forwardHref: `${emailComposePath(tenantSlug)}?forward=${message.id}`,
backHref: emailInboxPath(tenantSlug),
allowExternalImages,
});
const title = `${message.subject ?? t("emailInbox.list.noSubject")} | ${process.env.APP_NAME}`;
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 messageId = params.id ?? "";
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
const mailboxIds = mailboxes.map((m) => m.id);
const message = await getMessageForMailboxes(ctx.tenantId, mailboxIds, messageId);
if (!message) {
throw notFoundResponse();
}
const form = await request.formData();
const intent = String(form.get("intent") ?? "");
if (intent === "set-link" || intent === "clear-link") {
const targets =
intent === "clear-link"
? { kontaktId: null, leadId: null, projektId: null }
: {
kontaktId: String(form.get("kontaktId") ?? "").trim() || null,
leadId: String(form.get("leadId") ?? "").trim() || null,
projektId: String(form.get("projektId") ?? "").trim() || null,
};
await setMessageMatchOverride(ctx.tenantId, mailboxIds, messageId, ctx.userId, targets);
// M09 Block H: the manual override is an audit event (email_match_changed).
await createAuditEvent({
tenantId: ctx.tenantId,
actorId: ctx.userId,
actorType: "user",
action: "email_match_changed",
targetType: "email_message",
targetId: messageId,
sourceModule: "email-inbox",
metadata: {
previous: { kontaktId: message.matchedKontaktId, leadId: message.matchedLeadId, projektId: message.matchedProjektId, confidence: message.matchConfidence },
next: targets,
},
}).catch(() => undefined);
// The re-assignment is user-visible on the newly linked entity's timeline.
const subject = targets.kontaktId
? { subjectType: "contact" as const, subjectId: targets.kontaktId }
: targets.leadId
? { subjectType: "lead" as const, subjectId: targets.leadId }
: targets.projektId
? { subjectType: "project" as const, subjectId: targets.projektId }
: null;
if (subject) {
await logActivity({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
actorKind: "user",
activityType: message.direction === "inbound" ? "email_received" : "email_sent",
subjectType: subject.subjectType,
subjectId: subject.subjectId,
summaryText: `E-Mail manuell zugeordnet: ${message.subject?.trim() ? `„${message.subject.trim()}“` : "(ohne Betreff)"}`,
metadata: { emailMessageId: messageId, manualOverride: true },
}).catch(() => undefined);
}
return Response.json({ ok: true });
}
if (intent === "import-attachment") {
const attachmentId = String(form.get("attachmentId") ?? "");
const mailbox = mailboxes.find((m) => m.id === message.mailboxId);
if (!attachmentId || !mailbox) {
throw notFoundResponse();
}
try {
const { fileId } = await importAttachmentToFiles({
tenantId: ctx.tenantId,
userId: ctx.userId,
mailboxId: message.mailboxId,
provider: mailbox.provider,
messageId,
providerMessageId: message.providerMessageId,
attachmentId,
});
return Response.json({ ok: true, fileId });
} catch (error) {
if (error instanceof EmailAttachmentError) {
return Response.json({ error: `emailInbox.detail.attachment.error.${error.code}` }, { status: 400 });
}
throw error;
}
}
if (intent === "toggle-read") {
await bulkUpdateMessages(ctx.tenantId, mailboxIds, [messageId], { isRead: !message.isRead });
return Response.json({ ok: true });
}
throw notFoundResponse();
};
function ThreadMessage({ entry, csrf }: { entry: EmailThreadMessageVM; csrf?: string }) {
const { t, i18n } = useTranslation();
return (
<details open={entry.isFocused} className="border-border rounded-md border" data-thread-id={entry.id} data-focused={entry.isFocused}>
<summary className="flex cursor-pointer items-baseline justify-between px-3 py-2">
<span className="text-foreground truncate text-sm font-medium">
{entry.fromName ?? entry.fromAddress}
<span className="text-muted-foreground ml-2 text-xs">{t("emailInbox.detail.to")} {entry.toSummary}</span>
</span>
<span className="text-muted-foreground shrink-0 text-xs">{new Date(entry.sentAt).toLocaleString(i18n.language)}</span>
</summary>
<div className="px-3 pb-3">
{entry.blockedImageCount > 0 && (
<Form method="get" className="border-border text-muted-foreground mb-2 flex items-center justify-between rounded border px-2 py-1 text-xs" data-ui-id="ui.email.detail.blockedImages">
<span>{t("emailInbox.detail.imagesBlocked", { count: entry.blockedImageCount })}</span>
<input type="hidden" name="images" value="1" />
<button type="submit" className="text-theme-600 underline">
{t("emailInbox.detail.loadImages")}
</button>
</Form>
)}
{/* Sanitized server-side (dompurify) — safe to inject. */}
<div className="prose prose-sm max-w-none" dangerouslySetInnerHTML={{ __html: entry.safeBodyHtml }} data-ui-id="ui.email.detail.body" />
</div>
</details>
);
}
export default function EmailDetailRoute() {
const { t } = useTranslation();
const rootData = useRootData();
const { vm } = useLoaderData<LoaderData>();
useSearchParams();
if (vm.status !== "ready" || !vm.data) {
return <main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.email.detail" />;
}
const { subject, thread, attachments, match, canWrite, replyHref, forwardHref, backHref, mailbox } = vm.data;
return (
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.email.detail">
<Link to={backHref} className="text-muted-foreground text-sm underline">
← {t("emailInbox.detail.back")}
</Link>
<div className="mt-2 flex items-center justify-between">
<div>
<h1 className="text-foreground text-xl font-semibold">{subject ?? t("emailInbox.list.noSubject")}</h1>
<p className="text-muted-foreground mt-1 text-xs">{mailbox.emailAddress}</p>
</div>
{canWrite && (
<div className="flex gap-2">
<Link to={replyHref} className="bg-theme-600 rounded-md px-3 py-1.5 text-sm font-medium text-white" data-ui-id="ui.email.detail.reply">
{t("emailInbox.detail.reply")}
</Link>
<Link to={forwardHref} className="border-border rounded-md border px-3 py-1.5 text-sm" data-ui-id="ui.email.detail.forward">
{t("emailInbox.detail.forward")}
</Link>
</div>
)}
</div>
<section className="border-border mt-4 rounded-md border px-3 py-2" data-ui-id="ui.email.detail.linkEditor">
<div className="flex items-center justify-between">
<p className="text-sm">
<span className="text-muted-foreground">{t(match.sourceKey)}</span>
{match.links.map((link) => (
<Link key={`${link.type}:${link.id}`} to={link.href} className="text-theme-600 ml-2 text-sm underline" data-link-type={link.type}>
{t(`emailInbox.list.linkBadge.${link.type}`)}
</Link>
))}
{match.links.length === 0 && <span className="text-muted-foreground ml-2 text-sm">{t("emailInbox.detail.match.noneHint")}</span>}
</p>
</div>
{canWrite && (
<div className="mt-2 flex flex-wrap items-end gap-2">
<Form method="post" className="flex flex-wrap items-end gap-2">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<input type="hidden" name="intent" value="set-link" />
<label className="text-xs">
{t("emailInbox.detail.linkKontakt")}
<input name="kontaktId" className="border-border ml-1 rounded border px-2 py-1 text-xs" placeholder={t("emailInbox.detail.linkIdPlaceholder")} />
</label>
<label className="text-xs">
{t("emailInbox.detail.linkProjekt")}
<input name="projektId" className="border-border ml-1 rounded border px-2 py-1 text-xs" placeholder={t("emailInbox.detail.linkIdPlaceholder")} />
</label>
<button type="submit" className="border-border rounded border px-2 py-1 text-xs" data-ui-id="ui.email.detail.setLink">
{t("emailInbox.detail.applyLink")}
</button>
</Form>
<Form method="post">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<input type="hidden" name="intent" value="clear-link" />
<button type="submit" className="text-destructive px-2 py-1 text-xs underline" data-ui-id="ui.email.detail.clearLink">
{t("emailInbox.detail.clearLink")}
</button>
</Form>
</div>
)}
</section>
<section className="mt-4 space-y-2" data-ui-id="ui.email.detail.thread">
{thread.map((entry) => (
<ThreadMessage key={entry.id} entry={entry} csrf={rootData.csrf} />
))}
</section>
{attachments.length > 0 && (
<section className="mt-4" data-ui-id="ui.email.detail.attachments">
<h2 className="text-foreground text-sm font-medium">{t("emailInbox.detail.attachments")}</h2>
<ul className="mt-2 flex flex-wrap gap-2">
{attachments.map((attachment) => (
<li key={attachment.attachmentId} className="border-border flex items-center gap-2 rounded border px-2 py-1 text-xs" data-attachment-id={attachment.attachmentId}>
<span className="max-w-48 truncate">{attachment.filename}</span>
<span className="text-muted-foreground">{Math.max(1, Math.round(attachment.sizeBytes / 1024))} KB</span>
{attachment.downloadHref ? (
<Link to={attachment.downloadHref} className="text-theme-600 underline">
{t("emailInbox.detail.attachment.download")}
</Link>
) : canWrite ? (
<Form method="post">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<input type="hidden" name="intent" value="import-attachment" />
<input type="hidden" name="attachmentId" value={attachment.attachmentId} />
<button type="submit" className="text-theme-600 underline" data-ui-id="ui.email.detail.attachment.import">
{t("emailInbox.detail.attachment.import")}
</button>
</Form>
) : null}
</li>
))}
</ul>
</section>
)}
</main>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };