Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/worker/src/jobs/platform-notification-outbox.test.ts
T

284 lines
9.9 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { buildPlatformNotificationJob, buildRetryJobOptions, type NotificationJobDescriptor, type QueueEnqueueOptions } from "@hivegrid/queue";
import type { MailProvider } from "@hivegrid/mail";
import { buildHandlerRegistry } from "../handlers.js";
import {
PLATFORM_NOTIFICATION_OUTBOX_TYPE,
isPlatformNotificationOutboxJob,
parsePlatformNotificationOutboxJob,
runPlatformNotificationOutboxJob,
} from "./platform-notification-outbox.js";
function buildJob(overrides: Record<string, unknown> = {}): unknown {
return {
outboxEventId: "outbox_1",
tenantId: null,
eventType: PLATFORM_NOTIFICATION_OUTBOX_TYPE,
payload: {
deliveryId: "delivery_1",
userId: "user_haris",
sourceKey: "platform-lead:lead_1:email",
channel: "email",
messageKey: "platform.leads.captured",
category: "leads",
metadata: {
leadId: "lead_1",
sourceId: "hivegrid-website",
deeplink: "/leads/lead_1",
},
},
...overrides,
};
}
describe("platform notification outbox parser", () => {
it("parses the strict tenantless PII-free envelope", () => {
const parsed = parsePlatformNotificationOutboxJob(buildJob());
expect(parsed).toEqual({
outboxEventId: "outbox_1",
tenantId: null,
eventType: PLATFORM_NOTIFICATION_OUTBOX_TYPE,
payload: {
deliveryId: "delivery_1",
userId: "user_haris",
sourceKey: "platform-lead:lead_1:email",
channel: "email",
messageKey: "platform.leads.captured",
category: "leads",
metadata: {
leadId: "lead_1",
sourceId: "hivegrid-website",
deeplink: "/leads/lead_1",
},
},
});
expect(isPlatformNotificationOutboxJob(buildJob())).toBe(true);
expect(isPlatformNotificationOutboxJob({ eventType: "billing.subscription.ended" })).toBe(false);
});
it("rejects tenant scope and non-allowlisted PII fields", () => {
expect(() => parsePlatformNotificationOutboxJob(buildJob({ tenantId: "tenant_escape" }))).toThrow("require tenantId=null");
expect(() =>
parsePlatformNotificationOutboxJob(
buildJob({
payload: {
deliveryId: "delivery_1",
userId: "user_haris",
sourceKey: "platform-lead:lead_1:email",
channel: "email",
messageKey: "platform.leads.captured",
email: "lead@example.test",
},
})
)
).toThrow("non-allowlisted fields");
expect(() =>
parsePlatformNotificationOutboxJob(
buildJob({
payload: {
deliveryId: "delivery_1",
userId: "user_haris",
sourceKey: "platform-lead:lead_1:email",
channel: "email",
messageKey: "platform.leads.captured",
metadata: { leadId: "lead_1", message: "private lead text" },
},
})
)
).toThrow("non-allowlisted fields");
});
});
describe("platform notification outbox bridge", () => {
it("enqueues a deterministic retryable worker job without recipient PII", async () => {
const enqueue = vi.fn(async () => undefined);
const logger = { info: vi.fn() };
const result = await runPlatformNotificationOutboxJob(buildJob(), { enqueue, logger });
expect(result).toEqual({ status: "enqueued", outboxEventId: "outbox_1", deliveryId: "delivery_1", channel: "email" });
expect(enqueue).toHaveBeenCalledWith(
expect.objectContaining({
userId: "user_haris",
sourceKey: "platform-lead:lead_1:email",
channel: "email",
messageKey: "platform.leads.captured",
category: "leads",
subject: "Neuer Lead in HiveGrid",
text: expect.stringContaining("Ein neuer Lead ist eingegangen"),
html: expect.stringContaining("https://hivegrid.de/hivegrid-logo.png"),
metadata: {
leadId: "lead_1",
sourceId: "hivegrid-website",
deeplink: "/leads/lead_1",
deliveryId: "delivery_1",
eventId: "outbox_1",
},
}),
{ tenantId: null, idempotencyKey: "platform-notification-outbox:outbox_1" }
);
expect(JSON.stringify(enqueue.mock.calls)).not.toContain("@example.test");
expect(JSON.stringify(logger.info.mock.calls)).not.toContain("haris@example.test");
});
it("keeps in-app delivery PII-free as well", async () => {
const enqueue = vi.fn(async () => undefined);
const job = buildJob({
payload: {
deliveryId: "delivery_1",
userId: "user_haris",
sourceKey: "platform-lead:lead_1:in-app",
channel: "in-app",
messageKey: "platform.leads.captured",
metadata: { leadId: "lead_1" },
},
});
await runPlatformNotificationOutboxJob(job, { enqueue });
expect(enqueue).toHaveBeenCalledWith(expect.not.objectContaining({ email: expect.anything() }), expect.objectContaining({ tenantId: null }));
});
it("bridges an admin sales task reminder without requiring lead metadata", async () => {
const enqueue = vi.fn(async () => undefined);
const job = buildJob({
payload: {
deliveryId: "delivery_task_1",
adminUserId: "admin_1",
sourceKey: "admin-sales:task-reminder:task_1:2026-07-25",
channel: "in-app",
messageKey: "admin.sales.notifications.taskreminder",
category: "sales",
metadata: {
taskId: "task_1",
deeplink: "/sales/tasks/today",
},
},
});
await runPlatformNotificationOutboxJob(job, { enqueue });
expect(enqueue).toHaveBeenCalledWith(
expect.objectContaining({
adminUserId: "admin_1",
messageKey: "admin.sales.notifications.taskreminder",
subject: "Aufgabe ist bald fällig",
metadata: expect.objectContaining({ taskId: "task_1" }),
}),
{ tenantId: null, idempotencyKey: "platform-notification-outbox:outbox_1" }
);
});
it("bridges an opted-in live-open event to the separated admin identity", async () => {
const enqueue = vi.fn(async () => undefined);
const job = buildJob({
payload: {
deliveryId: "delivery_open_1",
adminUserId: "admin_1",
sourceKey: "admin-email-open:event_1",
channel: "in-app",
messageKey: "admin.sales.email.notifications.opened",
category: "admin-sales-email",
metadata: {
emailMessageId: "message_1",
emailEventId: "event_1",
deeplink: "/sales/email",
},
},
});
await runPlatformNotificationOutboxJob(job, { enqueue });
expect(enqueue).toHaveBeenCalledWith(
expect.objectContaining({
adminUserId: "admin_1",
messageKey: "admin.sales.email.notifications.opened",
metadata: expect.objectContaining({
emailMessageId: "message_1",
emailEventId: "event_1",
}),
}),
{
tenantId: null,
idempotencyKey: "platform-notification-outbox:outbox_1",
}
);
});
it("fails closed when a task reminder has no task id", async () => {
const enqueue = vi.fn(async () => undefined);
await expect(
runPlatformNotificationOutboxJob(
buildJob({
payload: {
deliveryId: "delivery_task_1",
userId: "admin_1",
sourceKey: "admin-sales:task-reminder:task_1:2026-07-25",
channel: "in-app",
messageKey: "admin.sales.notifications.taskreminder",
},
}),
{ enqueue }
)
).rejects.toMatchObject({ code: "INVALID_PAYLOAD" });
expect(enqueue).not.toHaveBeenCalled();
});
it("fails closed when a platform notification has no lead id", async () => {
const enqueue = vi.fn(async () => undefined);
await expect(
runPlatformNotificationOutboxJob(
buildJob({
payload: {
deliveryId: "delivery_1",
userId: "user_haris",
sourceKey: "platform-lead:lead_1:email",
channel: "email",
messageKey: "platform.leads.captured",
},
}),
{ enqueue }
)
).rejects.toMatchObject({ code: "INVALID_PAYLOAD" });
expect(enqueue).not.toHaveBeenCalled();
});
it("hands the durable outbox request to the existing retryable notification worker", async () => {
let queued: { descriptor: NotificationJobDescriptor; options: QueueEnqueueOptions } | undefined;
const mailProvider: MailProvider = {
id: "mailjet",
send: vi.fn(async () => ({ provider: "mailjet" as const, status: "queued" as const, messageId: "mailjet_1" })),
};
const markPlatformNotificationDeliveryStatus = vi.fn(async () => ({ count: 1 }));
await runPlatformNotificationOutboxJob(buildJob(), {
enqueue: async (input, options) => {
queued = { descriptor: buildPlatformNotificationJob(input), options };
},
});
expect(queued).toBeDefined();
expect(buildRetryJobOptions(queued!.descriptor)).toMatchObject({ attempts: 3, backoff: { type: "exponential", delay: 1_000 } });
expect(queued!.options).toEqual({ tenantId: null, idempotencyKey: "platform-notification-outbox:outbox_1" });
const registry = buildHandlerRegistry({
mailProvider,
createPlatformNotificationDelivery: vi.fn(async () => ({ id: "delivery_1", status: "PENDING" })),
markPlatformNotificationDeliveryStatus,
resolvePlatformLeadNotificationRecipient: vi.fn(async () => ({ email: "operator@example.test" })),
});
await expect(registry[queued!.descriptor.queueName](queued!.descriptor.payload, {}, { attemptsMade: 0, attemptsLimit: 3 })).resolves.toMatchObject({
action: "notification.platform.email.sent",
details: { deliveryId: "delivery_1" },
});
expect(markPlatformNotificationDeliveryStatus).toHaveBeenCalledWith(
expect.objectContaining({ id: "delivery_1", userId: "user_haris", status: "SENT", attemptsMade: 1 })
);
expect(JSON.stringify(markPlatformNotificationDeliveryStatus.mock.calls)).not.toContain("operator@example.test");
});
});