Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -5,8 +5,15 @@
// 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 {
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 {
@@ -39,8 +46,13 @@ import {
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 { 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 };
@@ -64,35 +76,41 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
}
const mailbox = mailboxes.find((m) => m.id === message.mailboxId);
const threadRows = message.providerThreadId
? await listThreadMessages(ctx.tenantId, mailboxIds, message.providerThreadId)
: [message];
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,
};
});
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 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;
@@ -106,9 +124,13 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
});
const links: EmailLinkBadge[] = [
...(message.matchedKontaktId ? [{ type: "kontakt" as const, id: message.matchedKontaktId, href: `/${tenantSlug}/contacts/${message.matchedKontaktId}` }] : []),
...(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}` }] : []),
...(message.matchedProjektId
? [{ type: "projekt" as const, id: message.matchedProjektId, href: `/${tenantSlug}/projects/${message.matchedProjektId}` }]
: []),
];
const vm = buildEmailMessageDetailVM({
@@ -172,7 +194,12 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
targetId: messageId,
sourceModule: "email-inbox",
metadata: {
previous: { kontaktId: message.matchedKontaktId, leadId: message.matchedLeadId, projektId: message.matchedProjektId, confidence: message.matchConfidence },
previous: {
kontaktId: message.matchedKontaktId,
leadId: message.matchedLeadId,
projektId: message.matchedProjektId,
confidence: message.matchConfidence,
},
next: targets,
},
}).catch(() => undefined);
@@ -192,11 +219,15 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
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 },
summaryText: "activity.runtime.email.manuallyLinked",
metadata: { emailMessageId: messageId, manualOverride: true, subject: message.subject?.trim() || null },
}).catch(() => undefined);
}
return Response.json({ ok: true });
return Response.json({
ok: true,
intent,
messageKey: intent === "clear-link" ? "emailInbox.toast.linkRemoved" : "emailInbox.toast.linkSaved",
});
}
if (intent === "import-attachment") {
@@ -215,10 +246,10 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
providerMessageId: message.providerMessageId,
attachmentId,
});
return Response.json({ ok: true, fileId });
return Response.json({ ok: true, intent, messageKey: "emailInbox.toast.attachmentImported", fileId });
} catch (error) {
if (error instanceof EmailAttachmentError) {
return Response.json({ error: `emailInbox.detail.attachment.error.${error.code}` }, { status: 400 });
return Response.json({ intent, error: `emailInbox.detail.attachment.error.${error.code}` }, { status: 400 });
}
throw error;
}
@@ -226,147 +257,56 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
if (intent === "toggle-read") {
await bulkUpdateMessages(ctx.tenantId, mailboxIds, [messageId], { isRead: !message.isRead });
return Response.json({ ok: true });
return Response.json({ ok: true, intent });
}
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>
);
}
/** AK-UI-02: the route only wires loader/action — the interim screen renders the UI (AD-28). */
export default function EmailDetailRoute() {
const { t } = useTranslation();
const rootData = useRootData();
const { vm } = useLoaderData<LoaderData>();
useSearchParams();
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();
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;
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 (
<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>
<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 ?? "."),
}}
/>
);
}