Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+109
@@ -0,0 +1,109 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
attachment: vi.fn(),
|
||||
audit: vi.fn(),
|
||||
sign: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/admin-sales-core.server", () => ({
|
||||
writeAdminSalesAudit: mocks.audit,
|
||||
}));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
adminEmailAttachment: { findFirst: mocks.attachment },
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/integrations/mediaSigning.server", () => ({
|
||||
createMediaDownloadUrl: mocks.sign,
|
||||
}));
|
||||
vi.mock("~/utils/integrations/storageService", () => ({
|
||||
resolveStorageBucket: () => "hivegrid-files",
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-email-connections.server", () => ({
|
||||
runAsAdminEmailOperator: async (
|
||||
_request: Request,
|
||||
permissions: readonly string[],
|
||||
operation: (context: unknown) => Promise<unknown>
|
||||
) => {
|
||||
expect(permissions).toEqual([
|
||||
"admin_sales.email.send",
|
||||
"admin_sales.communication.read_all",
|
||||
]);
|
||||
return operation({
|
||||
adminUserId: "manager",
|
||||
canReadAllCommunication: true,
|
||||
actor: (reason: string) => ({
|
||||
adminUserId: "manager",
|
||||
email: "manager@example.test",
|
||||
reason,
|
||||
}),
|
||||
});
|
||||
},
|
||||
}));
|
||||
|
||||
import { loader } from "./$attachmentId";
|
||||
|
||||
describe("admin email attachment download", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.attachment.mockResolvedValue({
|
||||
id: "attachment-b",
|
||||
adminUserId: "sales-b",
|
||||
messageId: "message-b",
|
||||
filename: "angebot.pdf",
|
||||
storageKey: "admin-email/sales-b/angebot.pdf",
|
||||
});
|
||||
mocks.sign.mockResolvedValue("https://storage.example.test/signed");
|
||||
});
|
||||
|
||||
it("audits a foreign team attachment before returning a short-lived redirect", async () => {
|
||||
const response = await loader({
|
||||
request: new Request(
|
||||
"https://admin.example.test/sales/email/attachments/attachment-b"
|
||||
),
|
||||
params: { attachmentId: "attachment-b" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(mocks.attachment).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
id: "attachment-b",
|
||||
storageBucket: "hivegrid-files",
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(mocks.audit).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
action: "admin.sales.email.attachment.downloaded",
|
||||
targetId: "attachment-b",
|
||||
after: {
|
||||
dataOwnerAdminUserId: "sales-b",
|
||||
messageId: "message-b",
|
||||
foreignAccess: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(response).toMatchObject({ status: 302 });
|
||||
expect((response as Response).headers.get("location")).toBe(
|
||||
"https://storage.example.test/signed"
|
||||
);
|
||||
});
|
||||
|
||||
it("returns 404 when RLS or owner scope hides the attachment", async () => {
|
||||
mocks.attachment.mockResolvedValue(null);
|
||||
await expect(
|
||||
loader({
|
||||
request: new Request(
|
||||
"https://admin.example.test/sales/email/attachments/missing"
|
||||
),
|
||||
params: { attachmentId: "missing" },
|
||||
context: {},
|
||||
} as never)
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
expect(mocks.audit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { writeAdminSalesAudit } from "@hivegrid/db/admin-sales-core.server";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import { runAsAdminEmailOperator } from "~/services/admin/admin-email-connections.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
|
||||
import { resolveStorageBucket } from "~/utils/integrations/storageService";
|
||||
|
||||
export async function loader({ params, request }: LoaderFunctionArgs) {
|
||||
const attachmentId = params.attachmentId;
|
||||
if (!attachmentId) {
|
||||
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
}
|
||||
return runAsAdminEmailOperator(
|
||||
request,
|
||||
[
|
||||
"admin_sales.email.send",
|
||||
"admin_sales.communication.read_all",
|
||||
],
|
||||
async (context) => {
|
||||
const attachment = await db.adminEmailAttachment.findFirst({
|
||||
where: {
|
||||
id: attachmentId,
|
||||
...(context.canReadAllCommunication
|
||||
? {}
|
||||
: { adminUserId: context.adminUserId }),
|
||||
storageBucket: resolveStorageBucket(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
adminUserId: true,
|
||||
messageId: true,
|
||||
filename: true,
|
||||
storageKey: true,
|
||||
},
|
||||
});
|
||||
if (!attachment) {
|
||||
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
}
|
||||
await writeAdminSalesAudit(db, {
|
||||
actor: context.actor("E-Mail-Anhang heruntergeladen"),
|
||||
action: "admin.sales.email.attachment.downloaded",
|
||||
targetType: "AdminEmailAttachment",
|
||||
targetId: attachment.id,
|
||||
after: {
|
||||
dataOwnerAdminUserId: attachment.adminUserId,
|
||||
messageId: attachment.messageId,
|
||||
foreignAccess:
|
||||
attachment.adminUserId !== context.adminUserId,
|
||||
},
|
||||
});
|
||||
const location = await createMediaDownloadUrl({
|
||||
key: attachment.storageKey,
|
||||
filename: attachment.filename,
|
||||
ttlSeconds: 60,
|
||||
});
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
"Cache-Control": "private, no-store",
|
||||
Location: location,
|
||||
},
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
runAs: vi.fn(async (_request, _permission, operation) =>
|
||||
operation({
|
||||
adminUserId: "admin-1",
|
||||
actor: (reason: string) => ({
|
||||
adminUserId: "admin-1",
|
||||
email: "raffael@hivegrid.de",
|
||||
reason,
|
||||
}),
|
||||
})
|
||||
),
|
||||
apply: vi.fn(),
|
||||
inbox: vi.fn(),
|
||||
templates: vi.fn(),
|
||||
scheduled: vi.fn(),
|
||||
domains: vi.fn(),
|
||||
validateCsrf: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/screens/admin/sales/email/AdminEmailInboxPage", () => ({ AdminEmailInboxPage: () => null }));
|
||||
vi.mock("~/components/screens/admin/sales/email/AdminEmailTemplatesPage", () => ({ AdminEmailTemplatesPage: () => null }));
|
||||
vi.mock("~/components/screens/admin/sales/email/AdminEmailScheduledPage", () => ({ AdminEmailScheduledPage: () => null }));
|
||||
vi.mock("~/components/screens/admin/sales/email/AdminEmailDomainsPage", () => ({ AdminEmailDomainsPage: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-email-connections.server", () => ({
|
||||
runAsAdminEmailOperator: mocks.runAs,
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-email-workspace.server", () => ({
|
||||
adminEmailWorkspaceHrefs: vi.fn(() => ({})),
|
||||
applyAdminEmailWorkspaceAction: mocks.apply,
|
||||
readAdminEmailInbox: mocks.inbox,
|
||||
readAdminEmailTemplates: mocks.templates,
|
||||
readAdminEmailScheduled: mocks.scheduled,
|
||||
readAdminEmailDomains: mocks.domains,
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: mocks.validateCsrf,
|
||||
}));
|
||||
|
||||
import { action as inboxAction, loader as inboxLoader } from "./inbox";
|
||||
import { action as scheduledAction, loader as scheduledLoader } from "./scheduled";
|
||||
import { action as templatesAction, loader as templatesLoader } from "./templates";
|
||||
import { action as domainsAction, loader as domainsLoader } from "../settings/sending-domains";
|
||||
|
||||
describe("admin email workspace routes", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.inbox.mockResolvedValue({
|
||||
stats: { threads: 0, unread: 0, assignmentQueue: 0 },
|
||||
threads: [],
|
||||
selectedThread: null,
|
||||
assignmentOptions: { contacts: [], deals: [] },
|
||||
});
|
||||
mocks.templates.mockResolvedValue({
|
||||
templates: [],
|
||||
snippets: [],
|
||||
signature: null,
|
||||
});
|
||||
mocks.scheduled.mockResolvedValue({
|
||||
outboundLocked: true,
|
||||
policy: null,
|
||||
scheduled: [],
|
||||
bulkRuns: [],
|
||||
reminders: [],
|
||||
mailboxes: [],
|
||||
contacts: [],
|
||||
});
|
||||
mocks.domains.mockResolvedValue({
|
||||
domains: [],
|
||||
bccAddresses: [],
|
||||
tracking: {
|
||||
enabled: false,
|
||||
liveOpenEnabled: false,
|
||||
retentionDays: 180,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("loads every screen through its smallest admin permission", async () => {
|
||||
await inboxLoader(loaderArgs("/sales/email/inbox?thread=thread-1"));
|
||||
expect(mocks.inbox).toHaveBeenCalledWith(expect.objectContaining({ adminUserId: "admin-1" }), "thread-1");
|
||||
expect(mocks.runAs).toHaveBeenLastCalledWith(
|
||||
expect.any(Request),
|
||||
[
|
||||
"admin_sales.email.send",
|
||||
"admin_sales.communication.read_all",
|
||||
],
|
||||
expect.any(Function)
|
||||
);
|
||||
|
||||
await templatesLoader(loaderArgs("/sales/email/templates"));
|
||||
expect(mocks.runAs).toHaveBeenLastCalledWith(
|
||||
expect.any(Request),
|
||||
"admin_sales.email.send",
|
||||
expect.any(Function)
|
||||
);
|
||||
|
||||
await scheduledLoader(loaderArgs("/sales/email/scheduled"));
|
||||
expect(mocks.runAs).toHaveBeenLastCalledWith(
|
||||
expect.any(Request),
|
||||
[
|
||||
"admin_sales.email.send",
|
||||
"admin_sales.communication.read_all",
|
||||
],
|
||||
expect.any(Function)
|
||||
);
|
||||
|
||||
await domainsLoader(loaderArgs("/sales/settings/sending-domains"));
|
||||
expect(mocks.runAs).toHaveBeenLastCalledWith(expect.any(Request), "admin_sales.email.track", expect.any(Function));
|
||||
});
|
||||
|
||||
it("validates and applies an explicit message assignment", async () => {
|
||||
const response = await inboxAction(
|
||||
actionArgs("/sales/email/inbox", {
|
||||
intent: "assign-message",
|
||||
messageId: "message-1",
|
||||
contactId: "contact-1",
|
||||
dealId: null,
|
||||
})
|
||||
);
|
||||
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledOnce();
|
||||
expect(mocks.apply).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ adminUserId: "admin-1" }),
|
||||
expect.objectContaining({
|
||||
intent: "assign-message",
|
||||
contactId: "contact-1",
|
||||
})
|
||||
);
|
||||
expect(response).toEqual({
|
||||
intent: "assign-message",
|
||||
ok: true,
|
||||
messageKey: "admin.sales.email.toast.assignmentSaved",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses bulk-send permission for a personalized list", async () => {
|
||||
const response = await scheduledAction(
|
||||
actionArgs("/sales/email/scheduled", {
|
||||
intent: "queue-bulk-email",
|
||||
mailboxId: "mailbox-1",
|
||||
name: "Demo Follow-up",
|
||||
contactIds: ["contact-1", "contact-2"],
|
||||
subjectTemplate: "Hallo {{first_name}}",
|
||||
bodyTemplate: "Guten Tag {{full_name}}",
|
||||
scheduledFor: "2026-07-25T08:00:00.000Z",
|
||||
timeZone: "Europe/Berlin",
|
||||
noReplyAfterDays: 3,
|
||||
idempotencyKey: "bulk-1",
|
||||
})
|
||||
);
|
||||
|
||||
expect(mocks.runAs).toHaveBeenLastCalledWith(expect.any(Request), "admin_sales.email.bulk_send", expect.any(Function));
|
||||
expect(mocks.apply).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
expect.objectContaining({
|
||||
intent: "queue-bulk-email",
|
||||
contactIds: ["contact-1", "contact-2"],
|
||||
})
|
||||
);
|
||||
expect(response).toEqual({
|
||||
intent: "queue-bulk-email",
|
||||
ok: true,
|
||||
messageKey: "admin.sales.email.toast.bulkQueued",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts template and domain actions and rejects cross-route intents", async () => {
|
||||
await expect(
|
||||
templatesAction(
|
||||
actionArgs("/sales/email/templates", {
|
||||
intent: "save-snippet",
|
||||
shortcut: "intro",
|
||||
title: "Einleitung",
|
||||
content: "Guten Tag",
|
||||
})
|
||||
)
|
||||
).resolves.toEqual({
|
||||
intent: "save-snippet",
|
||||
ok: true,
|
||||
messageKey: "admin.sales.email.toast.snippetSaved",
|
||||
});
|
||||
await expect(
|
||||
domainsAction(
|
||||
actionArgs("/sales/settings/sending-domains", {
|
||||
intent: "save-domain",
|
||||
domain: "hivegrid.de",
|
||||
spfRecordName: "hivegrid.de",
|
||||
spfExpectedValue: "v=spf1 -all",
|
||||
dkimRecordName: "mail._domainkey.hivegrid.de",
|
||||
dkimExpectedValue: "k=rsa; p=key",
|
||||
})
|
||||
)
|
||||
).resolves.toEqual({
|
||||
intent: "save-domain",
|
||||
ok: true,
|
||||
messageKey: "admin.sales.email.toast.domainSaved",
|
||||
});
|
||||
|
||||
const rejected = await templatesAction(
|
||||
actionArgs("/sales/email/templates", {
|
||||
intent: "assign-message",
|
||||
messageId: "message-1",
|
||||
contactId: "contact-1",
|
||||
dealId: null,
|
||||
})
|
||||
);
|
||||
expect(rejected).toBeInstanceOf(Response);
|
||||
expect((rejected as Response).status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
function loaderArgs(path: string) {
|
||||
return {
|
||||
request: new Request(`https://admin.hivegrid.de${path}`),
|
||||
params: {},
|
||||
context: {},
|
||||
} as never;
|
||||
}
|
||||
|
||||
function actionArgs(path: string, payload: object) {
|
||||
const form = new FormData();
|
||||
form.set("payload", JSON.stringify(payload));
|
||||
return {
|
||||
request: new Request(`https://admin.hivegrid.de${path}`, {
|
||||
method: "POST",
|
||||
body: form,
|
||||
}),
|
||||
params: {},
|
||||
context: {},
|
||||
} as never;
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import { adminEmailWorkspaceActionSchema, buildAdminEmailInboxVM } from "@hivegrid/view-models";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useNavigate, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminEmailInboxPage } from "~/components/screens/admin/sales/email/AdminEmailInboxPage";
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runAsAdminEmailOperator } from "~/services/admin/admin-email-connections.server";
|
||||
import { adminEmailWorkspaceHrefs, applyAdminEmailWorkspaceAction, readAdminEmailInbox } from "~/services/admin/admin-email-workspace.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type ActionData = { intent?: string; ok?: true; messageKey?: string; error?: string };
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const selected = new URL(request.url).searchParams.get("thread");
|
||||
return runAsAdminEmailOperator(
|
||||
request,
|
||||
[
|
||||
"admin_sales.email.send",
|
||||
"admin_sales.communication.read_all",
|
||||
],
|
||||
async (context) => ({
|
||||
vm: buildAdminEmailInboxVM(await readAdminEmailInbox(context, selected)),
|
||||
hrefs: adminEmailWorkspaceHrefs(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const parsed = adminEmailWorkspaceActionSchema.safeParse(parsePayload(form));
|
||||
if (!parsed.success || parsed.data.intent !== "assign-message") {
|
||||
return Response.json({ error: t("admin.sales.email.errors.invalidAction") }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await runAsAdminEmailOperator(request, "admin_sales.email.send", (context) => applyAdminEmailWorkspaceAction(context, parsed.data));
|
||||
return { intent: parsed.data.intent, ok: true, messageKey: "admin.sales.email.toast.assignmentSaved" } satisfies ActionData;
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.sales.email.errors.assignmentFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export function HydrateFallback() {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminEmailInboxRoute() {
|
||||
const { vm, hrefs } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
const submit = useSubmit();
|
||||
|
||||
useSaveToast(actionData?.ok ? actionData : undefined);
|
||||
return (
|
||||
<AdminEmailInboxPage
|
||||
vm={vm}
|
||||
hrefs={hrefs}
|
||||
submitting={navigation.state === "submitting"}
|
||||
errorMessage={actionData?.error}
|
||||
actions={{
|
||||
onOpenThread: (threadId) => navigate(`?thread=${encodeURIComponent(threadId)}`),
|
||||
onAssign: (input) => {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("payload", JSON.stringify({ intent: "assign-message", ...input }));
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function parsePayload(form: FormData) {
|
||||
try {
|
||||
return JSON.parse(String(form.get("payload") ?? "{}")) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { adminEmailWorkspaceActionSchema, buildAdminEmailScheduledVM } from "@hivegrid/view-models";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useNavigation, useSearchParams, useSubmit } from "react-router";
|
||||
|
||||
import { AdminEmailScheduledPage } from "~/components/screens/admin/sales/email/AdminEmailScheduledPage";
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runAsAdminEmailOperator } from "~/services/admin/admin-email-connections.server";
|
||||
import { adminEmailWorkspaceHrefs, applyAdminEmailWorkspaceAction, readAdminEmailScheduled } from "~/services/admin/admin-email-workspace.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type ActionData = { intent?: string; ok?: true; messageKey?: string; error?: string };
|
||||
|
||||
const SCHEDULED_SUCCESS_KEYS: Readonly<Record<string, string>> = {
|
||||
"queue-email": "admin.sales.email.toast.emailQueued",
|
||||
"queue-bulk-email": "admin.sales.email.toast.bulkQueued",
|
||||
"save-policy": "admin.sales.email.toast.policySaved",
|
||||
};
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
return runAsAdminEmailOperator(
|
||||
request,
|
||||
[
|
||||
"admin_sales.email.send",
|
||||
"admin_sales.communication.read_all",
|
||||
],
|
||||
async (context) => ({
|
||||
vm: buildAdminEmailScheduledVM(await readAdminEmailScheduled(context)),
|
||||
hrefs: adminEmailWorkspaceHrefs(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const parsed = adminEmailWorkspaceActionSchema.safeParse(parsePayload(await request.formData()));
|
||||
if (!parsed.success || (parsed.data.intent !== "queue-email" && parsed.data.intent !== "queue-bulk-email" && parsed.data.intent !== "save-policy")) {
|
||||
return Response.json({ error: t("admin.sales.email.errors.invalidAction") }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await runAsAdminEmailOperator(
|
||||
request,
|
||||
parsed.data.intent === "save-policy" || parsed.data.intent === "queue-bulk-email" ? "admin_sales.email.bulk_send" : "admin_sales.email.send",
|
||||
(context) => applyAdminEmailWorkspaceAction(context, parsed.data)
|
||||
);
|
||||
return { intent: parsed.data.intent, ok: true, messageKey: SCHEDULED_SUCCESS_KEYS[parsed.data.intent] } satisfies ActionData;
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.sales.email.errors.saveFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export function HydrateFallback() {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminEmailScheduledRoute() {
|
||||
const { vm, hrefs } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const submit = useSubmit();
|
||||
|
||||
useSaveToast(actionData?.ok ? actionData : undefined);
|
||||
const submitIntent = (intent: string, input: object) => {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("payload", JSON.stringify({ intent, ...input }));
|
||||
submit(form, { method: "post" });
|
||||
};
|
||||
return (
|
||||
<AdminEmailScheduledPage
|
||||
vm={vm}
|
||||
hrefs={hrefs}
|
||||
composeDefaults={{
|
||||
contactId: searchParams.get("contactId"),
|
||||
dealId: searchParams.get("dealId"),
|
||||
toAddress: searchParams.get("to") ?? "",
|
||||
}}
|
||||
submitting={navigation.state === "submitting"}
|
||||
errorMessage={actionData?.error}
|
||||
actions={{
|
||||
onQueueEmail: (input) => submitIntent("queue-email", input),
|
||||
onQueueBulkEmail: (input) => submitIntent("queue-bulk-email", input),
|
||||
onSavePolicy: (input) => submitIntent("save-policy", input),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function parsePayload(form: FormData) {
|
||||
try {
|
||||
return JSON.parse(String(form.get("payload") ?? "{}")) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import { adminEmailWorkspaceActionSchema, buildAdminEmailTemplatesVM } from "@hivegrid/view-models";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminEmailTemplatesPage } from "~/components/screens/admin/sales/email/AdminEmailTemplatesPage";
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runAsAdminEmailOperator } from "~/services/admin/admin-email-connections.server";
|
||||
import { adminEmailWorkspaceHrefs, applyAdminEmailWorkspaceAction, readAdminEmailTemplates } from "~/services/admin/admin-email-workspace.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type ActionData = { intent?: string; ok?: true; messageKey?: string; error?: string };
|
||||
|
||||
const TEMPLATE_SUCCESS_KEYS: Readonly<Record<string, string>> = {
|
||||
"save-template": "admin.sales.email.toast.templateSaved",
|
||||
"save-snippet": "admin.sales.email.toast.snippetSaved",
|
||||
"save-signature": "admin.sales.email.toast.signatureSaved",
|
||||
};
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
return runAsAdminEmailOperator(request, "admin_sales.email.send", async (context) => ({
|
||||
vm: buildAdminEmailTemplatesVM(await readAdminEmailTemplates(context)),
|
||||
hrefs: adminEmailWorkspaceHrefs(),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const parsed = adminEmailWorkspaceActionSchema.safeParse(parsePayload(await request.formData()));
|
||||
if (!parsed.success || !["save-template", "save-snippet", "save-signature"].includes(parsed.data.intent)) {
|
||||
return Response.json({ error: t("admin.sales.email.errors.invalidAction") }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await runAsAdminEmailOperator(request, "admin_sales.email.send", (context) => applyAdminEmailWorkspaceAction(context, parsed.data));
|
||||
return { intent: parsed.data.intent, ok: true, messageKey: TEMPLATE_SUCCESS_KEYS[parsed.data.intent] } satisfies ActionData;
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.sales.email.errors.saveFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export function HydrateFallback() {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminEmailTemplatesRoute() {
|
||||
const { vm, hrefs } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
|
||||
useSaveToast(actionData?.ok ? actionData : undefined);
|
||||
const submitIntent = (intent: string, input: object) => {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("payload", JSON.stringify({ intent, ...input }));
|
||||
submit(form, { method: "post" });
|
||||
};
|
||||
return (
|
||||
<AdminEmailTemplatesPage
|
||||
vm={vm}
|
||||
hrefs={hrefs}
|
||||
submitting={navigation.state === "submitting"}
|
||||
errorMessage={actionData?.error}
|
||||
actions={{
|
||||
onSaveTemplate: (input) => submitIntent("save-template", input),
|
||||
onSaveSnippet: (input) => submitIntent("save-snippet", input),
|
||||
onSaveSignature: (input) => submitIntent("save-signature", input),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function parsePayload(form: FormData) {
|
||||
try {
|
||||
return JSON.parse(String(form.get("payload") ?? "{}")) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user