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

351 lines
10 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
claimDueAdminEmails,
completeAdminEmailDelivery,
fireDueAdminNoReplyReminders,
isInsideAdminEmailWorkWindow,
} from "./admin-email-delivery.server.js";
const now = new Date("2026-07-24T10:00:00.000Z");
function candidate(id: string) {
return {
id,
createdAt: now,
updatedAt: now,
adminUserId: "admin-1",
mailboxId: "mailbox-1",
contactId: "contact-1",
leadId: null,
dealId: "deal-1",
threadId: null,
bulkRunId: null,
toAddresses: ["buyer@example.com"],
ccAddresses: [],
bccAddresses: [],
subject: "Demo",
bodyHtml: "<p>Hallo</p>",
bodyText: "Hallo",
scheduledFor: now,
timeZone: "Europe/Berlin",
noReplyAfterDays: null,
status: "queued",
idempotencyKey: id,
claimedAt: null,
sentAt: null,
sendAttemptCount: 0,
providerMessageId: null,
sentMessageId: null,
lastErrorMessageKey: null,
mailbox: {
emailAddress: "sales@hivegrid.de",
displayName: "Sales",
status: "active",
archivedAt: null,
connection: {
id: "connection-1",
provider: "google_mail",
status: "active",
archivedAt: null,
},
},
thread: null,
};
}
function policy() {
return {
id: "policy-1",
createdAt: now,
updatedAt: now,
adminUserId: "admin-1",
timeZone: "Europe/Berlin",
workdayStartMinutes: 9 * 60,
workdayEndMinutes: 18 * 60,
allowedWeekDays: [1, 2, 3, 4, 5],
dailySendLimit: 1,
bulkDailySendLimit: 1,
consentRulesConfigured: true,
trackingEnabled: false,
liveOpenEnabled: false,
trackingRetentionDays: 180,
configuredAt: now,
};
}
describe("admin email delivery persistence", () => {
it("claims due messages atomically and defers the batch at the daily budget", async () => {
const updateMany = vi
.fn()
.mockResolvedValueOnce({ count: 0 })
.mockResolvedValueOnce({ count: 1 })
.mockResolvedValueOnce({ count: 1 });
const tx = {
adminScheduledEmail: {
updateMany,
findMany: vi
.fn()
.mockResolvedValueOnce([candidate("scheduled-1"), candidate("scheduled-2")])
.mockResolvedValueOnce([]),
},
adminEmailOutboundPolicy: {
findUnique: vi.fn(async () => policy()),
},
};
const client = {
$transaction: vi.fn(async (callback) => callback(tx)),
};
const result = await claimDueAdminEmails(client as never, {
now,
take: 10,
});
expect(result).toMatchObject({
inspected: 2,
blocked: 0,
deferred: 1,
recoveredUnknown: 0,
});
expect(result.claimed.map((item) => item.id)).toEqual(["scheduled-1"]);
expect(updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "scheduled-1", status: "queued" },
data: expect.objectContaining({
status: "sending",
sendAttemptCount: { increment: 1 },
}),
})
);
expect(updateMany).toHaveBeenCalledWith({
where: { id: "scheduled-2", status: "queued" },
data: {
lastErrorMessageKey:
"admin.sales.email.delivery.errors.dailySendLimitReached",
},
});
});
it("uses the configured IANA zone for workday and work-hour gates", () => {
const configured = policy();
expect(isInsideAdminEmailWorkWindow(configured, now)).toBe(true);
expect(
isInsideAdminEmailWorkWindow(
configured,
new Date("2026-07-25T10:00:00.000Z")
)
).toBe(false);
});
it("persists the provider result as one thread message, event, activity, and audit", async () => {
const tx = {
adminScheduledEmail: {
findFirst: vi.fn(async () => ({ id: "scheduled-1" })),
update: vi.fn(async () => ({})),
},
adminEmailThread: {
findFirst: vi.fn(async () => null),
create: vi.fn(async () => ({ id: "thread-1" })),
update: vi.fn(async () => ({})),
},
adminEmailMessage: {
create: vi.fn(async () => ({ id: "message-1" })),
},
adminNoReplyReminder: {
upsert: vi.fn(async () => ({ id: "reminder-1" })),
},
adminBulkEmailRun: {
update: vi
.fn()
.mockResolvedValueOnce({
recipientCount: 1,
sentCount: 1,
failedCount: 0,
})
.mockResolvedValueOnce({}),
},
adminActivity: {
create: vi.fn(async () => ({})),
},
auditEvent: {
findFirst: vi.fn(async () => null),
create: vi.fn(async () => ({ id: "audit-1" })),
},
auditChainHead: {
findUnique: vi.fn(async () => null),
upsert: vi.fn(async () => ({})),
},
};
const client = {
$transaction: vi.fn(async (callback) => callback(tx)),
};
const email = {
...candidate("scheduled-1"),
connectionId: "connection-1",
provider: "google_mail" as const,
fromAddress: "sales@hivegrid.de",
fromName: "Sales",
providerThreadId: null,
bulkRunId: "bulk-1",
noReplyAfterDays: 3,
trackingEnabled: false,
liveOpenEnabled: false,
trackingRetentionDays: 180,
};
const result = await completeAdminEmailDelivery(client as never, {
email,
providerMessageId: "gmail-message-1",
providerThreadId: "gmail-thread-1",
sentAt: now,
deliveredBodyHtml: "<p>Tracked</p>",
trackingLinks: [
{
destinationUrl: "https://example.com/demo",
trackingTokenHash: "a".repeat(64),
},
],
});
expect(result).toEqual({ messageId: "message-1" });
expect(tx.adminEmailMessage.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
providerMessageId: "gmail-message-1",
direction: "outbound",
matchedContactId: "contact-1",
matchedDealId: "deal-1",
bodyHtml: "<p>Tracked</p>",
links: {
create: [
{
adminUserId: "admin-1",
destinationUrl: "https://example.com/demo",
trackingTokenHash: "a".repeat(64),
},
],
},
}),
})
);
expect(tx.adminScheduledEmail.update).toHaveBeenCalledWith({
where: { id: "scheduled-1" },
data: expect.objectContaining({
status: "sent",
sentMessageId: "message-1",
}),
});
expect(tx.adminActivity.create).toHaveBeenCalledOnce();
expect(tx.adminNoReplyReminder.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({
outboundMessageId: "message-1",
dueAt: new Date("2026-07-27T10:00:00.000Z"),
}),
})
);
expect(tx.adminBulkEmailRun.update).toHaveBeenLastCalledWith({
where: { id: "bulk-1" },
data: { status: "complete", lastErrorMessageKey: null },
});
});
});
describe("admin email no-reply reminders", () => {
it("creates one contextual task with an immediate reminder atomically", async () => {
const tx = {
adminNoReplyReminder: {
findFirst: vi.fn().mockResolvedValue({
id: "reminder-1",
adminUserId: "admin-1",
outboundMessageId: "message-1",
outboundMessage: {
matchedContactId: "contact-1",
matchedLeadId: null,
matchedDealId: "deal-1",
subject: "Demo",
},
}),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
update: vi.fn().mockResolvedValue({ id: "reminder-1" }),
},
adminEmailOutboundPolicy: {
findUnique: vi.fn().mockResolvedValue({ timeZone: "Europe/Berlin" }),
},
adminActivity: {
create: vi.fn().mockResolvedValue({ id: "activity-1" }),
update: vi.fn().mockResolvedValue({ id: "activity-1" }),
},
adminTask: {
create: vi.fn().mockResolvedValue({ id: "task-1" }),
},
auditEvent: {
findFirst: vi.fn().mockResolvedValue(null),
create: vi.fn().mockResolvedValue({ id: "audit-1" }),
},
};
const client = {
adminNoReplyReminder: {
findMany: vi.fn().mockResolvedValue([{ id: "reminder-1" }]),
},
$transaction: vi.fn(async (callback) => callback(tx)),
};
await expect(
fireDueAdminNoReplyReminders(client as never, { now, take: 25 })
).resolves.toEqual({ scanned: 1, created: 1 });
expect(tx.adminNoReplyReminder.updateMany).toHaveBeenCalledWith({
where: { id: "reminder-1", status: "pending" },
data: { status: "fired" },
});
expect(tx.adminTask.create).toHaveBeenCalledWith({
data: expect.objectContaining({
title: "E-Mail nachfassen: Demo",
contactId: "contact-1",
dealId: "deal-1",
assignedToAdminUserId: "admin-1",
timeZone: "Europe/Berlin",
reminderAt: now,
source: "email",
sourceActivityId: "activity-1",
}),
select: { id: true },
});
expect(tx.adminNoReplyReminder.update).toHaveBeenCalledWith({
where: { id: "reminder-1" },
data: { taskId: "task-1" },
});
});
it("does not create a duplicate task when another worker wins the claim", async () => {
const tx = {
adminNoReplyReminder: {
findFirst: vi.fn().mockResolvedValue({
id: "reminder-1",
adminUserId: "admin-1",
outboundMessageId: "message-1",
outboundMessage: {
matchedContactId: "contact-1",
matchedLeadId: null,
matchedDealId: null,
subject: null,
},
}),
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
},
adminTask: { create: vi.fn() },
};
const client = {
adminNoReplyReminder: {
findMany: vi.fn().mockResolvedValue([{ id: "reminder-1" }]),
},
$transaction: vi.fn(async (callback) => callback(tx)),
};
await expect(
fireDueAdminNoReplyReminders(client as never, { now })
).resolves.toEqual({ scanned: 1, created: 0 });
expect(tx.adminTask.create).not.toHaveBeenCalled();
});
});