Skip to content

Email for professionals and teams

update seed data

Hieu Nguyen (Jack)add11e1316ca
diff --git a/src/lib/domains/cloudflare-cleanup.ts b/src/lib/domains/cloudflare-cleanup.ts
new file mode 100644
index 0000000..130238b
--- /dev/null
+++ b/src/lib/domains/cloudflare-cleanup.ts
@@ -0,0 +1,37 @@
+import {
+ deleteEmailRoutingRule,
+ listEmailRoutingRules,
+} from "@/lib/cloudflare-api";
+
+function routesToDomain(ruleValue: string | undefined, hostname: string): boolean {
+ if (!ruleValue) return false;
+
+ const normalized = ruleValue.toLowerCase();
+ return normalized === hostname || normalized.endsWith(`@${hostname}`);
+}
+
+export async function deleteEmailRoutingRulesForDomain(
+ env: CloudflareEnv,
+ zoneId: string,
+ hostname: string,
+): Promise<void> {
+ const normalizedHostname = hostname.toLowerCase();
+ const rules = await listEmailRoutingRules(env, zoneId);
+ const linkedRules = rules.filter((rule) =>
+ rule.matchers?.some(
+ (matcher) =>
+ matcher.type === "literal" &&
+ matcher.field === "to" &&
+ routesToDomain(matcher.value, normalizedHostname),
+ ),
+ );
+
+ await Promise.all(
+ linkedRules.map(async (rule) => {
+ const ruleId = rule.id ?? rule.tag;
+ if (!ruleId) return;
+
+ await deleteEmailRoutingRule(env, zoneId, ruleId);
+ }),
+ );
+}
diff --git a/src/lib/domains/service.ts b/src/lib/domains/service.ts
index 292b247..f35634d 100644
--- a/src/lib/domains/service.ts
+++ b/src/lib/domains/service.ts
@@ -10,6 +10,7 @@ import {
deleteSendingSubdomain,
type CfDnsRecord,
} from "@/lib/cloudflare-api";
+import { deleteEmailRoutingRulesForDomain } from "@/lib/domains/cloudflare-cleanup";
import { provisionDomainOnCloudflare } from "@/lib/domains/provision";
export type DomainDnsView = {
@@ -93,6 +94,12 @@ export async function removeDomainForUser(
.limit(1);
if (!domain) throw new Error("Domain not found");
+ try {
+ await deleteEmailRoutingRulesForDomain(env, domain.zoneId, domain.hostname);
+ } catch (err) {
+ console.warn("deleteEmailRoutingRulesForDomain", err);
+ }
+
if (domain.routingEnabled) {
try {
await disableEmailRouting(env, domain.zoneId);
diff --git a/src/lib/seed-types.d.ts b/src/lib/seed-types.d.ts
new file mode 100644
index 0000000..c4a521d
--- /dev/null
+++ b/src/lib/seed-types.d.ts
@@ -0,0 +1,27 @@
+import type { mailboxes } from "@/db/schema";
+
+export type SeedMailboxKey = "support" | "billing";
+
+export type SeedMailboxMap = Record<SeedMailboxKey, typeof mailboxes.$inferSelect>;
+
+export type SeedMessageStatus =
+ | "received"
+ | "sent"
+ | "draft"
+ | "trash"
+ | "spam"
+ | "queued"
+ | "failed";
+
+export type SeedMessageDefinition = {
+ mailbox: SeedMailboxKey;
+ direction: "inbound" | "outbound";
+ status: SeedMessageStatus;
+ fromAddr: string;
+ toAddr: string;
+ subject: string;
+ textBody: string;
+ read?: boolean;
+ minutesAgo: number;
+ providerMessageId?: string;
+};
diff --git a/src/lib/seed-utils.ts b/src/lib/seed-utils.ts
new file mode 100644
index 0000000..51514ee
--- /dev/null
+++ b/src/lib/seed-utils.ts
@@ -0,0 +1,372 @@
+import { and, eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import {
+ domains,
+ mailboxes,
+ messageBodies,
+ messages,
+ outboundJobs,
+ users,
+} from "@/db/schema";
+import { hashPassword } from "@/lib/auth/password";
+import { buildSnippet } from "@/lib/email/parse";
+import { newId } from "@/lib/ids";
+import type {
+ SeedMailboxKey,
+ SeedMailboxMap,
+ SeedMessageDefinition,
+} from "@/lib/seed-types";
+
+export const demoCredentials = {
+ email: "[email protected]",
+ password: "demo-password-change-me",
+};
+
+const demoDomain = "example.com";
+
+const seedMailboxDefinitions: {
+ key: SeedMailboxKey;
+ localPart: string;
+ displayName: string;
+}[] = [
+ { key: "support", localPart: "support", displayName: "Support" },
+ { key: "billing", localPart: "billing", displayName: "Billing" },
+];
+
+const seedMessages: SeedMessageDefinition[] = [
+ {
+ mailbox: "support",
+ direction: "inbound",
+ status: "received",
+ fromAddr: "[email protected]",
+ toAddr: `support@${demoDomain}`,
+ subject: "Cannot access workspace",
+ textBody:
+ "I reset my password this morning, but the login page still loops back to the sign-in screen. Can you check whether the account is locked?",
+ read: false,
+ minutesAgo: 12,
+ providerMessageId: "<[email protected]>",
+ },
+ {
+ mailbox: "support",
+ direction: "inbound",
+ status: "received",
+ fromAddr: "[email protected]",
+ toAddr: `support@${demoDomain}`,
+ subject: "Webhook retry question",
+ textBody:
+ "We noticed three delivery attempts for the same event. Is there a way to confirm whether retries stop after a 2xx response?",
+ read: true,
+ minutesAgo: 47,
+ providerMessageId: "<[email protected]>",
+ },
+ {
+ mailbox: "billing",
+ direction: "inbound",
+ status: "received",
+ fromAddr: "[email protected]",
+ toAddr: `billing@${demoDomain}`,
+ subject: "Invoice address update",
+ textBody:
+ "Please update our invoice contact to [email protected] before the next billing cycle closes.",
+ read: false,
+ minutesAgo: 94,
+ providerMessageId: "<[email protected]>",
+ },
+ {
+ mailbox: "support",
+ direction: "outbound",
+ status: "sent",
+ fromAddr: `support@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Re: Cannot access workspace",
+ textBody:
+ "I cleared the stale session and sent a fresh password reset link. Please try again from an incognito window.",
+ read: true,
+ minutesAgo: 8,
+ providerMessageId: "<[email protected]>",
+ },
+ {
+ mailbox: "billing",
+ direction: "outbound",
+ status: "sent",
+ fromAddr: `billing@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Re: Invoice address update",
+ textBody:
+ "The billing contact is updated. Future invoices will go to [email protected].",
+ read: true,
+ minutesAgo: 35,
+ providerMessageId: "<[email protected]>",
+ },
+ {
+ mailbox: "support",
+ direction: "outbound",
+ status: "draft",
+ fromAddr: `support@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Re: Webhook retry question",
+ textBody:
+ "Draft note: include retry backoff details, delivery log location, and the recommendation to return HTTP 204 after processing.",
+ read: true,
+ minutesAgo: 22,
+ },
+ {
+ mailbox: "billing",
+ direction: "outbound",
+ status: "draft",
+ fromAddr: `billing@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Annual plan renewal",
+ textBody:
+ "Draft renewal response with seat count, purchase order reference, and requested renewal date.",
+ read: true,
+ minutesAgo: 128,
+ },
+ {
+ mailbox: "support",
+ direction: "inbound",
+ status: "spam",
+ fromAddr: "[email protected]",
+ toAddr: `support@${demoDomain}`,
+ subject: "Urgent traffic boost offer",
+ textBody:
+ "We can send thousands of visitors to your dashboard today. Reply now for the limited campaign rate.",
+ read: false,
+ minutesAgo: 166,
+ providerMessageId: "<[email protected]>",
+ },
+ {
+ mailbox: "billing",
+ direction: "inbound",
+ status: "spam",
+ fromAddr: "[email protected]",
+ toAddr: `billing@${demoDomain}`,
+ subject: "Payment account verification required",
+ textBody:
+ "Your payout account requires verification. Open the attached link and confirm your banking credentials.",
+ read: true,
+ minutesAgo: 219,
+ providerMessageId: "<[email protected]>",
+ },
+ {
+ mailbox: "support",
+ direction: "inbound",
+ status: "trash",
+ fromAddr: "[email protected]",
+ toAddr: `support@${demoDomain}`,
+ subject: "Legacy migration thread",
+ textBody:
+ "This message was moved to trash after the migration checklist was completed and archived.",
+ read: true,
+ minutesAgo: 266,
+ providerMessageId: "<[email protected]>",
+ },
+ {
+ mailbox: "billing",
+ direction: "outbound",
+ status: "trash",
+ fromAddr: `billing@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Old billing draft",
+ textBody:
+ "Discarded copy of an earlier billing reply that was replaced by the final invoice response.",
+ read: true,
+ minutesAgo: 314,
+ },
+ {
+ mailbox: "support",
+ direction: "outbound",
+ status: "queued",
+ fromAddr: `support@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Queued delivery status",
+ textBody:
+ "This seeded message represents an outbound email waiting for the worker queue to process.",
+ read: true,
+ minutesAgo: 4,
+ },
+ {
+ mailbox: "billing",
+ direction: "outbound",
+ status: "queued",
+ fromAddr: `billing@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Queued payment receipt",
+ textBody:
+ "This seeded receipt is queued so API and background-job views can exercise pending delivery states.",
+ read: true,
+ minutesAgo: 17,
+ },
+ {
+ mailbox: "support",
+ direction: "outbound",
+ status: "failed",
+ fromAddr: `support@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Failed SMTP handoff",
+ textBody:
+ "This seeded message failed delivery after the provider rejected the recipient address.",
+ read: true,
+ minutesAgo: 73,
+ },
+ {
+ mailbox: "billing",
+ direction: "outbound",
+ status: "failed",
+ fromAddr: `billing@${demoDomain}`,
+ toAddr: "[email protected]",
+ subject: "Failed billing notice",
+ textBody:
+ "This seeded billing notice failed because the destination mailbox no longer exists.",
+ read: true,
+ minutesAgo: 181,
+ },
+];
+
+export async function ensureDemoUser(env: CloudflareEnv) {
+ const db = getDb(env);
+ const [existing] = await db
+ .select()
+ .from(users)
+ .where(eq(users.email, demoCredentials.email))
+ .limit(1);
+ if (existing) return existing;
+
+ const id = newId("usr");
+ await db.insert(users).values({
+ id,
+ email: demoCredentials.email,
+ passwordHash: hashPassword(demoCredentials.password),
+ name: "Demo User",
+ });
+
+ const [created] = await db.select().from(users).where(eq(users.id, id)).limit(1);
+ return created!;
+}
+
+export async function ensureDemoDomain(env: CloudflareEnv, userId: string) {
+ const db = getDb(env);
+ const [existing] = await db
+ .select()
+ .from(domains)
+ .where(eq(domains.hostname, demoDomain))
+ .limit(1);
+ if (existing) return existing;
+
+ const id = newId("dom");
+ await db.insert(domains).values({
+ id,
+ userId,
+ hostname: demoDomain,
+ zoneId: "00000000000000000000000000000000",
+ status: "active",
+ routingEnabled: true,
+ sendingEnabled: true,
+ });
+
+ const [created] = await db.select().from(domains).where(eq(domains.id, id)).limit(1);
+ return created!;
+}
+
+export async function ensureDemoMailboxes(
+ env: CloudflareEnv,
+ userId: string,
+ domainId: string,
+): Promise<SeedMailboxMap> {
+ const db = getDb(env);
+ const entries = await Promise.all(
+ seedMailboxDefinitions.map(async (definition) => {
+ const [existing] = await db
+ .select()
+ .from(mailboxes)
+ .where(
+ and(
+ eq(mailboxes.domainId, domainId),
+ eq(mailboxes.localPart, definition.localPart),
+ ),
+ )
+ .limit(1);
+ if (existing) return [definition.key, existing] as const;
+
+ const id = newId("mbx");
+ await db.insert(mailboxes).values({
+ id,
+ userId,
+ domainId,
+ localPart: definition.localPart,
+ displayName: definition.displayName,
+ });
+
+ const [created] = await db
+ .select()
+ .from(mailboxes)
+ .where(eq(mailboxes.id, id))
+ .limit(1);
+ return [definition.key, created!] as const;
+ }),
+ );
+
+ return Object.fromEntries(entries) as SeedMailboxMap;
+}
+
+export async function insertDemoMessages(
+ env: CloudflareEnv,
+ userId: string,
+ mailboxMap: SeedMailboxMap,
+): Promise<number> {
+ const db = getDb(env);
+ const now = Date.now();
+
+ for (const seedMessage of seedMessages) {
+ const id = newId("msg");
+ const createdAt = new Date(now - seedMessage.minutesAgo * 60 * 1000);
+ const mailbox = mailboxMap[seedMessage.mailbox];
+
+ await db.insert(messages).values({
+ id,
+ userId,
+ mailboxId: mailbox.id,
+ direction: seedMessage.direction,
+ providerMessageId: seedMessage.providerMessageId ?? null,
+ fromAddr: seedMessage.fromAddr,
+ toAddr: seedMessage.toAddr,
+ subject: seedMessage.subject,
+ snippet: buildSnippet(seedMessage.textBody, null),
+ status: seedMessage.status,
+ read: seedMessage.read ?? true,
+ threadId: seedMessage.providerMessageId ?? null,
+ createdAt,
+ });
+
+ await db.insert(messageBodies).values({
+ id: newId(),
+ messageId: id,
+ textBody: seedMessage.textBody,
+ htmlBody: null,
+ });
+
+ if (seedMessage.status === "queued" || seedMessage.status === "failed") {
+ await db.insert(outboundJobs).values({
+ id: newId("job"),
+ userId,
+ messageId: id,
+ status: seedMessage.status,
+ payload: JSON.stringify({
+ from: seedMessage.fromAddr,
+ to: seedMessage.toAddr,
+ subject: seedMessage.subject,
+ text: seedMessage.textBody,
+ }),
+ error:
+ seedMessage.status === "failed"
+ ? "Seeded delivery failure for UI and API testing"
+ : null,
+ createdAt,
+ updatedAt: createdAt,
+ });
+ }
+ }
+
+ return seedMessages.length;
+}
diff --git a/src/lib/seed.ts b/src/lib/seed.ts
index 3bccf08..82f5041 100644
--- a/src/lib/seed.ts
+++ b/src/lib/seed.ts
@@ -1,39 +1,19 @@
-import { getDb } from "@/db";
-import { domains, mailboxes, users } from "@/db/schema";
-import { hashPassword } from "@/lib/auth/password";
-import { newId } from "@/lib/ids";
+import {
+ demoCredentials,
+ ensureDemoDomain,
+ ensureDemoMailboxes,
+ ensureDemoUser,
+ insertDemoMessages,
+} from "@/lib/seed-utils";
/** Dev-only seed without Cloudflare API (domain must be onboarded separately). */
-export async function seedDemoData(env: CloudflareEnv): Promise<void> {
- const db = getDb(env);
- const userId = newId("usr");
- const domainId = newId("dom");
- const mailboxId = newId("mbx");
+export async function seedDemoData(env: CloudflareEnv): Promise<{ messageCount: number }> {
+ const user = await ensureDemoUser(env);
+ const domain = await ensureDemoDomain(env, user.id);
+ const mailboxMap = await ensureDemoMailboxes(env, user.id, domain.id);
+ const messageCount = await insertDemoMessages(env, user.id, mailboxMap);
- await db.insert(users).values({
- id: userId,
- email: "[email protected]",
- passwordHash: hashPassword("demo-password-change-me"),
- name: "Demo User",
- });
+ console.info("Seeded demo user:", demoCredentials);
- await db.insert(domains).values({
- id: domainId,
- userId,
- hostname: "example.com",
- zoneId: "00000000000000000000000000000000",
- status: "active",
- routingEnabled: true,
- sendingEnabled: true,
- });
-
- await db.insert(mailboxes).values({
- id: mailboxId,
- userId,
- domainId,
- localPart: "support",
- displayName: "Support",
- });
-
- console.info("Seeded demo user:", { email: "[email protected]", password: "demo-password-change-me" });
+ return { messageCount };
}