Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/admin-email-events.server.test.ts
T

224 lines
7.1 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
recordAdminEmailEvent,
redactExpiredAdminEmailEventRawData,
} from "./admin-email-events.server.js";
const occurredAt = new Date("2026-07-24T10:00:00.000Z");
function transaction(overrides: {
trackingEnabled?: boolean;
liveOpenEnabled?: boolean;
existingEvent?: { id: string } | null;
link?: { id: string } | null;
createdEvents?: readonly { id: string }[];
} = {}) {
const link =
overrides.link === undefined ? { id: "link-1" } : overrides.link;
return {
adminScheduledEmail: {
findFirst: vi.fn(async () => ({ sentMessageId: "message-1" })),
},
adminEmailMessage: {
findFirst: vi.fn(async () => ({
id: "message-1",
subject: "Demo",
matchedContactId: "contact-1",
matchedLeadId: null,
matchedDealId: "deal-1",
})),
},
adminEmailOutboundPolicy: {
findUnique: vi.fn(async () => ({
trackingEnabled: overrides.trackingEnabled ?? true,
liveOpenEnabled: overrides.liveOpenEnabled ?? true,
})),
},
adminEmailLink: {
findFirst: vi.fn(async (): Promise<{ id: string } | null> => link),
},
adminEmailEvent: {
findUnique: vi.fn(async () => overrides.existingEvent ?? null),
findUniqueOrThrow: vi.fn(async () => ({ id: "event-raced" })),
createManyAndReturn: vi.fn(
async () => overrides.createdEvents ?? [{ id: "event-1" }]
),
},
adminActivity: { create: vi.fn(async () => ({})) },
notificationDelivery: {
findFirst: vi.fn(async () => null),
create: vi.fn(async () => ({ id: "notification-1" })),
},
outboxEvent: {
create: vi.fn(async () => ({ id: "outbox-1" })),
findUnique: vi.fn(async () => null),
},
auditEvent: {
findFirst: vi.fn(async () => null),
create: vi.fn(async () => ({ id: "audit-1" })),
},
auditChainHead: {
findUnique: vi.fn(async () => null),
upsert: vi.fn(async () => ({})),
},
};
}
describe("admin email event persistence", () => {
it("records a deduplicated opted-in open with activity, audit, and live notification", async () => {
const tx = transaction();
const client = { $transaction: vi.fn(async (callback) => callback(tx)) };
await expect(
recordAdminEmailEvent(client as never, {
adminUserId: "admin-1",
scheduledEmailId: "scheduled-1",
type: "opened",
eventKey: "open-token-hash",
occurredAt,
})
).resolves.toEqual({
status: "recorded",
eventId: "event-1",
messageId: "message-1",
});
expect(tx.adminEmailEvent.createManyAndReturn).toHaveBeenCalledWith({
data: expect.objectContaining({
adminUserId: "admin-1",
messageId: "message-1",
type: "opened",
providerEventId: "open-token-hash",
rawExpiresAt: new Date("2027-01-20T10:00:00.000Z"),
}),
skipDuplicates: true,
select: { id: true },
});
expect(tx.adminActivity.create).toHaveBeenCalledOnce();
expect(tx.notificationDelivery.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: null,
userId: null,
adminUserId: "admin-1",
messageKey: "admin.sales.email.notifications.opened",
}),
});
expect(tx.outboxEvent.create).toHaveBeenCalledWith({
data: expect.objectContaining({
eventType: "notification.platform.requested.v1",
dispatchKey: "platform-notification:notification-1",
payload: expect.objectContaining({
adminUserId: "admin-1",
metadata: {
emailMessageId: "message-1",
emailEventId: "event-1",
deeplink: "/sales/email",
},
}),
}),
});
});
it("does not record engagement when tracking is disabled", async () => {
const tx = transaction({ trackingEnabled: false });
const client = { $transaction: vi.fn(async (callback) => callback(tx)) };
await expect(
recordAdminEmailEvent(client as never, {
adminUserId: "admin-1",
scheduledEmailId: "scheduled-1",
type: "opened",
eventKey: "open-token-hash",
occurredAt,
})
).resolves.toEqual({ status: "ignored", reason: "tracking_disabled" });
expect(tx.adminEmailEvent.createManyAndReturn).not.toHaveBeenCalled();
});
it("returns the winner when a concurrent insert claims the provider key", async () => {
const tx = transaction({ createdEvents: [] });
const client = { $transaction: vi.fn(async (callback) => callback(tx)) };
await expect(
recordAdminEmailEvent(client as never, {
adminUserId: "admin-1",
scheduledEmailId: "scheduled-1",
type: "delivered",
eventKey: "provider-event-race",
occurredAt,
})
).resolves.toEqual({
status: "duplicate",
eventId: "event-raced",
messageId: "message-1",
});
expect(tx.adminActivity.create).not.toHaveBeenCalled();
});
it("returns the stable event for provider replays", async () => {
const tx = transaction({ existingEvent: { id: "event-existing" } });
const client = { $transaction: vi.fn(async (callback) => callback(tx)) };
await expect(
recordAdminEmailEvent(client as never, {
adminUserId: "admin-1",
scheduledEmailId: "scheduled-1",
type: "delivered",
eventKey: "provider-event-1",
occurredAt,
recipient: "Buyer@Example.com",
})
).resolves.toEqual({
status: "duplicate",
eventId: "event-existing",
messageId: "message-1",
});
});
it("rejects click events without the persisted signed link", async () => {
const tx = transaction({ link: null });
const client = { $transaction: vi.fn(async (callback) => callback(tx)) };
await expect(
recordAdminEmailEvent(client as never, {
adminUserId: "admin-1",
scheduledEmailId: "scheduled-1",
type: "clicked",
eventKey: "click-token-hash",
trackingTokenHash: "click-token-hash",
occurredAt,
})
).resolves.toEqual({ status: "ignored", reason: "link_not_found" });
});
it("redacts expired raw metadata without deleting event facts", async () => {
const client = {
adminEmailEvent: {
findMany: vi.fn(async () => [{ id: "event-1" }, { id: "event-2" }]),
updateMany: vi.fn(async () => ({ count: 2 })),
},
adminEmailLink: {
deleteMany: vi.fn(async () => ({ count: 1 })),
},
};
await expect(
redactExpiredAdminEmailEventRawData(client as never, { now: occurredAt })
).resolves.toEqual({ inspected: 2, redacted: 2, deletedLinks: 1 });
expect(client.adminEmailEvent.updateMany).toHaveBeenCalledWith({
where: {
id: { in: ["event-1", "event-2"] },
rawExpiresAt: { lte: occurredAt },
},
data: {
metadata: expect.anything(),
recipient: null,
linkId: null,
rawExpiresAt: null,
},
});
expect(client.adminEmailLink.deleteMany).toHaveBeenCalledWith({
where: {
createdAt: { lte: new Date("2026-01-25T10:00:00.000Z") },
events: { none: {} },
},
});
});
});