Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,284 @@
// VA-P23 · compose route (M09 Block G): new mail / reply (?replyTo=) / forward
// (?forward=) over the user's OWN mailbox. Templates come from the v1
// EmailTemplate table (M098 — NOT rebuilt); attachments upload as multipart
// form files (≤10 MB v1). Send errors surface as Klartext (M002 keys).
import * as React from "react";
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, Form, Link } from "react-router";
import { useTranslation } from "react-i18next";
import {
buildComposePrefill,
buildEmailComposeVM,
parseRecipients,
type EmailComposeVM,
} from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { validateCSRFToken } from "~/utils/session.server";
import { useRootData } from "~/utils/data/useRootData";
import {
canReadAllMailboxes,
loadEmailInboxContext,
requireEmailRead,
requireEmailWrite,
} from "~/modules/emailInbox/routes/emailInboxAccess.server";
import { EMAIL_INBOX_MODULE_KEY, emailInboxPath, emailMessagePath, emailSettingsPath, notFoundResponse } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
import { getMessageForMailboxes, listMailboxesForTenant, listMailboxesForUser } from "~/modules/emailInbox/db/emailInbox.db.server";
import { EmailSendError, listEmailTemplates, sendEmail } from "~/modules/emailInbox/services/EmailSendService.server";
import { renderPlainTextAsHtml, sanitizeEmailHtml } from "~/modules/emailInbox/services/emailHtmlSanitizer";
import ServerError from "~/components/ui/errors/ServerError";
const COMPOSE_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
type LoaderData = { title: string; vm: EmailComposeVM };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
try {
requireEmailRead(ctx);
requireEmailWrite(ctx);
} catch {
throw notFoundResponse();
}
const tenantSlug = params.tenant ?? "";
const url = new URL(request.url);
const replyToId = url.searchParams.get("replyTo");
const forwardId = url.searchParams.get("forward");
// Sending always runs over the user's OWN mailbox (M09 Block G).
const ownMailboxes = await listMailboxesForUser(ctx.tenantId, ctx.userId);
const templates = await listEmailTemplates(ctx.tenantId);
// Reply/forward context may live in a foreign mailbox for read_all users.
const visibleMailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : ownMailboxes;
const originalId = replyToId ?? forwardId;
const originalRow = originalId
? await getMessageForMailboxes(
ctx.tenantId,
visibleMailboxes.map((m) => m.id),
originalId,
)
: null;
const original = originalRow
? {
id: originalRow.id,
direction: originalRow.direction,
fromAddress: originalRow.fromAddress,
fromName: originalRow.fromName,
toSummary: Array.isArray(originalRow.toAddresses)
? (originalRow.toAddresses as Array<{ address?: string }>).map((a) => a.address ?? "").filter(Boolean).join(", ")
: "",
subject: originalRow.subject,
sentAtIso: originalRow.sentAt.toISOString(),
safeBodyHtml: originalRow.bodyHtml
? sanitizeEmailHtml(originalRow.bodyHtml).html
: originalRow.bodyText
? renderPlainTextAsHtml(originalRow.bodyText)
: "",
}
: null;
const vm = buildEmailComposeVM({
mailboxes: ownMailboxes.map((m) => ({ id: m.id, emailAddress: m.emailAddress, provider: m.provider, isDefaultForUser: m.isDefaultForUser })),
defaultMailboxId: ownMailboxes.find((m) => m.isDefaultForUser)?.id ?? ownMailboxes[0]?.id ?? null,
templates,
prefill: buildComposePrefill({ mode: replyToId ? "reply" : forwardId ? "forward" : "blank", original }),
backHref: originalId ? emailMessagePath(tenantSlug, originalId) : emailInboxPath(tenantSlug),
});
return Response.json({ title: `${t("emailInbox.compose.title")} | ${process.env.APP_NAME}`, 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 tenantSlug = params.tenant ?? "";
const form = await request.formData();
const to = parseRecipients(String(form.get("to") ?? ""));
const cc = parseRecipients(String(form.get("cc") ?? ""));
const bcc = parseRecipients(String(form.get("bcc") ?? ""));
const subject = String(form.get("subject") ?? "").trim();
const bodyText = String(form.get("body") ?? "");
const mailboxId = String(form.get("mailboxId") ?? "");
const replyToMessageId = String(form.get("replyToMessageId") ?? "").trim() || null;
const quotedHtml = String(form.get("quotedHtml") ?? "");
if (to.length === 0) {
return Response.json({ error: "emailInbox.compose.error.no_recipients" }, { status: 400 });
}
// Body: user plain-text (escaped) + the sanitized quoted original below it.
const bodyHtml = `${renderPlainTextAsHtml(bodyText)}${quotedHtml ? sanitizeEmailHtml(quotedHtml).html : ""}`;
const attachments: Array<{ filename: string; mimeType: string; contentBase64: string }> = [];
for (const entry of form.getAll("attachments")) {
if (typeof entry === "object" && entry && "arrayBuffer" in entry) {
const file = entry as File;
if (!file.name || file.size === 0) continue;
if (file.size > COMPOSE_ATTACHMENT_MAX_BYTES) {
return Response.json({ error: "emailInbox.compose.error.attachment_too_large" }, { status: 400 });
}
attachments.push({
filename: file.name,
mimeType: file.type || "application/octet-stream",
contentBase64: Buffer.from(await file.arrayBuffer()).toString("base64"),
});
}
}
try {
const { messageId } = await sendEmail({
tenantId: ctx.tenantId,
userId: ctx.userId,
mailboxId,
to,
cc,
bcc,
subject,
bodyHtml,
replyToMessageId,
attachments,
});
return redirect(`${emailMessagePath(tenantSlug, messageId)}?sent=1`);
} catch (error) {
if (error instanceof EmailSendError) {
return Response.json({ error: `emailInbox.compose.error.${error.code}` }, { status: 400 });
}
throw error;
}
};
export default function EmailComposeRoute() {
const { t } = useTranslation();
const rootData = useRootData();
const { vm } = useLoaderData<LoaderData>();
const actionData = useActionData<{ error?: string }>();
const [subject, setSubject] = React.useState<string | null>(null);
const [templateBody, setTemplateBody] = React.useState<string>("");
if (vm.status !== "ready" || !vm.data) {
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose" />;
}
const { mailboxes, defaultMailboxId, templates, prefill, backHref, noMailboxKey } = vm.data;
if (mailboxes.length === 0) {
return (
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose">
<p className="text-foreground font-medium">{t(noMailboxKey)}</p>
<Link to={backHref.replace(/\/emails.*$/, "/settings/integrations/email")} className="text-theme-600 mt-2 inline-block text-sm underline">
{t("emailInbox.list.connectCta")}
</Link>
</main>
);
}
return (
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose">
<Link to={backHref} className="text-muted-foreground text-sm underline">
← {t("emailInbox.compose.back")}
</Link>
<h1 className="text-foreground mt-2 text-xl font-semibold">{t("emailInbox.compose.title")}</h1>
{actionData?.error && (
<p className="text-destructive border-border mt-3 rounded-md border px-3 py-2 text-sm" data-ui-id="ui.email.compose.error">
{t(actionData.error)}
</p>
)}
<Form method="post" encType="multipart/form-data" className="mt-4 space-y-3">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<input type="hidden" name="replyToMessageId" value={prefill.replyToMessageId ?? ""} />
<input type="hidden" name="quotedHtml" value={prefill.quotedHtml} />
<label className="block text-sm">
{t("emailInbox.compose.mailbox")}
<select name="mailboxId" defaultValue={defaultMailboxId ?? ""} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" data-ui-id="ui.email.compose.mailbox">
{mailboxes.map((mailbox) => (
<option key={mailbox.id} value={mailbox.id}>
{mailbox.emailAddress}
</option>
))}
</select>
</label>
<label className="block text-sm">
{t("emailInbox.compose.to")}
<input name="to" defaultValue={prefill.to} required placeholder={t("emailInbox.compose.recipientsPlaceholder")} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" data-ui-id="ui.email.compose.to" />
</label>
<label className="block text-sm">
{t("emailInbox.compose.cc")}
<input name="cc" placeholder={t("emailInbox.compose.recipientsPlaceholder")} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" />
</label>
{templates.length > 0 && (
<label className="block text-sm">
{t("emailInbox.compose.template")}
<select
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
data-ui-id="ui.email.compose.template"
defaultValue=""
onChange={(event) => {
const template = templates.find((candidate) => candidate.id === event.target.value);
if (template) {
setSubject(template.subject);
setTemplateBody(template.htmlBody.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim());
}
}}
>
<option value="">{t("emailInbox.compose.noTemplate")}</option>
{templates.map((template) => (
<option key={template.id} value={template.id}>
{template.name}
</option>
))}
</select>
</label>
)}
<label className="block text-sm">
{t("emailInbox.compose.subject")}
<input
name="subject"
value={subject ?? prefill.subject}
onChange={(event) => setSubject(event.target.value)}
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
data-ui-id="ui.email.compose.subject"
/>
</label>
<label className="block text-sm">
{t("emailInbox.compose.body")}
<textarea
name="body"
rows={10}
value={templateBody || undefined}
onChange={(event) => setTemplateBody(event.target.value)}
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
data-ui-id="ui.email.compose.body"
/>
</label>
{prefill.quotedHtml && <p className="text-muted-foreground text-xs">{t("emailInbox.compose.quotedHint")}</p>}
<label className="block text-sm">
{t("emailInbox.compose.attachments")}
<input type="file" name="attachments" multiple className="mt-1 block text-sm" data-ui-id="ui.email.compose.attachments" />
</label>
<button type="submit" className="bg-theme-600 rounded-md px-4 py-2 text-sm font-medium text-white" data-ui-id="ui.email.compose.send">
{t("emailInbox.compose.send")}
</button>
</Form>
</main>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };