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
+198
@@ -0,0 +1,198 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { actor, createTenant, pipelineService } = vi.hoisted(() => ({
|
||||
actor: vi.fn((reason: string) => ({
|
||||
adminUserId: "admin_1",
|
||||
reason,
|
||||
})),
|
||||
createTenant: vi.fn(),
|
||||
pipelineService: {
|
||||
linkDealToTenant: vi.fn(),
|
||||
},
|
||||
}));
|
||||
const { telephonyActions } = vi.hoisted(() => ({
|
||||
telephonyActions: { queueOutboundCall: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("~/components/screens/admin/sales/deals/AdminSalesDealDetailPage", () => ({
|
||||
AdminSalesDealDetailPage: () => null,
|
||||
}));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
locale: "de-DE",
|
||||
t: (key: string) => key,
|
||||
})),
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-sales-pipeline.server", () => ({
|
||||
runAsAdminSalesPipelineOperator: vi.fn(
|
||||
async (_request, _permission, operation) =>
|
||||
operation({
|
||||
service: pipelineService,
|
||||
actor,
|
||||
adminUserId: "admin_1",
|
||||
firstName: "Raffael",
|
||||
locale: "de-DE",
|
||||
canWrite: true,
|
||||
})
|
||||
),
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-sales-tenant.server", () => ({
|
||||
createAndLinkAdminSalesTenant: createTenant,
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-sales-tasks.server", () => ({
|
||||
runAsAdminSalesTaskOperator: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-telephony-connections.server", () => ({
|
||||
runAsAdminTelephonyOperator: vi.fn(
|
||||
async (_request, _permission, operation) =>
|
||||
operation({
|
||||
actions: telephonyActions,
|
||||
actor,
|
||||
adminUserId: "admin_1",
|
||||
})
|
||||
),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runAsAdminSalesPipelineOperator } from "~/services/admin/admin-sales-pipeline.server";
|
||||
import { createAndLinkAdminSalesTenant } from "~/services/admin/admin-sales-tenant.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { runAsAdminTelephonyOperator } from "~/services/admin/admin-telephony-connections.server";
|
||||
import { action } from "./$id";
|
||||
|
||||
function actionRequest(values: Record<string, string>): Request {
|
||||
return new Request("https://admin.hivegrid.de/sales/deals/deal_1", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({
|
||||
intent: "tenant-promote",
|
||||
confirmed: "true",
|
||||
reason: "Kunde ausdrücklich freigegeben",
|
||||
...values,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
describe("admin sales deal tenant promotion action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
pipelineService.linkDealToTenant.mockResolvedValue({
|
||||
id: "deal_1",
|
||||
tenantId: "tenant_1",
|
||||
});
|
||||
createTenant.mockResolvedValue({
|
||||
dealId: "deal_1",
|
||||
tenantId: "tenant_reserved",
|
||||
});
|
||||
});
|
||||
|
||||
it("starts click-to-call for the selected buying-center contact", async () => {
|
||||
const response = await action({
|
||||
request: actionRequest({
|
||||
intent: "call",
|
||||
contactId: "contact_1",
|
||||
}),
|
||||
params: { id: "deal_1" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(runAsAdminTelephonyOperator).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin_sales.phone.call",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(telephonyActions.queueOutboundCall).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
adminUserId: "admin_1",
|
||||
contactId: "contact_1",
|
||||
dealId: "deal_1",
|
||||
})
|
||||
);
|
||||
expect(response.status).toBe(303);
|
||||
});
|
||||
|
||||
it("links an existing tenant only after an explicit confirmation", async () => {
|
||||
const request = actionRequest({
|
||||
mode: "link_existing",
|
||||
tenantId: "tenant_1",
|
||||
});
|
||||
const response = await action({
|
||||
request,
|
||||
params: { id: "deal_1" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(validateCSRFToken).toHaveBeenCalledWith(request);
|
||||
expect(runAsAdminSalesPipelineOperator).toHaveBeenCalledWith(
|
||||
request,
|
||||
"admin_sales.crm.write",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(pipelineService.linkDealToTenant).toHaveBeenCalledWith({
|
||||
dealId: "deal_1",
|
||||
tenantId: "tenant_1",
|
||||
actor: {
|
||||
adminUserId: "admin_1",
|
||||
reason: "Kunde ausdrücklich freigegeben",
|
||||
},
|
||||
});
|
||||
expect(createAndLinkAdminSalesTenant).not.toHaveBeenCalled();
|
||||
expect(response.status).toBe(303);
|
||||
});
|
||||
|
||||
it("creates a pending-owner tenant and links it through the dedicated service", async () => {
|
||||
const request = actionRequest({
|
||||
mode: "create_new",
|
||||
tenantName: "Muster GmbH",
|
||||
tenantSlug: "muster-gmbh",
|
||||
ownerEmail: "ada@example.test",
|
||||
ownerFirstName: "Ada",
|
||||
ownerLastName: "Lovelace",
|
||||
});
|
||||
const response = await action({
|
||||
request,
|
||||
params: { id: "deal_1" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(createAndLinkAdminSalesTenant).toHaveBeenCalledWith({
|
||||
request,
|
||||
dealId: "deal_1",
|
||||
tenantName: "Muster GmbH",
|
||||
tenantSlug: "muster-gmbh",
|
||||
ownerEmail: "ada@example.test",
|
||||
ownerFirstName: "Ada",
|
||||
ownerLastName: "Lovelace",
|
||||
admin: {
|
||||
id: "admin_1",
|
||||
firstName: "Raffael",
|
||||
locale: "de-DE",
|
||||
},
|
||||
actor: {
|
||||
adminUserId: "admin_1",
|
||||
reason: "Kunde ausdrücklich freigegeben",
|
||||
},
|
||||
});
|
||||
expect(pipelineService.linkDealToTenant).not.toHaveBeenCalled();
|
||||
expect(response.status).toBe(303);
|
||||
});
|
||||
|
||||
it("rejects an unconfirmed promotion before any tenant mutation", async () => {
|
||||
const request = actionRequest({
|
||||
mode: "link_existing",
|
||||
tenantId: "tenant_1",
|
||||
confirmed: "false",
|
||||
});
|
||||
const response = await action({
|
||||
request,
|
||||
params: { id: "deal_1" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(pipelineService.linkDealToTenant).not.toHaveBeenCalled();
|
||||
expect(createAndLinkAdminSalesTenant).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
import {
|
||||
adminDealBuyingCenterActionSchema,
|
||||
adminDealMoveActionSchema,
|
||||
adminDealTenantPromotionActionSchema,
|
||||
adminDealUpdateActionSchema,
|
||||
adminSalesTaskCompleteActionSchema,
|
||||
adminSalesTaskCreateActionSchema,
|
||||
buildAdminDealDetailVM,
|
||||
buildAdminSalesTaskRows,
|
||||
} from "@hivegrid/view-models";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminSalesDealDetailPage } from "~/components/screens/admin/sales/deals/AdminSalesDealDetailPage";
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runAsAdminSalesPipelineOperator } from "~/services/admin/admin-sales-pipeline.server";
|
||||
import { createAndLinkAdminSalesTenant } from "~/services/admin/admin-sales-tenant.server";
|
||||
import { runAsAdminSalesTaskOperator } from "~/services/admin/admin-sales-tasks.server";
|
||||
import { runAsAdminTelephonyOperator } from "~/services/admin/admin-telephony-connections.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const { locale } = await getTranslations(request);
|
||||
const pipelineResult = await runAsAdminSalesPipelineOperator(request, "admin_sales.crm.read", async ({ service, canWrite }) => {
|
||||
const deal = await service.getDealDetail(params.id ?? "");
|
||||
if (!deal) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
const [board, contactOptions, tenantOptions] = await Promise.all([
|
||||
service.getBoard(deal.pipelineId),
|
||||
service.listContactOptions(),
|
||||
service.listTenantOptions(),
|
||||
]);
|
||||
if (!board) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
return {
|
||||
vm: buildAdminDealDetailVM({
|
||||
now: new Date(),
|
||||
locale,
|
||||
deal,
|
||||
stages: board.stages.map((stage) => ({
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
kind: stage.kind,
|
||||
requiredFields: stage.requiredFields,
|
||||
})),
|
||||
lossReasons: board.lossReasons,
|
||||
contactOptions,
|
||||
tenantOptions,
|
||||
buildContactHref: (contactId) =>
|
||||
adminPath(`sales/contacts/${encodeURIComponent(contactId)}`, {
|
||||
mode: "host-aware",
|
||||
}),
|
||||
buildTenantHref: (tenantId) =>
|
||||
adminPath(`accounts/${encodeURIComponent(tenantId)}`, {
|
||||
mode: "host-aware",
|
||||
}),
|
||||
canWrite,
|
||||
}),
|
||||
};
|
||||
});
|
||||
const taskResult = await runAsAdminSalesTaskOperator(request, "admin_sales.crm.read", async ({ service, adminUserId, timeZone, canWrite }) => {
|
||||
const tasks = await service.listForDeal(params.id ?? "");
|
||||
return {
|
||||
taskVm: {
|
||||
tasks: buildAdminSalesTaskRows({
|
||||
now: new Date(),
|
||||
locale,
|
||||
tasks,
|
||||
buildContactHref: (contactId) =>
|
||||
adminPath(`sales/contacts/${encodeURIComponent(contactId)}`, {
|
||||
mode: "host-aware",
|
||||
}),
|
||||
buildDealHref: (dealId) =>
|
||||
adminPath(`sales/deals/${encodeURIComponent(dealId)}`, {
|
||||
mode: "host-aware",
|
||||
}),
|
||||
canWrite,
|
||||
}),
|
||||
currentAdminUserId: adminUserId,
|
||||
timeZone,
|
||||
canWrite,
|
||||
},
|
||||
};
|
||||
});
|
||||
return { ...pipelineResult, ...taskResult };
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const dealId = params.id ?? "";
|
||||
|
||||
try {
|
||||
if (intent === "call") {
|
||||
const contactId = String(form.get("contactId") ?? "");
|
||||
await runAsAdminTelephonyOperator(request, "admin_sales.phone.call", ({ actions, adminUserId, actor }) =>
|
||||
actions.queueOutboundCall({
|
||||
adminUserId,
|
||||
contactId,
|
||||
dealId,
|
||||
idempotencyKey: randomUUID(),
|
||||
actor: actor(t("admin.sales.telephony.audit.queue_call")),
|
||||
})
|
||||
);
|
||||
const target = new URL(adminPath("sales/calls", { mode: "host-aware" }), request.url);
|
||||
target.searchParams.set("toast", "admin.sales.deals.toast.callQueued");
|
||||
return Response.redirect(target, 303);
|
||||
}
|
||||
await runAsAdminSalesPipelineOperator(request, "admin_sales.crm.write", async ({ service, actor, adminUserId, firstName, locale }) => {
|
||||
if (intent === "move") {
|
||||
const command = adminDealMoveActionSchema.parse({
|
||||
dealId,
|
||||
targetStageId: form.get("targetStageId"),
|
||||
lossReasonId: optionalFormString(form.get("lossReasonId")),
|
||||
lossReasonNote: optionalFormString(form.get("lossReasonNote")),
|
||||
reason: form.get("reason"),
|
||||
});
|
||||
await service.moveDeal({ ...command, actor: actor(command.reason) });
|
||||
return;
|
||||
}
|
||||
if (intent === "update") {
|
||||
const command = adminDealUpdateActionSchema.parse({
|
||||
dealId,
|
||||
amountCents: nullableInteger(form.get("amountCents")),
|
||||
currencyCode: form.get("currencyCode"),
|
||||
expectedCloseDate: optionalFormString(form.get("expectedCloseDate")),
|
||||
nextStep: optionalFormString(form.get("nextStep")),
|
||||
nextStepDueAt: optionalFormString(form.get("nextStepDueAt")),
|
||||
reason: form.get("reason"),
|
||||
});
|
||||
await service.updateDeal({
|
||||
dealId,
|
||||
amountCents: command.amountCents,
|
||||
currencyCode: command.currencyCode,
|
||||
expectedCloseDate: command.expectedCloseDate ? new Date(`${command.expectedCloseDate}T00:00:00.000Z`) : null,
|
||||
nextStep: command.nextStep,
|
||||
nextStepDueAt: command.nextStepDueAt ? new Date(command.nextStepDueAt) : null,
|
||||
actor: actor(command.reason),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (intent === "buying-center") {
|
||||
const command = adminDealBuyingCenterActionSchema.parse({
|
||||
dealId,
|
||||
contactIds: form.getAll("contactId").map(String),
|
||||
primaryContactId: optionalFormString(form.get("primaryContactId")),
|
||||
roles: parseRoles(form.get("roles")),
|
||||
reason: form.get("reason"),
|
||||
});
|
||||
await service.replaceDealContacts({
|
||||
dealId,
|
||||
contactIds: command.contactIds,
|
||||
primaryContactId: command.primaryContactId,
|
||||
roles: command.roles,
|
||||
actor: actor(command.reason),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (intent === "tenant-promote") {
|
||||
const command = adminDealTenantPromotionActionSchema.parse({
|
||||
dealId,
|
||||
mode: form.get("mode"),
|
||||
tenantId: optionalFormString(form.get("tenantId")),
|
||||
tenantName: optionalFormString(form.get("tenantName")),
|
||||
tenantSlug: optionalFormString(form.get("tenantSlug")),
|
||||
ownerEmail: optionalFormString(form.get("ownerEmail")),
|
||||
ownerFirstName: optionalFormString(form.get("ownerFirstName")),
|
||||
ownerLastName: optionalFormString(form.get("ownerLastName")),
|
||||
confirmed: form.get("confirmed") === "true",
|
||||
reason: form.get("reason"),
|
||||
});
|
||||
const promotionActor = actor(command.reason);
|
||||
if (command.mode === "link_existing") {
|
||||
await service.linkDealToTenant({
|
||||
dealId,
|
||||
tenantId: command.tenantId!,
|
||||
actor: promotionActor,
|
||||
});
|
||||
} else {
|
||||
await createAndLinkAdminSalesTenant({
|
||||
request,
|
||||
dealId,
|
||||
tenantName: command.tenantName!,
|
||||
tenantSlug: command.tenantSlug!,
|
||||
ownerEmail: command.ownerEmail!,
|
||||
ownerFirstName: command.ownerFirstName!,
|
||||
ownerLastName: command.ownerLastName!,
|
||||
admin: {
|
||||
id: adminUserId,
|
||||
firstName,
|
||||
locale,
|
||||
},
|
||||
actor: promotionActor,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (intent === "task-create") {
|
||||
const command = adminSalesTaskCreateActionSchema.parse({
|
||||
title: form.get("title"),
|
||||
description: optionalFormString(form.get("description")),
|
||||
contactId: optionalFormString(form.get("contactId")),
|
||||
dealId,
|
||||
assignedToAdminUserId: form.get("assignedToAdminUserId"),
|
||||
dueAt: form.get("dueAt"),
|
||||
timeZone: form.get("timeZone"),
|
||||
reminderAt: optionalFormString(form.get("reminderAt")),
|
||||
priority: form.get("priority"),
|
||||
recurrenceFrequency: optionalFormString(form.get("recurrenceFrequency")),
|
||||
recurrenceInterval: Number(form.get("recurrenceInterval")),
|
||||
recurrenceEndsAt: optionalFormString(form.get("recurrenceEndsAt")),
|
||||
reason: form.get("reason"),
|
||||
});
|
||||
await runAsAdminSalesTaskOperator(request, "admin_sales.crm.write", ({ service: taskService, actor: taskActor }) =>
|
||||
taskService.createTask({
|
||||
...command,
|
||||
dueAt: new Date(command.dueAt),
|
||||
reminderAt: command.reminderAt ? new Date(command.reminderAt) : null,
|
||||
recurrence: command.recurrenceFrequency
|
||||
? {
|
||||
frequency: command.recurrenceFrequency,
|
||||
interval: command.recurrenceInterval,
|
||||
endsAt: command.recurrenceEndsAt ? new Date(command.recurrenceEndsAt) : null,
|
||||
}
|
||||
: null,
|
||||
actor: taskActor(command.reason),
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (intent === "task-complete") {
|
||||
const command = adminSalesTaskCompleteActionSchema.parse({
|
||||
taskId: form.get("taskId"),
|
||||
reason: form.get("reason"),
|
||||
});
|
||||
await runAsAdminSalesTaskOperator(request, "admin_sales.crm.write", ({ service: taskService, actor: taskActor }) =>
|
||||
taskService.completeTask({
|
||||
taskId: command.taskId,
|
||||
actor: taskActor(command.reason),
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
throw new Error("INVALID_INTENT");
|
||||
});
|
||||
const messageKeyByIntent: Record<string, string> = {
|
||||
move: "admin.sales.deals.toast.moved",
|
||||
update: "admin.sales.deals.toast.updated",
|
||||
"buying-center": "admin.sales.deals.toast.buyingCenterSaved",
|
||||
"tenant-promote": "admin.sales.deals.toast.tenantLinked",
|
||||
"task-create": "admin.sales.tasks.toast.created",
|
||||
"task-complete": "admin.sales.tasks.toast.completed",
|
||||
};
|
||||
const target = new URL(adminPath(`sales/deals/${encodeURIComponent(dealId)}`, { mode: "host-aware" }), request.url);
|
||||
target.searchParams.set("toast", messageKeyByIntent[intent] ?? "admin.sales.deals.toast.updated");
|
||||
return Response.redirect(target, 303);
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.sales.deals.errors.actionFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export function HydrateFallback(): React.JSX.Element {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminSalesDealDetailRoute(): React.JSX.Element {
|
||||
const { t } = useTranslation();
|
||||
const { vm, taskVm } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData() as { readonly error?: string } | undefined;
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const primaryEmailContact = vm.contacts.find((contact) => contact.isPrimary && contact.email);
|
||||
|
||||
function submitInput(intent: string, input: Record<string, unknown>) {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("intent", intent);
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
if (value === null || value === undefined) continue;
|
||||
if (key === "contactIds" && Array.isArray(value)) {
|
||||
value.forEach((entry) => form.append("contactId", String(entry)));
|
||||
} else if (key === "roles") {
|
||||
form.set("roles", JSON.stringify(value));
|
||||
} else {
|
||||
form.set(key, String(value));
|
||||
}
|
||||
}
|
||||
submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminSalesDealDetailPage
|
||||
vm={vm}
|
||||
taskVm={taskVm}
|
||||
backHref={`${adminPath("sales/deals", { mode: "host-aware" })}?pipeline=${encodeURIComponent(vm.pipelineId)}`}
|
||||
emailComposeHref={
|
||||
primaryEmailContact
|
||||
? `${adminPath("sales/email/scheduled", { mode: "host-aware" })}?dealId=${encodeURIComponent(vm.id)}&contactId=${encodeURIComponent(primaryEmailContact.id)}&to=${encodeURIComponent(primaryEmailContact.email!)}`
|
||||
: null
|
||||
}
|
||||
submitting={navigation.state === "submitting"}
|
||||
errorMessage={actionData?.error ?? null}
|
||||
actions={{
|
||||
onMove: (input) => submitInput("move", input),
|
||||
onUpdate: (input) => submitInput("update", input),
|
||||
onReplaceBuyingCenter: (input) => submitInput("buying-center", { ...input, contactIds: input.contactIds }),
|
||||
onPromoteTenant: (input) => submitInput("tenant-promote", input),
|
||||
onCreateTask: (input) => submitInput("task-create", input),
|
||||
onCompleteTask: (taskId) =>
|
||||
submitInput("task-complete", {
|
||||
taskId,
|
||||
reason: t("admin.sales.tasks.audit.completed"),
|
||||
}),
|
||||
onCall: (contactId) => submitInput("call", { contactId }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function optionalFormString(value: FormDataEntryValue | null): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function nullableInteger(value: FormDataEntryValue | null): number | null {
|
||||
if (typeof value !== "string" || value.trim() === "") return null;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) ? parsed : Number.NaN;
|
||||
}
|
||||
|
||||
function parseRoles(value: FormDataEntryValue | null): Record<string, string> {
|
||||
if (typeof value !== "string") return {};
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
||||
return Object.fromEntries(Object.entries(parsed).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { service, actor } = vi.hoisted(() => ({
|
||||
service: {
|
||||
listPipelines: vi.fn(),
|
||||
getBoard: vi.fn(),
|
||||
moveDeal: vi.fn(),
|
||||
createPipeline: vi.fn(),
|
||||
},
|
||||
actor: vi.fn((reason: string) => ({ adminUserId: "admin_1", reason })),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/ui-app", () => ({ toAdminSalesDealsProps: (vm: unknown) => vm }));
|
||||
vi.mock("~/components/screens/admin/sales/deals/AdminSalesDealPipelinePage", () => ({ AdminSalesDealPipelinePage: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ locale: "de-DE", t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-sales-pipeline.server", () => ({
|
||||
runAsAdminSalesPipelineOperator: vi.fn(async (_request, _permission, operation) =>
|
||||
operation({ service, actor, canWrite: true, canConfigure: true })
|
||||
),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
|
||||
import { runAsAdminSalesPipelineOperator } from "~/services/admin/admin-sales-pipeline.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { action, loader } from "./index";
|
||||
|
||||
describe("admin sales deals route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service.listPipelines.mockResolvedValue([{ id: "pipeline_1", name: "SaaS Sales", isDefault: true }]);
|
||||
service.getBoard.mockResolvedValue({
|
||||
pipeline: { id: "pipeline_1", name: "SaaS Sales", description: null },
|
||||
stages: [],
|
||||
lossReasons: [],
|
||||
});
|
||||
service.moveDeal.mockResolvedValue({ id: "deal_1" });
|
||||
});
|
||||
|
||||
it("builds the pipeline VM behind the smallest read permission", async () => {
|
||||
const result = await loader({
|
||||
request: new Request("https://admin.hivegrid.de/sales/deals?pipeline=pipeline_1"),
|
||||
params: {},
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(runAsAdminSalesPipelineOperator).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin_sales.crm.read",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(service.getBoard).toHaveBeenCalledWith("pipeline_1");
|
||||
expect(result.vm).toMatchObject({
|
||||
status: "ready",
|
||||
pipelineId: "pipeline_1",
|
||||
permissions: { canWrite: true, canConfigure: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("validates CSRF and moves a deal through the write-gated domain service", async () => {
|
||||
const response = await action({
|
||||
request: new Request("https://admin.hivegrid.de/sales/deals", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({
|
||||
intent: "move",
|
||||
dealId: "deal_1",
|
||||
targetStageId: "stage_demo",
|
||||
reason: "Deal nach Demo verschoben",
|
||||
}),
|
||||
}),
|
||||
params: {},
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(runAsAdminSalesPipelineOperator).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin_sales.crm.write",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(service.moveDeal).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dealId: "deal_1",
|
||||
targetStageId: "stage_demo",
|
||||
actor: { adminUserId: "admin_1", reason: "Deal nach Demo verschoben" },
|
||||
})
|
||||
);
|
||||
expect(response.status).toBe(303);
|
||||
});
|
||||
|
||||
it("creates the default pipeline with request-locale labels", async () => {
|
||||
const response = await action({
|
||||
request: new Request("https://admin.hivegrid.de/sales/deals", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ intent: "create-default-pipeline" }),
|
||||
}),
|
||||
params: {},
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(service.createPipeline).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "admin.sales.pipelineSettings.defaults.pipelineName",
|
||||
stages: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "admin.sales.pipelineSettings.defaults.stages.quote" }),
|
||||
expect.objectContaining({ name: "admin.sales.pipelineSettings.defaults.stages.won" }),
|
||||
]),
|
||||
lossReasons: [
|
||||
"admin.sales.pipelineSettings.defaults.lossReasons.noBudget",
|
||||
"admin.sales.pipelineSettings.defaults.lossReasons.noNeed",
|
||||
"admin.sales.pipelineSettings.defaults.lossReasons.competitor",
|
||||
"admin.sales.pipelineSettings.defaults.lossReasons.timing",
|
||||
"admin.sales.pipelineSettings.defaults.lossReasons.badFit",
|
||||
"admin.sales.pipelineSettings.defaults.lossReasons.noResponse",
|
||||
],
|
||||
})
|
||||
);
|
||||
expect(response.status).toBe(303);
|
||||
});
|
||||
});
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import { ADMIN_SAAS_PIPELINE_BLUEPRINT, type AdminPipelineStageInput } from "@hivegrid/db/admin-sales-pipeline.server";
|
||||
import { adminDealMoveActionSchema, buildAdminDealPipelineVM } from "@hivegrid/view-models";
|
||||
import { toAdminSalesDealsProps } from "@hivegrid/ui-app";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useNavigate, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminSalesDealPipelinePage } from "~/components/screens/admin/sales/deals/AdminSalesDealPipelinePage";
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runAsAdminSalesPipelineOperator } from "~/services/admin/admin-sales-pipeline.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const { locale } = await getTranslations(request);
|
||||
return runAsAdminSalesPipelineOperator(request, "admin_sales.crm.read", async ({ service, canWrite, canConfigure }) => {
|
||||
const pipelineId = new URL(request.url).searchParams.get("pipeline");
|
||||
const [pipelines, board] = await Promise.all([service.listPipelines(), service.getBoard(pipelineId)]);
|
||||
return {
|
||||
vm: toAdminSalesDealsProps(
|
||||
buildAdminDealPipelineVM({
|
||||
now: new Date(),
|
||||
locale,
|
||||
pipelines,
|
||||
board,
|
||||
buildDealHref: (dealId) => adminPath(`sales/deals/${encodeURIComponent(dealId)}`, { mode: "host-aware" }),
|
||||
permissions: { canRead: true, canWrite, canConfigure },
|
||||
})
|
||||
),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
|
||||
try {
|
||||
if (intent === "move") {
|
||||
const command = adminDealMoveActionSchema.parse({
|
||||
dealId: form.get("dealId"),
|
||||
targetStageId: form.get("targetStageId"),
|
||||
lossReasonId: optionalFormString(form.get("lossReasonId")),
|
||||
lossReasonNote: optionalFormString(form.get("lossReasonNote")),
|
||||
reason: form.get("reason"),
|
||||
});
|
||||
await runAsAdminSalesPipelineOperator(request, "admin_sales.crm.write", ({ service, actor }) =>
|
||||
service.moveDeal({ ...command, actor: actor(command.reason) })
|
||||
);
|
||||
} else if (intent === "create-default-pipeline") {
|
||||
await runAsAdminSalesPipelineOperator(request, "admin_sales.crm.assign", ({ service, actor }) =>
|
||||
service.createPipeline({
|
||||
name: t("admin.sales.pipelineSettings.defaults.pipelineName"),
|
||||
description: t("admin.sales.pipelineSettings.defaultPipelineDescription"),
|
||||
isDefault: true,
|
||||
stages: ADMIN_SAAS_PIPELINE_BLUEPRINT.map(
|
||||
(stage, position): AdminPipelineStageInput => ({
|
||||
name: t(`admin.sales.pipelineSettings.defaults.stages.${stage.key}`),
|
||||
position,
|
||||
kind: stage.kind,
|
||||
probabilityBasisPoints: stage.probabilityBasisPoints,
|
||||
agingThresholdDays: stage.agingThresholdDays,
|
||||
requiredFields:
|
||||
stage.key === "demo"
|
||||
? ["nextStep"]
|
||||
: stage.key === "quote"
|
||||
? ["amountCents", "expectedCloseDate", "nextStep"]
|
||||
: stage.key === "won"
|
||||
? ["amountCents", "companyId", "primaryContactId"]
|
||||
: stage.key === "lost"
|
||||
? ["lossReasonId"]
|
||||
: [],
|
||||
})
|
||||
),
|
||||
lossReasons: ["noBudget", "noNeed", "competitor", "timing", "badFit", "noResponse"].map((key) =>
|
||||
t(`admin.sales.pipelineSettings.defaults.lossReasons.${key}`)
|
||||
),
|
||||
actor: actor(t("admin.sales.deals.audit.defaultPipeline")),
|
||||
})
|
||||
);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
const target = new URL(adminPath("sales/deals", { mode: "host-aware" }), request.url);
|
||||
target.searchParams.set("toast", intent === "move" ? "admin.sales.deals.toast.moved" : "admin.sales.deals.toast.defaultPipelineCreated");
|
||||
return Response.redirect(target, 303);
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.sales.deals.errors.actionFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export function HydrateFallback(): React.JSX.Element {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminSalesDealsIndexRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData() as { readonly error?: string } | undefined;
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
const submit = useSubmit();
|
||||
const submitting = navigation.state === "submitting";
|
||||
|
||||
return (
|
||||
<AdminSalesDealPipelinePage
|
||||
vm={vm}
|
||||
submitting={submitting}
|
||||
errorMessage={actionData?.error ?? null}
|
||||
actions={{
|
||||
onSwitchPipeline: (pipelineId) => {
|
||||
const search = new URLSearchParams({ pipeline: pipelineId });
|
||||
void navigate(`${adminPath("sales/deals", { mode: "host-aware" })}?${search}`);
|
||||
},
|
||||
onMove: (input) => {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("intent", "move");
|
||||
form.set("dealId", input.dealId);
|
||||
form.set("targetStageId", input.targetStageId);
|
||||
if (input.lossReasonId) form.set("lossReasonId", input.lossReasonId);
|
||||
if (input.lossReasonNote) form.set("lossReasonNote", input.lossReasonNote);
|
||||
form.set("reason", input.reason);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onCreateDefaultPipeline: () => {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("intent", "create-default-pipeline");
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onOpenSettings: () => void navigate(adminPath("settings/pipelines", { mode: "host-aware" })),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function optionalFormString(value: FormDataEntryValue | null): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
Reference in new issue
Block a user