Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/worker/src/jobs/form-submission-actions.test.ts
T

92 lines
3.1 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { verifyMarketingToken } from "@hivegrid/foundation/marketing-token";
import { runStartDoubleOptInFormAction, type StartDoubleOptInPrisma } from "./form-submission-actions.js";
type PublishedOptInEvent = Parameters<Parameters<typeof runStartDoubleOptInFormAction>[0]["publishOutboxEvent"]>[0];
const env = {
APP_URL: "https://app.example.test",
MARKETING_TOKEN_SECRET: "x".repeat(40),
};
function prismaStub(overrides: Partial<StartDoubleOptInPrisma> = {}): StartDoubleOptInPrisma {
return {
kontakt: {
findFirst: vi.fn(async () => ({ id: "kontakt_1", primaerEmail: "Ada@Example.com", vorname: "Ada", nachname: "Lovelace" })),
},
kontaktMarketingConsent: {
upsert: vi.fn(async () => ({})),
},
...overrides,
};
}
describe("runStartDoubleOptInFormAction", () => {
it("upserts single consent and queues the double-opt-in mail", async () => {
const prisma = prismaStub();
const publishOutboxEvent = vi.fn(async (event: PublishedOptInEvent) => {
void event;
});
const result = await runStartDoubleOptInFormAction({
prisma,
publishOutboxEvent,
tenantId: "tenant_1",
formId: "form_1",
submissionId: "sub_1",
actionId: "action_1",
mapped: { email: "ada@example.com" },
config: {},
env,
now: () => new Date("2026-07-09T10:00:00.000Z"),
});
expect(result).toEqual({ status: "started", kontaktId: "kontakt_1", email: "ada@example.com" });
expect(prisma.kontaktMarketingConsent.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId_kontaktId: { tenantId: "tenant_1", kontaktId: "kontakt_1" } },
create: expect.objectContaining({ status: "single", optInSource: "form:form_1" }),
}),
);
const event = vi.mocked(publishOutboxEvent).mock.calls[0]?.[0];
expect(event).toMatchObject({
tenantId: "tenant_1",
type: "mail.transactional.send",
dispatchKey: "form-action-optin:sub_1:action_1",
payload: expect.objectContaining({
to: ["ada@example.com"],
subject: "Bitte bestätige deine Anmeldung",
}),
});
const link = String((event?.payload.html as string).match(/https:\/\/app\.example\.test\/optin\/([^"]+)/u)?.[1] ?? "");
expect(verifyMarketingToken(decodeURIComponent(link), { env, expectedPurpose: "optin" })).toMatchObject({
tenantId: "tenant_1",
kontaktId: "kontakt_1",
});
});
it("skips when no matching contact exists", async () => {
const prisma = prismaStub({
kontakt: {
findFirst: vi.fn(async () => null),
},
});
const publishOutboxEvent = vi.fn(async (event: PublishedOptInEvent) => {
void event;
});
await expect(runStartDoubleOptInFormAction({
prisma,
publishOutboxEvent,
tenantId: "tenant_1",
formId: "form_1",
submissionId: "sub_1",
actionId: "action_1",
mapped: { email: "nobody@example.com" },
config: {},
env,
})).resolves.toEqual({ status: "skipped", reason: "no_contact" });
expect(publishOutboxEvent).not.toHaveBeenCalled();
});
});