318 lines
12 KiB
TypeScript
318 lines
12 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,
|
|
useActionData,
|
|
useLoaderData,
|
|
useNavigate,
|
|
useSearchParams,
|
|
useSubmit,
|
|
} from "react-router";
|
|
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.server";
|
|
import {
|
|
EmailMessageDetailPage,
|
|
type EmailMessageDetailLinkTargets,
|
|
} from "~/components/screens/email-inbox/EmailMessageDetailPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
|
|
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[] = await Promise.all(
|
|
threadRows.map(async (row) => {
|
|
const rawHtml = row.bodyHtml ?? (row.bodyText ? renderPlainTextAsHtml(row.bodyText) : "");
|
|
const sanitized = row.bodyHtml ? await 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: "activity.runtime.email.manuallyLinked",
|
|
metadata: { emailMessageId: messageId, manualOverride: true, subject: message.subject?.trim() || null },
|
|
}).catch(() => undefined);
|
|
}
|
|
return Response.json({
|
|
ok: true,
|
|
intent,
|
|
messageKey: intent === "clear-link" ? "emailInbox.toast.linkRemoved" : "emailInbox.toast.linkSaved",
|
|
});
|
|
}
|
|
|
|
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, intent, messageKey: "emailInbox.toast.attachmentImported", fileId });
|
|
} catch (error) {
|
|
if (error instanceof EmailAttachmentError) {
|
|
return Response.json({ intent, 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, intent });
|
|
}
|
|
|
|
throw notFoundResponse();
|
|
};
|
|
|
|
/** AK-UI-02: the route only wires loader/action — the interim screen renders the UI (AD-28). */
|
|
export default function EmailDetailRoute() {
|
|
const rootData = useRootData();
|
|
const { vm } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
|
|
useSaveToast(actionData, { intents: ["set-link", "clear-link", "import-attachment"] });
|
|
const [searchParams] = useSearchParams();
|
|
const submit = useSubmit();
|
|
const navigate = useNavigate();
|
|
|
|
const postIntent = (intent: string, fields: Record<string, string> = {}): void => {
|
|
const form = new FormData();
|
|
if (rootData.csrf) form.set("csrf", rootData.csrf);
|
|
form.set("intent", intent);
|
|
for (const [name, value] of Object.entries(fields)) {
|
|
form.set(name, value);
|
|
}
|
|
void submit(form, { method: "post" });
|
|
};
|
|
|
|
const setLink = (targets: EmailMessageDetailLinkTargets): void => {
|
|
postIntent("set-link", {
|
|
kontaktId: targets.kontaktId ?? "",
|
|
leadId: targets.leadId ?? "",
|
|
projektId: targets.projektId ?? "",
|
|
});
|
|
};
|
|
|
|
return (
|
|
<EmailMessageDetailPage
|
|
vm={vm}
|
|
actionErrorKey={actionData?.error}
|
|
justSent={searchParams.get("sent") === "1"}
|
|
actions={{
|
|
onSetLink: setLink,
|
|
onClearLink: () => postIntent("clear-link"),
|
|
onImportAttachment: (attachmentId) => postIntent("import-attachment", { attachmentId }),
|
|
onToggleRead: () => postIntent("toggle-read"),
|
|
onLoadImages: () => void submit(new URLSearchParams({ images: "1" }), { method: "get" }),
|
|
onReply: () => void navigate(vm.data?.replyHref ?? "."),
|
|
onForward: () => void navigate(vm.data?.forwardHref ?? "."),
|
|
onBack: () => void navigate(vm.data?.backHref ?? "."),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };
|