Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat(email): redesign every email in the Ledger style (#1330)

Goldflag47d6a8ed1255
diff --git a/client/public/rybbit/email-logo.png b/client/public/rybbit/email-logo.png
new file mode 100644
index 000000000..df4b5a64a
Binary files /dev/null and b/client/public/rybbit/email-logo.png differ
diff --git a/server/src/api/__snapshots__/routes.test.ts.snap b/server/src/api/__snapshots__/routes.test.ts.snap
index fc4df9be3..cb999a93c 100644
--- a/server/src/api/__snapshots__/routes.test.ts.snap
+++ b/server/src/api/__snapshots__/routes.test.ts.snap
@@ -131,6 +131,7 @@ exports[`API route table > pins the access each route requires 1`] = `
"GET /api/stripe/subscription β†’ authenticated",
"GET /api/user/organizations β†’ authenticated",
"GET /api/user/unsubscribe-marketing-oneclick β†’ public",
+ "GET /api/user/unsubscribe-reports-oneclick β†’ public",
"GET /api/version β†’ public",
"PATCH /api/admin/organizations/:organizationId/members/:memberId β†’ system-admin",
"POST /api/admin/telemetry β†’ public",
@@ -180,6 +181,7 @@ exports[`API route table > pins the access each route requires 1`] = `
"POST /api/user/api-keys β†’ authenticated",
"POST /api/user/unsubscribe-marketing β†’ authenticated",
"POST /api/user/unsubscribe-marketing-oneclick β†’ public",
+ "POST /api/user/unsubscribe-reports-oneclick β†’ public",
"PUT /api/admin/organizations/:organizationId/subscription-override β†’ system-admin",
"PUT /api/admin/sites/:siteId/move β†’ system-admin",
"PUT /api/organizations/:organizationId/members/:memberId/sites β†’ org members:manage [admin+]",
diff --git a/server/src/api/routes.test.ts b/server/src/api/routes.test.ts
index 7b62a64c1..3d036f69e 100644
--- a/server/src/api/routes.test.ts
+++ b/server/src/api/routes.test.ts
@@ -71,3 +71,25 @@ describe("API route table", () => {
expect(table).toMatchSnapshot();
});
});
+
+describe("one-click unsubscribe routes", () => {
+ // RFC 8058: mail clients POST "List-Unsubscribe=One-Click" as a form body.
+ // Without a form parser Fastify answers 415 and the handler never runs.
+ it.each(["/api/user/unsubscribe-marketing-oneclick", "/api/user/unsubscribe-reports-oneclick"])(
+ "accept a form-encoded List-Unsubscribe-Post at %s",
+ async url => {
+ const app = Fastify();
+ await app.register(apiRoutes, { prefix: "/api" });
+ const response = await app.inject({
+ method: "POST",
+ url,
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ payload: "List-Unsubscribe=One-Click",
+ });
+ await app.close();
+
+ // No signed query, so the handler itself rejects the request.
+ expect(response.statusCode).toBe(400);
+ }
+ );
+});
diff --git a/server/src/api/routes.ts b/server/src/api/routes.ts
index a05edea8e..f97dc9cda 100644
--- a/server/src/api/routes.ts
+++ b/server/src/api/routes.ts
@@ -184,6 +184,7 @@ import {
getUserOrganizations,
listOrganizationMembers,
oneClickUnsubscribeMarketing,
+ oneClickUnsubscribeReports,
unsubscribeMarketing,
updateAccountSettings,
} from "./user/index.js";
@@ -553,8 +554,19 @@ async function userRoutes(fastify: FastifyInstance) {
fastify.get("/user/organizations", authenticated({ resource: "org", action: "read" }), getUserOrganizations);
fastify.post("/user/account-settings", authenticated("deny-scoped"), updateAccountSettings);
fastify.post("/user/unsubscribe-marketing", authenticated("deny-scoped"), unsubscribeMarketing);
- fastify.get("/user/unsubscribe-marketing-oneclick", publicRoute, oneClickUnsubscribeMarketing); // Public - for link clicks
- fastify.post("/user/unsubscribe-marketing-oneclick", publicRoute, oneClickUnsubscribeMarketing); // Public - for List-Unsubscribe header
+ await fastify.register(async oneClick => {
+ // Email clients send RFC 8058 one-click unsubscribes as an
+ // application/x-www-form-urlencoded POST ("List-Unsubscribe=One-Click").
+ // The handlers only read the query string, but without a parser Fastify
+ // answers 415 before they run.
+ oneClick.addContentTypeParser("application/x-www-form-urlencoded", { parseAs: "string" }, (_request, _body, done) =>
+ done(null, {})
+ );
+ oneClick.get("/user/unsubscribe-marketing-oneclick", publicRoute, oneClickUnsubscribeMarketing); // Public - for link clicks
+ oneClick.post("/user/unsubscribe-marketing-oneclick", publicRoute, oneClickUnsubscribeMarketing); // Public - for List-Unsubscribe header
+ oneClick.get("/user/unsubscribe-reports-oneclick", publicRoute, oneClickUnsubscribeReports); // Public - weekly report footer link
+ oneClick.post("/user/unsubscribe-reports-oneclick", publicRoute, oneClickUnsubscribeReports); // Public - weekly report List-Unsubscribe header
+ });
fastify.post("/user/api-keys", authenticated("deny-scoped"), createUserApiKey);
fastify.post("/organizations/:organizationId/api-keys", org("apikeys:manage"), createOrgApiKey);
fastify.get("/organizations/:organizationId/api-usage", org("org:read"), getOrgApiUsage);
diff --git a/server/src/api/sites/siteTransfers.test.ts b/server/src/api/sites/siteTransfers.test.ts
index 4bf26fd3e..cd2567b1b 100644
--- a/server/src/api/sites/siteTransfers.test.ts
+++ b/server/src/api/sites/siteTransfers.test.ts
@@ -43,7 +43,7 @@ import {
// Only the columns these handlers and applySiteMove touch.
const DDL = `
CREATE TABLE "organization" ("id" text PRIMARY KEY, "name" text NOT NULL);
-CREATE TABLE "user" ("id" text PRIMARY KEY, "email" text NOT NULL, "emailVerified" boolean NOT NULL DEFAULT false, "role" text);
+CREATE TABLE "user" ("id" text PRIMARY KEY, "name" text, "email" text NOT NULL, "emailVerified" boolean NOT NULL DEFAULT false, "role" text);
CREATE TABLE "sites" (
"site_id" serial PRIMARY KEY,
"name" text NOT NULL,
diff --git a/server/src/api/sites/siteTransfers.ts b/server/src/api/sites/siteTransfers.ts
index fe6f41026..dd0c8aa7f 100644
--- a/server/src/api/sites/siteTransfers.ts
+++ b/server/src/api/sites/siteTransfers.ts
@@ -159,13 +159,20 @@ export async function createSiteTransfer(
columns: { name: true },
});
- const sender = await db.query.user.findFirst({ where: eq(user.id, senderId), columns: { email: true } });
+ const sender = await db.query.user.findFirst({
+ where: eq(user.id, senderId),
+ columns: { email: true, name: true },
+ });
+ const trimmedName = sender?.name?.trim();
+ const senderName = trimmedName && !trimmedName.includes("@") ? trimmedName : null;
try {
await sendSiteTransferEmail({
email: transfer.recipientEmail,
- sentBy: sender?.email ?? sourceOrg?.name ?? "A Rybbit user",
+ sentBy: senderName ?? sender?.email ?? sourceOrg?.name ?? "A Rybbit user",
+ sentByEmail: sender?.email ?? null,
siteDomain,
organizationName: sourceOrg?.name ?? "",
+ expiresAt: transfer.expiresAt,
transferLink: transferUrl(transfer.id),
});
} catch (error) {
diff --git a/server/src/api/user/index.ts b/server/src/api/user/index.ts
index 96eff4ada..4e494760e 100644
--- a/server/src/api/user/index.ts
+++ b/server/src/api/user/index.ts
@@ -8,6 +8,7 @@ export { listOrganizationMembers } from "./listOrganizationMembers.js";
// Account Settings
export { updateAccountSettings } from "./updateAccountSettings.js";
export { unsubscribeMarketing, oneClickUnsubscribeMarketing } from "./unsubscribeMarketing.js";
+export { oneClickUnsubscribeReports } from "./unsubscribeReports.js";
// API Keys
export { createUserApiKey } from "./createApiKey.js";
diff --git a/server/src/api/user/unsubscribeReports.test.ts b/server/src/api/user/unsubscribeReports.test.ts
new file mode 100644
index 000000000..edd1d8579
--- /dev/null
+++ b/server/src/api/user/unsubscribeReports.test.ts
@@ -0,0 +1,84 @@
+import type { FastifyReply, FastifyRequest } from "fastify";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ set: vi.fn(),
+ where: vi.fn(),
+}));
+
+vi.mock("../../db/postgres/postgres.js", () => ({
+ db: {
+ update: () => ({ set: (values: unknown) => (mocks.set(values), { where: mocks.where }) }),
+ },
+}));
+vi.mock("../../lib/const.js", () => ({ SECRET: "test-secret" }));
+
+import { signExpiringPayload } from "../../lib/signedToken.js";
+import { oneClickUnsubscribeReports } from "./unsubscribeReports.js";
+
+type Query = { userId?: string; exp?: string; sig?: string };
+
+function requestStub(method: string, query: Query) {
+ return { method, query, log: { error: vi.fn() } } as unknown as FastifyRequest<{ Querystring: Query }>;
+}
+
+function replyStub() {
+ return {
+ status: vi.fn().mockReturnThis(),
+ type: vi.fn().mockReturnThis(),
+ send: vi.fn().mockReturnThis(),
+ } as unknown as FastifyReply;
+}
+
+function signedQuery(userId = "u1"): Query {
+ const { exp, sig } = signExpiringPayload(`unsubscribe-reports:${userId}`, 3600);
+ return { userId, exp: String(exp), sig };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.where.mockResolvedValue(undefined);
+});
+
+describe("one-click weekly report unsubscribe", () => {
+ it("turns off weekly reports from the footer link and confirms it", async () => {
+ const reply = replyStub();
+ await oneClickUnsubscribeReports(requestStub("GET", signedQuery()), reply);
+
+ expect(mocks.set).toHaveBeenCalledWith({ sendAutoEmailReports: false });
+ expect(reply.status).toHaveBeenCalledWith(200);
+ expect(reply.send).toHaveBeenCalledWith(expect.stringContaining("Weekly reports turned off"));
+ });
+
+ it("answers an email client's List-Unsubscribe-Post with a bare 200", async () => {
+ const reply = replyStub();
+ await oneClickUnsubscribeReports(requestStub("POST", signedQuery()), reply);
+
+ expect(mocks.set).toHaveBeenCalledWith({ sendAutoEmailReports: false });
+ expect(reply.status).toHaveBeenCalledWith(200);
+ });
+
+ it("rejects a link signed for another user", async () => {
+ const reply = replyStub();
+ await oneClickUnsubscribeReports(requestStub("POST", { ...signedQuery("u1"), userId: "u2" }), reply);
+
+ expect(mocks.set).not.toHaveBeenCalled();
+ expect(reply.status).toHaveBeenCalledWith(400);
+ });
+
+ it("rejects a link with no signature", async () => {
+ const reply = replyStub();
+ await oneClickUnsubscribeReports(requestStub("GET", { userId: "u1" }), reply);
+
+ expect(mocks.set).not.toHaveBeenCalled();
+ expect(reply.status).toHaveBeenCalledWith(400);
+ });
+
+ it("reports a failed update instead of confirming it", async () => {
+ mocks.where.mockRejectedValue(new Error("db down"));
+ const reply = replyStub();
+ await oneClickUnsubscribeReports(requestStub("POST", signedQuery()), reply);
+
+ expect(reply.status).toHaveBeenCalledWith(500);
+ });
+});
diff --git a/server/src/api/user/unsubscribeReports.ts b/server/src/api/user/unsubscribeReports.ts
new file mode 100644
index 000000000..48814703f
--- /dev/null
+++ b/server/src/api/user/unsubscribeReports.ts
@@ -0,0 +1,78 @@
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { db } from "../../db/postgres/postgres.js";
+import { user } from "../../db/postgres/schema.js";
+import { verifyExpiringPayload } from "../../lib/signedToken.js";
+
+const page = (title: string, heading: string, body: string) => `
+ <!DOCTYPE html>
+ <html><head><title>${title} - Rybbit</title></head>
+ <body style="font-family: sans-serif; max-width: 600px; margin: 50px auto; text-align: center;">
+ <h1>${heading}</h1>
+ <p>${body}</p>
+ </body></html>
+`;
+
+/**
+ * One-click "Turn off weekly reports" from the report email, without logging in.
+ * GET: the footer link, answered with a confirmation page.
+ * POST: an email client's List-Unsubscribe-Post (RFC 8058), answered with 200.
+ * The link carries a signed (userId, exp) pair from weeklyReportUnsubscribeUrl.
+ * It can be turned back on under Account settings.
+ */
+export const oneClickUnsubscribeReports = async (
+ request: FastifyRequest<{ Querystring: { userId?: string; exp?: string; sig?: string } }>,
+ reply: FastifyReply
+) => {
+ const isGetRequest = request.method === "GET";
+ const { userId, exp, sig } = request.query;
+
+ if (!userId || !exp || !sig || !verifyExpiringPayload(`unsubscribe-reports:${userId}`, exp, sig)) {
+ if (isGetRequest) {
+ return reply
+ .status(400)
+ .type("text/html")
+ .send(
+ page(
+ "Weekly reports",
+ "Invalid link",
+ "This link is invalid or has expired. You can turn off weekly reports in your account settings."
+ )
+ );
+ }
+ return reply.status(400).send({ error: "Invalid or expired unsubscribe link" });
+ }
+
+ try {
+ await db.update(user).set({ sendAutoEmailReports: false }).where(eq(user.id, userId));
+ } catch (error) {
+ request.log.error({ err: error }, "Error turning off weekly reports");
+ if (isGetRequest) {
+ return reply
+ .status(500)
+ .type("text/html")
+ .send(
+ page(
+ "Weekly reports",
+ "Something went wrong",
+ "We couldn't turn off your weekly reports just now. Please try the link again in a few minutes."
+ )
+ );
+ }
+ return reply.status(500).send({ error: "Failed to unsubscribe" });
+ }
+
+ if (isGetRequest) {
+ return reply
+ .status(200)
+ .type("text/html")
+ .send(
+ page(
+ "Weekly reports",
+ "Weekly reports turned off",
+ "You won't get weekly reports anymore. You can turn them back on in your account settings."
+ )
+ );
+ }
+ return reply.status(200).send();
+};
diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.ts
index 7a433fd46..ee8d27bb9 100644
--- a/server/src/lib/auth.ts
+++ b/server/src/lib/auth.ts
@@ -202,12 +202,15 @@ const pluginList = [
},
sendInvitationEmail: async invitationData => {
const inviteLink = `${process.env.BASE_URL}/invitation?invitationId=${invitationData.invitation.id}&organization=${invitationData.organization.name}&inviterEmail=${invitationData.inviter.user.email}`;
- await sendInvitationEmail(
- invitationData.email,
- invitationData.inviter.user.email,
- invitationData.organization.name,
- inviteLink
- );
+ await sendInvitationEmail({
+ email: invitationData.email,
+ inviterName: invitationData.inviter.user.name,
+ inviterEmail: invitationData.inviter.user.email,
+ organizationName: invitationData.organization.name,
+ role: invitationData.role,
+ expiresAt: new Date(invitationData.invitation.expiresAt),
+ inviteLink,
+ });
},
schema: {
invitation: {
diff --git a/server/src/lib/email/email.ts b/server/src/lib/email/email.ts
index 0c435958e..720386499 100644
--- a/server/src/lib/email/email.ts
+++ b/server/src/lib/email/email.ts
@@ -1,14 +1,23 @@
-import { Resend } from "resend";
import { render } from "@react-email/components";
-import { IS_CLOUD } from "../const.js";
-import { ApproachingLimitEmail } from "./templates/ApproachingLimitEmail.js";
-import { InvitationEmail } from "./templates/InvitationEmail.js";
-import { LimitExceededEmail } from "./templates/LimitExceededEmail.js";
-import { OtpEmail, type OtpEmailType } from "./templates/OtpEmail.js";
-import { SiteTransferEmail } from "./templates/SiteTransferEmail.js";
-import { WeeklyReportEmail } from "./templates/WeeklyReportEmail.js";
+import { Resend } from "resend";
import type { SiteReport } from "../../services/weekyReports/weeklyReportTypes.js";
+import { welcome } from "../../services/lifecycleEmails/lifecycleContent.js";
+import { IS_CLOUD } from "../const.js";
import { signExpiringPayload } from "../signedToken.js";
+import { letterText, type Letter } from "./letter.js";
+import {
+ ApproachingLimitEmail,
+ approachingLimitSubject,
+ type UsageEmailProps,
+} from "./templates/ApproachingLimitEmail.js";
+import { ChangeEmailEmail } from "./templates/ChangeEmailEmail.js";
+import { InvitationEmail, inviterLabel } from "./templates/InvitationEmail.js";
+import { LetterEmail } from "./templates/LetterEmail.js";
+import { LimitExceededEmail } from "./templates/LimitExceededEmail.js";
+import { OTP_COPY, OtpEmail, type OtpEmailType } from "./templates/OtpEmail.js";
+import { SiteTransferEmail, type SiteTransferEmailProps } from "./templates/SiteTransferEmail.js";
+import { VerifyEmailEmail } from "./templates/VerifyEmailEmail.js";
+import { WeeklyReportEmail, weeklyReportSubject } from "./templates/WeeklyReportEmail.js";
let resend: Resend | undefined;
let marketingAudienceId: string | null = null;
@@ -99,8 +108,18 @@ export const unsubscribeContact = async (email: string): Promise<void> => {
}
};
+const TRANSACTIONAL_FROM = "Rybbit <[email protected]>";
+const BILL_FROM = "Bill from Rybbit <[email protected]>";
+// Replies to any email land in the monitored support inbox.
+const REPLY_TO = "[email protected]";
+
+interface SendOptions {
+ text?: string;
+ headers?: Record<string, string>;
+}
+
/** Sends a transactional email. Throws when Resend does not accept it. */
-export const sendEmail = async (email: string, subject: string, html: string) => {
+export const sendEmail = async (email: string, subject: string, html: string, options: SendOptions = {}) => {
if (!resend) {
return;
// not sure how to handle self hosted instances without resend
@@ -108,10 +127,13 @@ export const sendEmail = async (email: string, subject: string, html: string) =>
}
try {
const response = await resend.emails.send({
- from: "Rybbit <[email protected]>",
+ from: TRANSACTIONAL_FROM,
+ replyTo: REPLY_TO,
to: email,
subject,
html,
+ ...(options.text ? { text: options.text } : {}),
+ ...(options.headers ? { headers: options.headers } : {}),
});
if (response.error) {
throw new ResendRequestError("email send", response.error);
@@ -123,163 +145,91 @@ export const sendEmail = async (email: string, subject: string, html: string) =>
}
};
-const OTP_SUBJECTS: Record<OtpEmailType, string> = {
- "sign-in": "Your Rybbit Sign-In Code",
- "email-verification": "Verify Your Email Address",
- "forget-password": "Reset Your Password",
- "change-email": "Change Your Email Address",
-};
-
export const sendOtpEmail = async (email: string, otp: string, type: OtpEmailType) => {
- const html = await render(OtpEmail({ otp, type }));
- await sendEmail(email, OTP_SUBJECTS[type], html);
+ const html = await render(OtpEmail({ otp, type, email }));
+ await sendEmail(email, OTP_COPY[type].subject, html);
};
export const sendEmailVerificationLink = async (email: string, verificationUrl: string) => {
- const html = `
- <div style="font-family: Arial, sans-serif; max-width: 560px; margin: 0 auto; padding: 24px; color: #111;">
- <h2 style="margin: 0 0 16px;">Verify your email</h2>
- <p>Click the button below to verify this email address on your Rybbit account.</p>
- <p style="margin: 24px 0;">
- <a href="${verificationUrl}" style="background: #111; color: #fff; padding: 12px 20px; border-radius: 6px; text-decoration: none; display: inline-block;">Verify email</a>
- </p>
- <p style="font-size: 12px; color: #666; word-break: break-all;">Or paste this link into your browser: ${verificationUrl}</p>
- </div>
- `;
-
- await sendEmail(email, "Verify your Rybbit email", html);
-};
-
-export const sendChangeEmailVerification = async (
- currentEmail: string,
- newEmail: string,
- verificationUrl: string
-) => {
- const html = `
- <div style="font-family: Arial, sans-serif; max-width: 560px; margin: 0 auto; padding: 24px; color: #111;">
- <h2 style="margin: 0 0 16px;">Confirm your new email</h2>
- <p>We received a request to change the email on your Rybbit account from <strong>${currentEmail}</strong> to <strong>${newEmail}</strong>.</p>
- <p>Click the button below to confirm the change. If you didn't request this, you can safely ignore this email.</p>
- <p style="margin: 24px 0;">
- <a href="${verificationUrl}" style="background: #111; color: #fff; padding: 12px 20px; border-radius: 6px; text-decoration: none; display: inline-block;">Confirm email change</a>
- </p>
- <p style="font-size: 12px; color: #666; word-break: break-all;">Or paste this link into your browser: ${verificationUrl}</p>
- </div>
- `;
-
- await sendEmail(currentEmail, "Confirm your email change on Rybbit", html);
+ const html = await render(VerifyEmailEmail({ email, verificationUrl }));
+ await sendEmail(email, "Verify your email for Rybbit", html);
};
-export const sendInvitationEmail = async (
- email: string,
- invitedBy: string,
- organizationName: string,
- inviteLink: string
-) => {
- const html = await render(
- InvitationEmail({
- email,
- invitedBy,
- organizationName,
- inviteLink,
- })
- );
-
- await sendEmail(email, "You're Invited to Join an Organization on Rybbit", html);
+export const sendChangeEmailVerification = async (currentEmail: string, newEmail: string, confirmUrl: string) => {
+ const html = await render(ChangeEmailEmail({ currentEmail, newEmail, confirmUrl }));
+ await sendEmail(currentEmail, "Confirm your new Rybbit email address", html);
};
-export const sendSiteTransferEmail = async (props: {
+export const sendInvitationEmail = async (props: {
email: string;
- sentBy: string;
- siteDomain: string;
+ inviterName: string | null;
+ inviterEmail: string;
organizationName: string;
- transferLink: string;
+ role: string;
+ expiresAt: Date;
+ inviteLink: string;
}) => {
- const html = await render(SiteTransferEmail(props));
- await sendEmail(props.email, `${props.siteDomain} is being transferred to you on Rybbit`, html);
+ const html = await render(InvitationEmail(props));
+ const inviter = inviterLabel(props.inviterName, props.inviterEmail);
+ await sendEmail(props.email, `${inviter} invited you to ${props.organizationName} on Rybbit`, html);
};
-export const sendLimitExceededEmail = async (
- email: string,
- organizationName: string,
- eventCount: number,
- eventLimit: number
-) => {
- const upgradeLink = "https://app.rybbit.io/settings/subscription";
-
- const html = await render(
- LimitExceededEmail({
- organizationName,
- eventCount,
- eventLimit,
- upgradeLink,
- })
- );
-
- await sendEmail(email, `Action Required: ${organizationName} has exceeded its monthly event limit`, html);
+export const sendSiteTransferEmail = async (props: SiteTransferEmailProps) => {
+ const html = await render(SiteTransferEmail(props));
+ await sendEmail(props.email, `${props.sentBy} wants to transfer ${props.siteDomain} to you`, html);
};
-export const sendApproachingLimitEmail = async (
- email: string,
- organizationName: string,
- eventCount: number,
- eventLimit: number
-) => {
- const upgradeLink = "https://app.rybbit.io/settings/subscription";
-
- const html = await render(
- ApproachingLimitEmail({
- organizationName,
- eventCount,
- eventLimit,
- upgradeLink,
- })
- );
-
- await sendEmail(email, `${organizationName} is approaching its monthly event limit`, html);
+export const sendLimitExceededEmail = async (email: string, usage: UsageEmailProps) => {
+ const html = await render(LimitExceededEmail(usage));
+ await sendEmail(email, `Tracking is paused for ${usage.organizationName}`, html);
};
-export const sendWeeklyReportEmail = async (
- email: string,
- userName: string,
- organizationName: string,
- site: SiteReport
-) => {
- const html = await render(
- WeeklyReportEmail({
- userName,
- organizationName,
- site,
- })
- );
+export const sendApproachingLimitEmail = async (email: string, usage: UsageEmailProps) => {
+ const html = await render(ApproachingLimitEmail(usage));
+ await sendEmail(email, approachingLimitSubject(usage.organizationName, usage.eventCount, usage.eventLimit), html);
+};
- const subject = `Weekly Analytics Report - ${site.siteName}`;
+/**
+ * Signed one-click link that turns off weekly reports for one user, used in the
+ * report footer and its List-Unsubscribe header. Same 2-year TTL as the
+ * marketing link: it has to keep working from old emails.
+ */
+export const weeklyReportUnsubscribeUrl = (userId: string): string => {
+ const { exp, sig } = signExpiringPayload(`unsubscribe-reports:${userId}`, 2 * 365 * 24 * 3600);
+ return `${process.env.BASE_URL}/api/user/unsubscribe-reports-oneclick?userId=${encodeURIComponent(userId)}&exp=${exp}&sig=${sig}`;
+};
- await sendEmail(email, subject, html);
+export const sendWeeklyReportEmail = async ({
+ email,
+ userId,
+ site,
+}: {
+ email: string;
+ userId: string;
+ site: SiteReport;
+}) => {
+ const unsubscribeUrl = weeklyReportUnsubscribeUrl(userId);
+ const html = await render(WeeklyReportEmail({ site, unsubscribeUrl }));
+ await sendEmail(email, weeklyReportSubject(site), html, {
+ headers: {
+ "List-Unsubscribe": `<${unsubscribeUrl}>`,
+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
+ },
+ });
};
export const sendWelcomeEmail = async (email: string, name?: string) => {
if (!resend) return;
- const greeting = name ? `Hi ${name}` : "Hi there";
- const text = `${greeting},
-
-Welcome to Rybbit! Thanks for signing up.
-
-I'm excited to have you on board. Rybbit is fully self-funded and we're fully committed to making an analytics platform that only serves the interests of our users.
-
-If you run into any issues or have any questions or suggestions, just reply to this email - I'd love to hear from you.
-
-Cheers,
-Bill`;
-
+ const letter = welcome(name);
try {
const { error } = await resend.emails.send({
- from: "Bill from Rybbit <[email protected]>",
- replyTo: "[email protected]",
+ from: BILL_FROM,
+ replyTo: REPLY_TO,
to: email,
- subject: "Welcome to Rybbit!",
- text,
+ subject: letter.subject,
+ html: await render(LetterEmail({ letter })),
+ text: letterText(letter),
});
if (error) throw new ResendRequestError("welcome email send", error);
} catch (error) {
@@ -298,8 +248,9 @@ export const marketingUnsubscribeUrl = (email: string): string => {
};
/**
- * Plain-text lifecycle email from Bill with a monitored reply address.
- * All state-machine onboarding/retention emails go through here.
+ * Lifecycle letter from Bill with a monitored reply address, sent as Ledger
+ * HTML with the same content as plain text. All state-machine
+ * onboarding/retention emails go through here.
*
* Returns true only when Resend actually accepted the message: the SDK
* resolves with { data: null, error } on HTTP/network failures rather than
@@ -307,24 +258,23 @@ export const marketingUnsubscribeUrl = (email: string): string => {
* stable idempotencyKey (the lifecycle email key) so a retry after an
* "accepted but response lost" failure can't double-send.
*/
-export const sendLifecycleEmail = async (
- email: string,
- subject: string,
- text: string,
- idempotencyKey?: string
-): Promise<boolean> => {
+export const sendLifecycleEmail = async (email: string, letter: Letter, idempotencyKey?: string): Promise<boolean> => {
if (!resend) return false;
const unsubscribeUrl = marketingUnsubscribeUrl(email);
try {
+ const html = await render(
+ LetterEmail({ letter, footer: [{ label: "Unsubscribe from these emails", href: unsubscribeUrl }] })
+ );
const response = await resend.emails.send(
{
- from: "Bill from Rybbit <[email protected]>",
- replyTo: "[email protected]",
+ from: BILL_FROM,
+ replyTo: REPLY_TO,
to: email,
- subject,
- text: `${text}\n\n--\nUnsubscribe from these emails: ${unsubscribeUrl}`,
+ subject: letter.subject,
+ html,
+ text: `${letterText(letter)}\n\n--\nUnsubscribe from these emails: ${unsubscribeUrl}`,
headers: {
"List-Unsubscribe": `<${unsubscribeUrl}>`,
"List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
diff --git a/server/src/lib/email/format.ts b/server/src/lib/email/format.ts
new file mode 100644
index 000000000..e0f7ad5f0
--- /dev/null
+++ b/server/src/lib/email/format.ts
@@ -0,0 +1,44 @@
+import { DateTime } from "luxon";
+
+export const appUrl = () => (process.env.BASE_URL || "https://app.rybbit.io").replace(/\/$/, "");
+
+export const formatCount = (n: number | null | undefined): string =>
+ n == null || !Number.isFinite(n) ? "0" : Math.round(n).toLocaleString("en-US");
+
+/** "Oct 26, 2026" */
+export const formatDate = (date: DateTime): string => date.setZone("utc").toFormat("LLL d, yyyy");
+
+/** "Oct 26, 2026 at 14:02 UTC" */
+export const formatDateTime = (date: DateTime): string => date.setZone("utc").toFormat("LLL d, yyyy 'at' HH:mm 'UTC'");
+
+export const plural = (n: number, noun: string, pluralNoun = `${noun}s`) =>
+ `${formatCount(n)} ${n === 1 ? noun : pluralNoun}`;
+
+/**
+ * Week-over-week change as a signed percentage, or null when there is nothing
+ * to compare against: a jump from zero is not "+100%".
+ */
+export const percentChange = (current: number | null | undefined, previous: number | null | undefined) => {
+ const curr = current ?? 0;
+ const prev = previous ?? 0;
+ if (!Number.isFinite(curr) || !Number.isFinite(prev) || prev <= 0) return null;
+ return ((curr - prev) / prev) * 100;
+};
+
+/** "+9.8%", "βˆ’5.4%" (true minus sign), "0%" */
+export const formatChange = (change: number): string => {
+ const rounded = Math.round(change * 10) / 10;
+ if (rounded === 0) return "0%";
+ return `${rounded > 0 ? "+" : "βˆ’"}${Math.abs(rounded).toFixed(1)}%`;
+};
+
+/** "2m 41s", "48s" */
+export const formatDuration = (seconds: number | null | undefined): string => {
+ const s = Math.max(0, Math.round(seconds ?? 0));
+ if (s < 60) return `${s}s`;
+ return `${Math.floor(s / 60)}m ${s % 60}s`;
+};
+
+/** Cuts long paths and referrers so a table cell stays one or two lines. */
+export const truncate = (value: string, max = 56): string =>
+ value.length > max ? `${value.slice(0, max - 1)}…` : value;
diff --git a/server/src/lib/email/letter.ts b/server/src/lib/email/letter.ts
new file mode 100644
index 000000000..6373b2ab5
--- /dev/null
+++ b/server/src/lib/email/letter.ts
@@ -0,0 +1,66 @@
+/**
+ * A letter from Bill: the welcome and lifecycle emails. Content is written once
+ * as blocks and rendered twice, as Ledger HTML (LetterEmail.tsx) and as the
+ * plain-text part (letterText), so the two can't drift apart.
+ */
+
+export interface LetterRow {
+ label: string;
+ value: string;
+ /** Links the value; the text part prints the URL instead. */
+ href?: string;
+ strong?: boolean;
+}
+
+export type LetterBlock =
+ | { type: "p"; text: string }
+ | { type: "note"; text: string }
+ | { type: "rows"; rows: LetterRow[] }
+ | { type: "steps"; steps: { title: string; detail: string }[] }
+ | { type: "stats"; stats: { label: string; value: string }[] }
+ | { type: "code"; code: string }
+ /** One site's tracking script in a multi-site email. */
+ | { type: "site"; domain: string; code: string; guide?: { label: string; url: string } }
+ | { type: "button"; label: string; href: string; secondary?: { label: string; href: string } };
+
+export interface Letter {
+ subject: string;
+ preview: string;
+ greeting: string;
+ blocks: LetterBlock[];
+}
+
+export const greeting = (name?: string | null) => {
+ // Email-signup users have their email prefix stored as their name - don't greet with that
+ const clean = name && !name.includes("@") ? name.split(" ")[0] : "";
+ return clean ? `Hi ${clean},` : "Hi,";
+};
+
+export const SIGNOFF = "Bill\nFounder, Rybbit";
+
+const lowerFirst = (s: string) => s.charAt(0).toLowerCase() + s.slice(1);
+
+const blockText = (block: LetterBlock): string => {
+ switch (block.type) {
+ case "p":
+ case "note":
+ return block.text;
+ case "rows":
+ return block.rows.map(row => `${row.label}: ${row.href ?? row.value}`).join("\n");
+ case "steps":
+ return block.steps.map((step, i) => `${i + 1}. ${step.title} (${lowerFirst(step.detail)})`).join("\n");
+ case "stats":
+ return block.stats.map(stat => `${stat.label}: ${stat.value}`).join("\n");
+ case "code":
+ return block.code;
+ case "site":
+ return `${block.domain}${block.guide ? ` (${block.guide.label} guide: ${block.guide.url})` : ""}\n${block.code}`;
+ case "button":
+ return [`${block.label}: ${block.href}`, block.secondary && `${block.secondary.label}: ${block.secondary.href}`]
+ .filter(Boolean)
+ .join("\n");
+ }
+};
+
+export const letterText = (letter: Letter): string =>
+ [letter.greeting, ...letter.blocks.map(blockText), SIGNOFF].join("\n\n");
diff --git a/server/src/lib/email/templates/ApproachingLimitEmail.tsx b/server/src/lib/email/templates/ApproachingLimitEmail.tsx
index 8a95f63f1..12bc9a832 100644
--- a/server/src/lib/email/templates/ApproachingLimitEmail.tsx
+++ b/server/src/lib/email/templates/ApproachingLimitEmail.tsx
@@ -1,98 +1,134 @@
-import {
- Body,
- Container,
- Head,
- Hr,
- Html,
- Img,
- Link,
- Preview,
- Text,
- Tailwind,
- pixelBasedPreset,
-} from "@react-email/components";
+import { DateTime } from "luxon";
import * as React from "react";
+import { appUrl, formatCount, formatDate, plural } from "../format.js";
+import { color, H1, H2, HELP_URL, LedgerLayout, Meter, P, PrimaryButton, Rows, ShareTable } from "./ledger.js";
-interface ApproachingLimitEmailProps {
+export interface SiteUsage {
+ domain: string;
+ events: number;
+}
+
+export interface UsageEmailProps {
organizationName: string;
eventCount: number;
eventLimit: number;
- upgradeLink: string;
+ /** The organization's sites with this month's events, largest first. */
+ sites: SiteUsage[];
+ now?: DateTime;
}
-export const ApproachingLimitEmail = ({
- organizationName,
- eventCount,
- eventLimit,
- upgradeLink,
-}: ApproachingLimitEmailProps) => {
- const currentYear = new Date().getFullYear();
- const usagePercent = Math.min(100, Math.round((eventCount / eventLimit) * 100));
-
- return (
- <Html>
- <Head />
- <Preview>{organizationName} is approaching its monthly event limit</Preview>
- <Tailwind
- config={{
- presets: [pixelBasedPreset],
- theme: {
- extend: {
- colors: {
- brand: "#10b981",
- darkText: "#111827",
- mutedText: "#6b7280",
- borderColor: "#e5e7eb",
- },
- },
- },
- }}
- >
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-8 px-6 max-w-[600px]">
- <Img
- src="https://app.rybbit.io/rybbit/horizontal_black.svg"
- alt="Rybbit"
- width="120"
- height="28"
- className="mb-8"
- />
-
- <Text className="text-darkText text-base leading-relaxed mb-4">Hi there,</Text>
+const MAX_SITE_ROWS = 5;
- <Text className="text-darkText text-base leading-relaxed mb-4">
- Your organization <span className="font-semibold">{organizationName}</span> is on track to exceed its
- monthly event limit before the end of the month.
- </Text>
+/** Usage is counted per calendar month (UTC), so the limit resets on the 1st. */
+export const usagePeriod = (now: DateTime) => {
+ const utc = now.setZone("utc");
+ const start = utc.startOf("month");
+ const reset = start.plus({ months: 1 });
+ return { start, reset, daysLeft: Math.max(0, Math.ceil(reset.diff(utc, "days").days)) };
+};
- <Text className="text-darkText text-base leading-relaxed mb-4">
- Current usage: <span className="font-semibold">{eventCount.toLocaleString()}</span> events ({usagePercent}
- %)
- <br />
- Monthly limit: <span className="font-semibold">{eventLimit.toLocaleString()}</span> events
- </Text>
+/** When the limit will be reached at this month's average daily rate, if before the reset. */
+export const projectedLimitDate = (eventCount: number, eventLimit: number, now: DateTime): DateTime | null => {
+ const { start, reset } = usagePeriod(now);
+ const daysElapsed = now.diff(start, "days").days;
+ if (daysElapsed < 1 || eventCount <= 0 || eventCount >= eventLimit) return null;
+ const perDay = eventCount / daysElapsed;
+ const date = now.plus({ days: (eventLimit - eventCount) / perDay });
+ return date < reset ? date : null;
+};
- <Text className="text-darkText text-base leading-relaxed mb-4">
- Once you reach your limit, analytics tracking will be paused until your plan resets or you upgrade.
- Upgrading now keeps your data flowing without interruption.
- </Text>
+export const usagePercent = (eventCount: number, eventLimit: number) =>
+ eventLimit > 0 ? Math.floor((eventCount / eventLimit) * 100) : 100;
- <Text className="text-darkText text-base leading-relaxed mb-4">
- <Link href={upgradeLink} className="text-brand underline">
- Upgrade your plan
- </Link>
- </Text>
+export const approachingLimitSubject = (
+ organizationName: string,
+ eventCount: number,
+ eventLimit: number,
+ now = DateTime.utc()
+) =>
+ `${organizationName} has used ${usagePercent(eventCount, eventLimit)}% of its ${now.setZone("utc").toFormat("LLLL")} events`;
- <Text className="text-mutedText text-sm leading-relaxed">
- Need help? Reply to this email or contact [email protected].
- </Text>
+const shortDate = (date: DateTime) => date.setZone("utc").toFormat("LLL d");
- <Hr className="border-borderColor my-8" />
+export const ApproachingLimitEmail = ({
+ organizationName,
+ eventCount,
+ eventLimit,
+ sites,
+ now = DateTime.utc(),
+}: UsageEmailProps) => {
+ const { start, reset, daysLeft } = usagePeriod(now);
+ const percent = usagePercent(eventCount, eventLimit);
+ const projected = projectedLimitDate(eventCount, eventLimit, now);
+ const month = now.setZone("utc").toFormat("LLLL");
+ const total = sites.reduce((sum, site) => sum + site.events, 0);
+ const top = sites.slice(0, MAX_SITE_ROWS);
+ const largest = top[0]?.events || 1;
- <Text className="text-mutedText text-xs">Β© {currentYear} Rybbit Analytics</Text>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ return (
+ <LedgerLayout
+ preview={
+ projected
+ ? `At this rate you'll hit your ${formatCount(eventLimit)}-event limit around ${shortDate(projected)}.`
+ : `${formatCount(eventCount)} of ${formatCount(eventLimit)} events used, with ${plural(daysLeft, "day")} left in ${month}.`
+ }
+ footer={[
+ { label: "Help", href: HELP_URL },
+ { label: "Billing", href: `${appUrl()}/settings/billing` },
+ ]}
+ >
+ <H1>
+ {organizationName} has used {percent}% of this month's events
+ </H1>
+ <P>
+ That's {formatCount(eventCount)} of {formatCount(eventLimit)} events, with {plural(daysLeft, "day")} left in{" "}
+ {month}.{projected ? ` At this rate you'll hit the limit around ${shortDate(projected)}.` : ""}
+ </P>
+ <Meter
+ used={formatCount(eventCount)}
+ of={`${formatCount(eventLimit)} events`}
+ percent={percent}
+ barColor={color.warning}
+ startLabel={shortDate(start)}
+ endLabel={`Resets ${shortDate(reset)}`}
+ />
+ <Rows
+ rows={[
+ { label: "Used", value: `${formatCount(eventCount)} events (${percent}%)` },
+ { label: "Plan limit", value: `${formatCount(eventLimit)} events a month` },
+ { label: "Resets", value: formatDate(reset) },
+ ...(projected
+ ? [{ label: "At this pace", value: `Limit reached around ${shortDate(projected)}`, strong: true }]
+ : []),
+ ]}
+ />
+ <P top={24}>
+ If you hit the limit, Rybbit stops tracking until your plan resets on {shortDate(reset)}. Your existing data
+ stays available.
+ </P>
+ {sites.length > 1 && (
+ <>
+ <H2>By site</H2>
+ <ShareTable
+ labelHeader="Site"
+ valueHeader="Events"
+ rows={top.map(site => ({
+ label: site.domain,
+ value: formatCount(site.events),
+ share: total > 0 ? (site.events / total) * 100 : null,
+ bar: (site.events / largest) * 100,
+ }))}
+ />
+ {sites.length > MAX_SITE_ROWS && (
+ <P top={12}>
+ <span style={{ fontSize: 13, color: color.muted }}>
+ Plus {plural(sites.length - MAX_SITE_ROWS, "more site")}.
+ </span>
+ </P>
+ )}
+ </>
+ )}
+ <PrimaryButton top={40} label="Upgrade plan" href={`${appUrl()}/settings/billing`} />
+ </LedgerLayout>
);
};
diff --git a/server/src/lib/email/templates/ChangeEmailEmail.tsx b/server/src/lib/email/templates/ChangeEmailEmail.tsx
new file mode 100644
index 000000000..861e59c17
--- /dev/null
+++ b/server/src/lib/email/templates/ChangeEmailEmail.tsx
@@ -0,0 +1,40 @@
+import * as React from "react";
+import { appUrl } from "../format.js";
+import { H1, HELP_URL, LedgerLayout, Note, P, PrimaryButton, Rows, TextLink, UrlFallback } from "./ledger.js";
+
+interface ChangeEmailEmailProps {
+ currentEmail: string;
+ newEmail: string;
+ confirmUrl: string;
+}
+
+/**
+ * Sent to the current address. Confirming makes Better Auth send a
+ * verification link to the new address, which completes the change.
+ */
+export const ChangeEmailEmail = ({ currentEmail, newEmail, confirmUrl }: ChangeEmailEmailProps) => (
+ <LedgerLayout
+ preview={`Confirm the switch from ${currentEmail} to ${newEmail}.`}
+ footer={[
+ { label: "Help", href: HELP_URL },
+ { label: "Account settings", href: `${appUrl()}/settings/account` },
+ ]}
+ >
+ <H1>Confirm your new email address</H1>
+ <P>We got a request to change the email on your Rybbit account.</P>
+ <Rows
+ top={24}
+ rows={[
+ { label: "Current", value: currentEmail },
+ { label: "New", value: newEmail, strong: true },
+ ]}
+ />
+ <PrimaryButton label="Confirm the change" href={confirmUrl} />
+ <P top={24}>Once you confirm, we'll send a verification link to {newEmail}.</P>
+ <UrlFallback url={confirmUrl} />
+ <Note>
+ Didn't request this? Don't click the button, and{" "}
+ <TextLink href={`${appUrl()}/settings/account`}>change your password</TextLink> right away.
+ </Note>
+ </LedgerLayout>
+);
diff --git a/server/src/lib/email/templates/InvitationEmail.tsx b/server/src/lib/email/templates/InvitationEmail.tsx
index e7b956aa6..935105728 100644
--- a/server/src/lib/email/templates/InvitationEmail.tsx
+++ b/server/src/lib/email/templates/InvitationEmail.tsx
@@ -1,83 +1,53 @@
-import {
- Body,
- Container,
- Head,
- Hr,
- Html,
- Img,
- Link,
- Preview,
- Text,
- Tailwind,
- pixelBasedPreset,
-} from "@react-email/components";
+import { DateTime } from "luxon";
import * as React from "react";
+import { formatDateTime } from "../format.js";
+import { H1, HELP_URL, LedgerLayout, Note, P, PrimaryButton, Rows } from "./ledger.js";
interface InvitationEmailProps {
- email: string;
- invitedBy: string;
+ inviterName: string | null;
+ inviterEmail: string;
organizationName: string;
+ role: string;
+ expiresAt: Date;
inviteLink: string;
}
-export const InvitationEmail = ({ email, invitedBy, organizationName, inviteLink }: InvitationEmailProps) => {
- const currentYear = new Date().getFullYear();
-
+/** "Sam Chen" when the inviter has a real name, otherwise their email. */
+export const inviterLabel = (name: string | null, email: string) =>
+ name && name.trim() && !name.includes("@") ? name.trim() : email;
+
+const roleLabel = (role: string) => role.charAt(0).toUpperCase() + role.slice(1);
+
+export const InvitationEmail = ({
+ inviterName,
+ inviterEmail,
+ organizationName,
+ role,
+ expiresAt,
+ inviteLink,
+}: InvitationEmailProps) => {
+ const inviter = inviterLabel(inviterName, inviterEmail);
+ const expires = formatDateTime(DateTime.fromJSDate(expiresAt));
return (
- <Html>
- <Head />
- <Preview>You're invited to join {organizationName} on Rybbit</Preview>
- <Tailwind
- config={{
- presets: [pixelBasedPreset],
- theme: {
- extend: {
- colors: {
- brand: "#10b981",
- darkText: "#111827",
- mutedText: "#6b7280",
- borderColor: "#e5e7eb",
- },
- },
- },
- }}
- >
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-8 px-6 max-w-[600px]">
- <Img
- src="https://app.rybbit.io/rybbit/horizontal_black.svg"
- alt="Rybbit"
- width="120"
- height="28"
- className="mb-8"
- />
-
- <Text className="text-darkText text-base leading-relaxed mb-4">Hi there,</Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- {invitedBy} has invited you to join <span className="font-semibold">{organizationName}</span> on Rybbit
- Analytics.
- </Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- Rybbit is an open-source analytics platform that helps you understand your website traffic while
- respecting user privacy.
- </Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- <Link href={inviteLink} className="text-brand underline">
- Accept the invitation
- </Link>
- </Text>
-
- <Text className="text-mutedText text-sm leading-relaxed">This invitation was sent to {email}.</Text>
-
- <Hr className="border-borderColor my-8" />
-
- <Text className="text-mutedText text-xs">Β© {currentYear} Rybbit Analytics</Text>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ <LedgerLayout
+ preview={`Join as ${/^[aeiou]/i.test(role) ? "an" : "a"} ${role}. The invitation expires ${expires}.`}
+ footer={[{ label: "Help", href: HELP_URL }]}
+ >
+ <H1>Join {organizationName} on Rybbit</H1>
+ <P>
+ {inviter === inviterEmail ? inviterEmail : `${inviter} (${inviterEmail})`} invited you to join{" "}
+ {organizationName}.
+ </P>
+ <Rows
+ top={24}
+ rows={[
+ { label: "Organization", value: organizationName },
+ { label: "Role", value: roleLabel(role) },
+ { label: "Expires", value: expires },
+ ]}
+ />
+ <PrimaryButton label="Accept invitation" href={inviteLink} />
+ <Note>If you don't have a Rybbit account yet, you'll create one when you accept.</Note>
+ </LedgerLayout>
);
};
diff --git a/server/src/lib/email/templates/LetterEmail.tsx b/server/src/lib/email/templates/LetterEmail.tsx
new file mode 100644
index 000000000..b291c4667
--- /dev/null
+++ b/server/src/lib/email/templates/LetterEmail.tsx
@@ -0,0 +1,93 @@
+import * as React from "react";
+import type { Letter, LetterBlock } from "../letter.js";
+import {
+ color,
+ LedgerLayout,
+ Note,
+ P,
+ PrimaryButton,
+ Rows,
+ Signoff,
+ Snippet,
+ StatGrid,
+ Steps,
+ TextLink,
+ type FooterLink,
+} from "./ledger.js";
+
+interface LetterEmailProps {
+ letter: Letter;
+ footer?: FooterLink[];
+}
+
+/** Space above a block depends on what it follows: prose runs tight, everything else breathes. */
+const gapBefore = (block: LetterBlock, previous: LetterBlock | undefined): number => {
+ const afterProse = previous === undefined || previous.type === "p";
+ switch (block.type) {
+ case "p":
+ return afterProse ? 16 : 28;
+ case "code":
+ return afterProse ? 16 : 12;
+ case "site":
+ return 24;
+ case "note":
+ return 24;
+ case "button":
+ return 32;
+ default:
+ return 28;
+ }
+};
+
+const Block = ({ block, top }: { block: LetterBlock; top: number }) => {
+ switch (block.type) {
+ case "p":
+ return <P top={top}>{block.text}</P>;
+ case "note":
+ return <Note top={top}>{block.text}</Note>;
+ case "rows":
+ return (
+ <Rows
+ top={top}
+ rows={block.rows.map(row => ({
+ label: row.label,
+ strong: row.strong,
+ value: row.href ? <TextLink href={row.href}>{row.value}</TextLink> : row.value,
+ }))}
+ />
+ );
+ case "steps":
+ return <Steps top={top} steps={block.steps} />;
+ case "stats":
+ return <StatGrid top={top} stats={block.stats} />;
+ case "code":
+ return <Snippet top={top} code={block.code} />;
+ case "site":
+ return (
+ <div style={{ marginTop: top }}>
+ <p style={{ margin: 0, fontSize: 14, lineHeight: "20px", fontWeight: 600, color: color.text }}>
+ {block.domain}
+ {block.guide && (
+ <span style={{ fontWeight: 400, color: color.muted }}>
+ {" Β· "}
+ <TextLink href={block.guide.url}>{block.guide.label} guide</TextLink>
+ </span>
+ )}
+ </p>
+ <Snippet top={8} code={block.code} />
+ </div>
+ );
+ case "button":
+ return <PrimaryButton top={top} label={block.label} href={block.href} secondary={block.secondary} />;
+ }
+};
+
+export const LetterEmail = ({ letter, footer }: LetterEmailProps) => (
+ <LedgerLayout preview={letter.preview} footer={footer}>
+ <P top={36}>{letter.greeting}</P>
+ {letter.blocks.map((block, i) => (
+ <Block key={i} block={block} top={gapBefore(block, letter.blocks[i - 1])} />
+ ))}
+ <Signoff />
+ </LedgerLayout>
+);
diff --git a/server/src/lib/email/templates/LimitExceededEmail.tsx b/server/src/lib/email/templates/LimitExceededEmail.tsx
index a4f2a21c7..d9e6734ed 100644
--- a/server/src/lib/email/templates/LimitExceededEmail.tsx
+++ b/server/src/lib/email/templates/LimitExceededEmail.tsx
@@ -1,95 +1,72 @@
-import {
- Body,
- Container,
- Head,
- Hr,
- Html,
- Img,
- Link,
- Preview,
- Text,
- Tailwind,
- pixelBasedPreset,
-} from "@react-email/components";
+import { DateTime } from "luxon";
import * as React from "react";
+import { appUrl, formatCount, formatDateTime, plural } from "../format.js";
+import { usagePercent, usagePeriod, type UsageEmailProps } from "./ApproachingLimitEmail.js";
+import { Badge, color, H1, HELP_URL, LedgerLayout, Meter, Note, P, PrimaryButton, Rows } from "./ledger.js";
-interface LimitExceededEmailProps {
- organizationName: string;
- eventCount: number;
- eventLimit: number;
- upgradeLink: string;
-}
+const MAX_LISTED_SITES = 5;
+const shortDate = (date: DateTime) => date.setZone("utc").toFormat("LLL d");
+
+/**
+ * Over the limit, ingestion stops for every site in the organization until the
+ * month resets or the plan changes (a Stripe webhook refreshes the blocks
+ * straight away). Dashboards and stored data stay readable throughout.
+ */
export const LimitExceededEmail = ({
organizationName,
eventCount,
eventLimit,
- upgradeLink,
-}: LimitExceededEmailProps) => {
- const currentYear = new Date().getFullYear();
+ sites,
+ now = DateTime.utc(),
+}: UsageEmailProps) => {
+ const { start, reset } = usagePeriod(now);
+ const domains = sites.map(site => site.domain);
+ const listed = domains.slice(0, MAX_LISTED_SITES).join(", ");
+ const hidden = domains.length - MAX_LISTED_SITES;
+ const which =
+ domains.length === 0 ? "its sites" : domains.length === 1 ? domains[0] : `its ${plural(domains.length, "site")}`;
return (
- <Html>
- <Head />
- <Preview>{organizationName} has exceeded its monthly event limit</Preview>
- <Tailwind
- config={{
- presets: [pixelBasedPreset],
- theme: {
- extend: {
- colors: {
- brand: "#10b981",
- darkText: "#111827",
- mutedText: "#6b7280",
- borderColor: "#e5e7eb",
- },
- },
- },
- }}
- >
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-8 px-6 max-w-[600px]">
- <Img
- src="https://app.rybbit.io/rybbit/horizontal_black.svg"
- alt="Rybbit"
- width="120"
- height="28"
- className="mb-8"
- />
-
- <Text className="text-darkText text-base leading-relaxed mb-4">Hi there,</Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- Your organization <span className="font-semibold">{organizationName}</span> has exceeded its monthly event
- limit.
- </Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- Current usage: <span className="font-semibold">{eventCount.toLocaleString()}</span> events
- <br />
- Monthly limit: <span className="font-semibold">{eventLimit.toLocaleString()}</span> events
- </Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- Analytics tracking has been paused. To resume tracking and access your data, upgrade your plan:
- </Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- <Link href={upgradeLink} className="text-brand underline">
- Upgrade your plan
- </Link>
- </Text>
-
- <Text className="text-mutedText text-sm leading-relaxed">
- Need help? Reply to this email or contact [email protected].
- </Text>
-
- <Hr className="border-borderColor my-8" />
-
- <Text className="text-mutedText text-xs">Β© {currentYear} Rybbit Analytics</Text>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ <LedgerLayout
+ preview={`You went over your ${formatCount(eventLimit)}-event limit. Upgrade to start tracking again.`}
+ footer={[
+ { label: "Help", href: HELP_URL },
+ { label: "Billing", href: `${appUrl()}/settings/billing` },
+ ]}
+ >
+ <H1>Tracking is paused for {organizationName}</H1>
+ <P>
+ {organizationName} went over its {formatCount(eventLimit)}-event monthly limit, so Rybbit has stopped tracking{" "}
+ {which}.
+ </P>
+ <div style={{ marginTop: 24 }}>
+ <Badge tone="danger">Paused</Badge>
+ <span style={{ paddingLeft: 8, fontSize: 13, lineHeight: "20px", color: color.muted }}>
+ since {now.setZone("utc").toFormat("LLL d, HH:mm 'UTC'")}
+ </span>
+ </div>
+ <Meter
+ top={16}
+ used={formatCount(eventCount)}
+ of={`${formatCount(eventLimit)} events`}
+ percent={usagePercent(eventCount, eventLimit)}
+ barColor={color.danger}
+ startLabel={shortDate(start)}
+ endLabel={`Resets ${shortDate(reset)}`}
+ />
+ <Rows
+ rows={[
+ { label: "Paused since", value: formatDateTime(now) },
+ ...(domains.length > 0
+ ? [{ label: "Sites affected", value: hidden > 0 ? `${listed} and ${hidden} more` : listed }]
+ : []),
+ { label: "Resumes", value: `${shortDate(reset)}, or as soon as you upgrade`, strong: true },
+ ]}
+ />
+ <P top={24}>Your dashboards and existing data are still available.</P>
+ <PrimaryButton label="Upgrade and resume tracking" href={`${appUrl()}/settings/billing`} />
+ <Note>Questions? Just reply.</Note>
+ </LedgerLayout>
);
};
diff --git a/server/src/lib/email/templates/OtpEmail.tsx b/server/src/lib/email/templates/OtpEmail.tsx
index 94cb53070..1602eb5f1 100644
--- a/server/src/lib/email/templates/OtpEmail.tsx
+++ b/server/src/lib/email/templates/OtpEmail.tsx
@@ -1,105 +1,61 @@
-import {
- Body,
- Container,
- Head,
- Hr,
- Html,
- Img,
- Preview,
- Section,
- Text,
- Tailwind,
- pixelBasedPreset,
-} from "@react-email/components";
import * as React from "react";
+import { appUrl } from "../format.js";
+import { CodeBox, H1, HELP_URL, LedgerLayout, Note, P, Rows } from "./ledger.js";
export type OtpEmailType = "sign-in" | "email-verification" | "forget-password" | "change-email";
+// Better Auth's email OTP default lifetime; auth.ts doesn't override it.
+export const OTP_EXPIRES_MINUTES = 5;
+
interface OtpEmailProps {
otp: string;
type: OtpEmailType;
+ email: string;
}
-const getContent = (type: OtpEmailType) => {
- switch (type) {
- case "sign-in":
- return {
- preview: "Your Rybbit sign-in code",
- description: "Here is your one-time password to sign in to Rybbit:",
- };
- case "email-verification":
- return {
- preview: "Verify your email address",
- description: "Here is your verification code for Rybbit:",
- };
- case "forget-password":
- return {
- preview: "Reset your password",
- description: "You requested to reset your password for Rybbit. Here is your one-time password:",
- };
- case "change-email":
- return {
- preview: "Change your email address",
- description: "Here is your verification code for Rybbit:",
- };
- }
+export const OTP_COPY: Record<OtpEmailType, { subject: string; heading: string; lead: string }> = {
+ "sign-in": {
+ subject: "Your Rybbit sign-in code",
+ heading: "Sign in to Rybbit",
+ lead: "Use this code to sign in.",
+ },
+ "email-verification": {
+ subject: "Your Rybbit verification code",
+ heading: "Verify your email",
+ lead: "Use this code to verify your email address.",
+ },
+ "forget-password": {
+ subject: "Your Rybbit password reset code",
+ heading: "Reset your password",
+ lead: "Use this code to set a new password.",
+ },
+ "change-email": {
+ subject: "Your Rybbit email change code",
+ heading: "Change your email",
+ lead: "Use this code to confirm your new email address.",
+ },
};
-export const OtpEmail = ({ otp, type }: OtpEmailProps) => {
- const currentYear = new Date().getFullYear();
- const content = getContent(type);
-
+export const OtpEmail = ({ otp, type, email }: OtpEmailProps) => {
+ const copy = OTP_COPY[type];
return (
- <Html>
- <Head />
- <Preview>{content?.preview}</Preview>
- <Tailwind
- config={{
- presets: [pixelBasedPreset],
- theme: {
- extend: {
- colors: {
- brand: "#10b981",
- cardBg: "#f9fafb",
- darkText: "#111827",
- mutedText: "#6b7280",
- borderColor: "#e5e7eb",
- },
- },
- },
- }}
- >
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-8 px-6 max-w-[600px]">
- <Img
- src="https://app.rybbit.io/rybbit/horizontal_black.svg"
- alt="Rybbit"
- width="120"
- height="28"
- className="mb-8"
- />
-
- <Text className="text-darkText text-base leading-relaxed mb-4">Hi there,</Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">{content?.description}</Text>
-
- <Section className="text-center mb-6">
- <div className="bg-cardBg py-5 px-6 rounded-md inline-block">
- <Text className="text-brand text-3xl font-bold tracking-widest m-0">{otp}</Text>
- </div>
- </Section>
-
- <Text className="text-mutedText text-sm leading-relaxed mb-2">This code will expire in 5 minutes.</Text>
- <Text className="text-mutedText text-sm leading-relaxed">
- If you didn't request this code, you can safely ignore this email.
- </Text>
-
- <Hr className="border-borderColor my-8" />
-
- <Text className="text-mutedText text-xs">Β© {currentYear} Rybbit Analytics</Text>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ <LedgerLayout
+ preview={`Your code is ${otp}. It expires in ${OTP_EXPIRES_MINUTES} minutes.`}
+ footer={[
+ { label: "Help", href: HELP_URL },
+ { label: "Account settings", href: `${appUrl()}/settings/account` },
+ ]}
+ >
+ <H1>{copy.heading}</H1>
+ <P>{copy.lead}</P>
+ <CodeBox code={otp} />
+ <Rows
+ rows={[
+ { label: "Account", value: email },
+ { label: "Expires", value: `In ${OTP_EXPIRES_MINUTES} minutes`, strong: true },
+ ]}
+ />
+ <Note>If you didn't request this, you can ignore this email.</Note>
+ </LedgerLayout>
);
};
diff --git a/server/src/lib/email/templates/SiteTransferEmail.tsx b/server/src/lib/email/templates/SiteTransferEmail.tsx
index fe8edac8c..75dcb8f81 100644
--- a/server/src/lib/email/templates/SiteTransferEmail.tsx
+++ b/server/src/lib/email/templates/SiteTransferEmail.tsx
@@ -1,95 +1,54 @@
-import {
- Body,
- Container,
- Head,
- Hr,
- Html,
- Img,
- Link,
- Preview,
- Text,
- Tailwind,
- pixelBasedPreset,
-} from "@react-email/components";
+import { DateTime } from "luxon";
import * as React from "react";
+import { formatDate } from "../format.js";
+import { H1, HELP_URL, LedgerLayout, Note, P, PrimaryButton, Rows } from "./ledger.js";
-interface SiteTransferEmailProps {
+export interface SiteTransferEmailProps {
email: string;
+ /** Who sent it, as shown in the subject and heading: a name, or an email when there's no name. */
sentBy: string;
+ sentByEmail: string | null;
siteDomain: string;
organizationName: string;
+ expiresAt: string;
transferLink: string;
}
export const SiteTransferEmail = ({
- email,
sentBy,
+ sentByEmail,
siteDomain,
organizationName,
+ expiresAt,
transferLink,
}: SiteTransferEmailProps) => {
- const currentYear = new Date().getFullYear();
-
+ const expires = formatDate(DateTime.fromISO(expiresAt));
return (
- <Html>
- <Head />
- <Preview>
- {sentBy} wants to hand {siteDomain} over to you on Rybbit
- </Preview>
- <Tailwind
- config={{
- presets: [pixelBasedPreset],
- theme: {
- extend: {
- colors: {
- brand: "#10b981",
- darkText: "#111827",
- mutedText: "#6b7280",
- borderColor: "#e5e7eb",
- },
- },
+ <LedgerLayout
+ preview={`The site moves to you with all its data. The offer expires ${expires}.`}
+ footer={[{ label: "Help", href: HELP_URL }]}
+ >
+ <H1>
+ {sentBy} wants to transfer {siteDomain} to you
+ </H1>
+ <P>If you accept, the site moves to an organization you manage, with all its data and settings.</P>
+ <Rows
+ top={24}
+ rows={[
+ { label: "Site", value: siteDomain, strong: true },
+ ...(organizationName ? [{ label: "From", value: organizationName }] : []),
+ {
+ label: "Sent by",
+ value: sentByEmail && sentByEmail !== sentBy ? `${sentBy} (${sentByEmail})` : sentBy,
},
- }}
- >
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-8 px-6 max-w-[600px]">
- <Img
- src="https://app.rybbit.io/rybbit/horizontal_black.svg"
- alt="Rybbit"
- width="120"
- height="28"
- className="mb-8"
- />
-
- <Text className="text-darkText text-base leading-relaxed mb-4">Hi there,</Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- {sentBy} wants to transfer the analytics for <span className="font-semibold">{siteDomain}</span>
- {organizationName ? ` from ${organizationName}` : ""} to you on Rybbit Analytics.
- </Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- Accepting moves the site, with all of its data and settings, into an organization you manage. You'll need
- a Rybbit account with this email address; you can create one from the link.
- </Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- <Link href={transferLink} className="text-brand underline">
- Review the transfer
- </Link>
- </Text>
-
- <Text className="text-mutedText text-sm leading-relaxed">
- This transfer was sent to {email} and expires in 7 days. If you weren't expecting it, you can ignore this
- email.
- </Text>
-
- <Hr className="border-borderColor my-8" />
-
- <Text className="text-mutedText text-xs">Β© {currentYear} Rybbit Analytics</Text>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ { label: "Expires", value: expires },
+ ]}
+ />
+ <PrimaryButton label="Review the transfer" href={transferLink} />
+ <Note>
+ You'll need a Rybbit account with this email address to accept. If you weren't expecting this, you can ignore
+ it.
+ </Note>
+ </LedgerLayout>
);
};
diff --git a/server/src/lib/email/templates/VerifyEmailEmail.tsx b/server/src/lib/email/templates/VerifyEmailEmail.tsx
new file mode 100644
index 000000000..ae13ccf2d
--- /dev/null
+++ b/server/src/lib/email/templates/VerifyEmailEmail.tsx
@@ -0,0 +1,30 @@
+import * as React from "react";
+import { H1, HELP_URL, LedgerLayout, Note, P, PrimaryButton, Rows, UrlFallback } from "./ledger.js";
+
+interface VerifyEmailEmailProps {
+ email: string;
+ verificationUrl: string;
+}
+
+/**
+ * Confirms an address: a new account's, or the new address at the end of an
+ * email change. Better Auth's verification token lasts an hour by default.
+ */
+export const VerifyEmailEmail = ({ email, verificationUrl }: VerifyEmailEmailProps) => (
+ <LedgerLayout
+ preview={`Confirm ${email} to continue. The link expires in 1 hour.`}
+ footer={[{ label: "Help", href: HELP_URL }]}
+ >
+ <H1>Verify your email</H1>
+ <P>Click the button to confirm {email} is your email address.</P>
+ <PrimaryButton top={24} label="Verify email" href={verificationUrl} />
+ <Rows
+ rows={[
+ { label: "Email", value: email },
+ { label: "Link expires", value: "In 1 hour", strong: true },
+ ]}
+ />
+ <UrlFallback url={verificationUrl} />
+ <Note>If you didn't request this, you can ignore this email.</Note>
+ </LedgerLayout>
+);
diff --git a/server/src/lib/email/templates/WeeklyReportEmail.tsx b/server/src/lib/email/templates/WeeklyReportEmail.tsx
index ae3900ce8..11ee931f9 100644
--- a/server/src/lib/email/templates/WeeklyReportEmail.tsx
+++ b/server/src/lib/email/templates/WeeklyReportEmail.tsx
@@ -1,410 +1,382 @@
-import {
- Body,
- Container,
- Head,
- Hr,
- Html,
- Img,
- Link,
- Preview,
- Section,
- Tailwind,
- Text,
- pixelBasedPreset,
-} from "@react-email/components";
+import { DateTime } from "luxon";
import * as React from "react";
-import type { SiteReport, MetricData } from "../../../services/weekyReports/weeklyReportTypes.js";
+import type { DailySessions, MetricData, SiteReport } from "../../../services/weekyReports/weeklyReportTypes.js";
+import { appUrl, formatChange, formatCount, formatDuration, percentChange, truncate } from "../format.js";
+import {
+ color,
+ H1,
+ H2,
+ LedgerLayout,
+ Note,
+ PrimaryButton,
+ ShareTable,
+ StatGrid,
+ tableAttrs,
+ type Stat,
+} from "./ledger.js";
interface WeeklyReportEmailProps {
- userName: string;
- organizationName: string;
site: SiteReport;
+ unsubscribeUrl: string;
}
-interface MetricCardProps {
- label: string;
- currentValue: string;
- growth: string;
- isPositive: boolean;
-}
-
-interface TopListItemProps {
- value: string;
- percentage: number | null;
- count: number;
- barWidth: number;
- isLast: boolean;
- favicon?: string;
- labelClassName?: string;
-}
-
-interface TopListSectionProps {
- title: string;
- items: MetricData[];
- renderLabel: (item: MetricData) => React.ReactNode;
- showFavicon?: boolean;
- labelClassName?: string;
- className?: string;
-}
+const CHART_HEIGHT = 112;
+const ROWS_PER_TABLE = 5;
-const calculateGrowth = (current: number | null | undefined, previous: number | null | undefined): string => {
- const curr = current ?? 0;
- const prev = previous ?? 0;
+const regionNames = new Intl.DisplayNames(["en"], { type: "region" });
- if (prev === 0) {
- return curr > 0 ? "+100%" : "0%";
+const countryName = (code: string) => {
+ try {
+ return regionNames.of(code.toUpperCase()) ?? code;
+ } catch {
+ return code;
}
- const growth = ((curr - prev) / prev) * 100;
- const sign = growth > 0 ? "+" : "";
- return `${sign}${growth.toFixed(1)}%`;
};
-const formatDuration = (seconds: number): string => {
- if (seconds < 60) {
- return `${Math.round(seconds)}s`;
- }
- const minutes = Math.floor(seconds / 60);
- const remainingSeconds = Math.round(seconds % 60);
- return `${minutes}m ${remainingSeconds}s`;
+const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+
+const day = (iso: string) => DateTime.fromISO(iso, { zone: "utc" });
+
+/** "Oct 13–19", or "Sep 29–Oct 5" across a month boundary. */
+export const formatWeekRange = (startIso: string, endIso: string) => {
+ const start = day(startIso);
+ const end = day(endIso);
+ return start.month === end.month
+ ? `${start.toFormat("LLL d")}–${end.toFormat("d")}`
+ : `${start.toFormat("LLL d")}–${end.toFormat("LLL d")}`;
};
-const formatNumber = (num: number | null | undefined): string => {
- if (num == null || isNaN(num)) {
- return "0";
- }
- if (num >= 1000000) {
- return `${(num / 1000000).toFixed(1)}M`;
- }
- if (num >= 1000) {
- return `${(num / 1000).toFixed(1)}K`;
- }
- return num.toFixed(0);
+const previousRange = (site: SiteReport) =>
+ formatWeekRange(
+ day(site.weekStart).minus({ days: 7 }).toISODate()!,
+ day(site.weekEnd).minus({ days: 7 }).toISODate()!
+ );
+
+const visitorChange = (site: SiteReport) => percentChange(site.currentWeek.users, site.previousWeek.users);
+
+/** "up 9.8%", "down 3.1%", "flat", or null when last week had no visitors. */
+const changeWords = (change: number | null) => {
+ if (change === null) return null;
+ const rounded = Math.round(change * 10) / 10;
+ if (rounded === 0) return "flat";
+ return `${rounded > 0 ? "up" : "down"} ${Math.abs(rounded).toFixed(1)}%`;
};
-const safeToFixed = (num: number | null | undefined, decimals: number = 1): string => {
- if (num == null || isNaN(num)) {
- return "0";
- }
- return num.toFixed(decimals);
+const visitorsPhrase = (n: number) => `${formatCount(n)} ${n === 1 ? "visitor" : "visitors"}`;
+
+export const weeklyReportSubject = (site: SiteReport) => {
+ const words = changeWords(visitorChange(site));
+ return `${site.siteDomain}: ${visitorsPhrase(site.currentWeek.users)} last week${words && words !== "flat" ? `, ${words}` : ""}`;
};
-const regionNamesInEnglish = new Intl.DisplayNames(["en"], { type: "region" });
+const busiestDay = (daily: DailySessions[]) =>
+ daily.reduce<DailySessions | null>((best, d) => (d.sessions > (best?.sessions ?? 0) ? d : best), null);
-const getCountryFlag = (countryCode: string): string => {
- if (!countryCode || countryCode.length !== 2) return "";
- const codePoints = countryCode
- .toUpperCase()
- .split("")
- .map(char => 127397 + char.charCodeAt(0));
- return String.fromCodePoint(...codePoints);
+export const weeklyReportPreview = (site: SiteReport) => {
+ const busiest = busiestDay(site.daily);
+ return [
+ busiest && `Busiest day ${day(busiest.date).toFormat("cccc")}, ${formatCount(busiest.sessions)} sessions`,
+ site.topReferrers[0] && `Top source ${site.topReferrers[0].value}`,
+ formatWeekRange(site.weekStart, site.weekEnd),
+ ]
+ .filter(Boolean)
+ .join(" Β· ");
};
-const getCountryDisplay = (countryCode: string): string => {
- try {
- const flag = getCountryFlag(countryCode);
- const name = regionNamesInEnglish.of(countryCode.toUpperCase()) || countryCode;
- return `${flag} ${name}`;
- } catch (error) {
- return countryCode;
- }
+/** "+9.8% from 5,560"; green when the move is good for the site, red when it isn't. */
+const Change = ({
+ current,
+ previous,
+ format,
+ lowerIsBetter = false,
+ points = false,
+}: {
+ current: number | null;
+ previous: number | null;
+ format: (n: number) => string;
+ lowerIsBetter?: boolean;
+ points?: boolean;
+}) => {
+ const prev = previous ?? 0;
+ const curr = current ?? 0;
+ const change = points ? (prev > 0 ? curr - prev : null) : percentChange(curr, prev);
+ if (change === null) return <>from {format(prev)}</>;
+ const rounded = Math.round(change * 10) / 10;
+ const good = lowerIsBetter ? rounded < 0 : rounded > 0;
+ const label = points
+ ? rounded === 0
+ ? "0 pp"
+ : `${rounded > 0 ? "+" : "βˆ’"}${Math.abs(rounded).toFixed(1)} pp`
+ : formatChange(change);
+ return (
+ <>
+ <span style={{ fontWeight: 500, color: rounded === 0 ? color.muted : good ? color.up : color.down }}>
+ {label}
+ </span>{" "}
+ from {format(prev)}
+ </>
+ );
+};
+
+const percent = (n: number | null) => `${(n ?? 0).toFixed(1)}%`;
+const oneDecimal = (n: number | null) => (n ?? 0).toFixed(1);
+
+const stats = (site: SiteReport): Stat[] => {
+ const { currentWeek: c, previousWeek: p } = site;
+ return [
+ {
+ label: "Visitors",
+ value: formatCount(c.users),
+ change: <Change current={c.users} previous={p.users} format={formatCount} />,
+ },
+ {
+ label: "Sessions",
+ value: formatCount(c.sessions),
+ change: <Change current={c.sessions} previous={p.sessions} format={formatCount} />,
+ },
+ {
+ label: "Pageviews",
+ value: formatCount(c.pageviews),
+ change: <Change current={c.pageviews} previous={p.pageviews} format={formatCount} />,
+ },
+ {
+ label: "Pages per session",
+ value: oneDecimal(c.pages_per_session),
+ change: <Change current={c.pages_per_session} previous={p.pages_per_session} format={oneDecimal} />,
+ },
+ {
+ label: "Avg. session",
+ value: formatDuration(c.session_duration),
+ change: <Change current={c.session_duration} previous={p.session_duration} format={formatDuration} />,
+ },
+ {
+ label: "Bounce rate",
+ value: percent(c.bounce_rate),
+ change: <Change current={c.bounce_rate} previous={p.bounce_rate} format={percent} lowerIsBetter points />,
+ },
+ ];
};
-const MetricCard = ({ label, currentValue, growth, isPositive }: MetricCardProps) => (
- <div
+const LegendSwatch = ({ fill, outline }: { fill: string; outline?: string }) => (
+ <span
style={{
- backgroundColor: "#f9fafb",
- border: "1px solid #e5e7eb",
- borderRadius: "8px",
- padding: "16px",
+ display: "inline-block",
+ width: 10,
+ height: 10,
+ borderRadius: 2,
+ backgroundColor: fill,
+ border: outline ? `1px solid ${outline}` : undefined,
+ boxSizing: "border-box",
+ verticalAlign: "-1px",
+ marginRight: 6,
}}
- >
- <Text style={{ color: "#6b7280", fontSize: "12px", marginBottom: "4px", marginTop: 0 }}>{label}</Text>
- <div>
- <span style={{ color: "#111827", fontSize: "24px", fontWeight: "bold", lineHeight: "1", marginRight: "8px" }}>
- {currentValue}
- </span>
- <span
- style={{
- color: isPositive ? "#10b981" : "#ef4444",
- fontSize: "12px",
- fontWeight: 500,
- lineHeight: "1",
- verticalAlign: "baseline",
- }}
- >
- {growth}
- </span>
- </div>
- </div>
+ />
);
-const TopListItem = ({ value, percentage, count, barWidth, isLast, favicon, labelClassName }: TopListItemProps) => {
- const barStyle: React.CSSProperties = {
- background: `linear-gradient(to right, rgba(16, 185, 129, 0.25) 0%, rgba(16, 185, 129, 0.25) ${barWidth}%, transparent ${barWidth}%, transparent 100%)`,
- borderRadius: "6px",
- };
+/** A solid bar drawn as a table cell, which Outlook sizes where it ignores div heights. */
+const Bar = ({ width, height, fill }: { width: number; height: number; fill: string }) => (
+ <table {...tableAttrs} width={width} style={{ width }}>
+ <tbody>
+ <tr>
+ <td
+ height={height}
+ style={{ height, width, backgroundColor: fill, borderRadius: "2px 2px 0 0", fontSize: 0, lineHeight: "0px" }}
+ >
+ &nbsp;
+ </td>
+ </tr>
+ </tbody>
+ </table>
+);
+
+const DailyChart = ({ site }: { site: SiteReport }) => {
+ const max = Math.max(1, ...site.daily.flatMap(d => [d.sessions, d.previousSessions]));
+ const busiest = busiestDay(site.daily);
+ const scale = (n: number) => (n > 0 ? Math.max(2, Math.round((n / max) * CHART_HEIGHT)) : 0);
+ const label = (d: DailySessions) => ({
+ fontSize: 11,
+ lineHeight: "14px",
+ fontWeight: d === busiest ? 600 : 400,
+ color: d === busiest ? color.text : color.muted,
+ });
return (
- <table
- style={{
- width: "100%",
- marginBottom: isLast ? "0" : "8px",
- borderCollapse: "separate",
- borderSpacing: "0",
- ...barStyle,
- }}
- >
- <tbody>
- <tr>
- <td style={{ padding: "4px 8px", verticalAlign: "middle" }}>
- {favicon ? (
- <table style={{ width: "100%", borderCollapse: "collapse" }}>
- <tbody>
- <tr>
- <td style={{ width: "16px", paddingRight: "4px", verticalAlign: "middle" }}>
- <img src={favicon} alt="" width="16" height="16" style={{ display: "block" }} />
- </td>
- <td style={{ verticalAlign: "middle" }}>
- <Text
- style={{
- color: "#111827",
- fontSize: "14px",
- margin: 0,
- lineHeight: "1.2",
- overflow: "hidden",
- textOverflow: "ellipsis",
- whiteSpace: "nowrap",
- }}
- >
- {value}
- </Text>
- </td>
- </tr>
- </tbody>
- </table>
- ) : (
- <Text style={{ color: "#111827", fontSize: "14px", margin: 0, lineHeight: "1.2" }}>{value}</Text>
- )}
- </td>
- <td style={{ padding: "8px", textAlign: "right", verticalAlign: "middle", whiteSpace: "nowrap" }}>
- <Text style={{ color: "#6b7280", fontSize: "12px", margin: 0, marginRight: "12px", lineHeight: "1.2" }}>
- {safeToFixed(percentage, 1)}%
- </Text>
- </td>
- <td
- style={{ padding: "8px", textAlign: "right", verticalAlign: "middle", whiteSpace: "nowrap", width: "40px" }}
- >
- <Text style={{ color: "#111827", fontSize: "14px", fontWeight: 500, margin: 0, lineHeight: "1.2" }}>
- {formatNumber(count)}
- </Text>
- </td>
- </tr>
- </tbody>
- </table>
+ <>
+ <table {...tableAttrs} width="100%" style={{ marginTop: 40 }}>
+ <tbody>
+ <tr>
+ <td>
+ <H2 top={0}>Sessions by day</H2>
+ </td>
+ <td align="right" style={{ fontSize: 12, lineHeight: "16px", color: color.muted, whiteSpace: "nowrap" }}>
+ <LegendSwatch fill={color.data} />
+ {formatWeekRange(site.weekStart, site.weekEnd)}
+ <span style={{ paddingLeft: 16 }} />
+ <LegendSwatch fill={color.previous} />
+ {previousRange(site)}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <table {...tableAttrs} width="100%" style={{ marginTop: 16, tableLayout: "fixed" }}>
+ <tbody>
+ <tr>
+ {site.daily.map(d => (
+ <td key={d.date} align="center" style={label(d)}>
+ {formatCount(d.sessions)}
+ </td>
+ ))}
+ </tr>
+ <tr>
+ {site.daily.map(d => (
+ <td
+ key={d.date}
+ align="center"
+ valign="bottom"
+ height={CHART_HEIGHT + 6}
+ style={{
+ height: CHART_HEIGHT + 6,
+ verticalAlign: "bottom",
+ borderBottom: `1px solid ${color.axis}`,
+ }}
+ >
+ <table {...tableAttrs} align="center">
+ <tbody>
+ <tr>
+ <td valign="bottom" style={{ verticalAlign: "bottom", paddingRight: 3 }}>
+ {scale(d.previousSessions) > 0 && (
+ <Bar width={12} height={scale(d.previousSessions)} fill={color.previous} />
+ )}
+ </td>
+ <td valign="bottom" style={{ verticalAlign: "bottom" }}>
+ {scale(d.sessions) > 0 && <Bar width={24} height={scale(d.sessions)} fill={color.data} />}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </td>
+ ))}
+ </tr>
+ <tr>
+ {site.daily.map(d => (
+ <td key={d.date} align="center" style={{ ...label(d), paddingTop: 8 }}>
+ {day(d.date).toFormat("ccc d")}
+ </td>
+ ))}
+ </tr>
+ </tbody>
+ </table>
+ </>
);
};
-const TopListSection = ({ title, items, renderLabel, showFavicon, labelClassName, className }: TopListSectionProps) => {
+const Breakdown = ({
+ title,
+ labelHeader,
+ items,
+ labelFor,
+}: {
+ title: string;
+ labelHeader: string;
+ items: MetricData[];
+ labelFor: (item: MetricData) => string;
+}) => {
if (items.length === 0) return null;
-
- const ratio = items[0]?.percentage ? 100 / items[0].percentage : 1;
-
+ const rows = items.slice(0, ROWS_PER_TABLE);
+ const largest = rows[0]?.count || 1;
return (
- <div
- style={{
- backgroundColor: "#f9fafb",
- border: "1px solid #e5e7eb",
- borderRadius: "8px",
- padding: "16px",
- marginBottom: "16px",
- }}
- >
- <Text style={{ color: "#111827", fontSize: "14px", fontWeight: 600, marginBottom: "12px", marginTop: 0 }}>
- {title}
- </Text>
- {items.map((item, index) => {
- const barWidth = (item.percentage ?? 0) * ratio;
- const favicon = showFavicon ? `https://www.google.com/s2/favicons?domain=${item.value}&sz=16` : undefined;
-
- return (
- <TopListItem
- key={index}
- value={typeof renderLabel(item) === "string" ? (renderLabel(item) as string) : item.value}
- percentage={item.percentage}
- count={item.count}
- barWidth={barWidth}
- isLast={index === items.length - 1}
- favicon={favicon}
- labelClassName={labelClassName}
- />
- );
- })}
- </div>
+ <>
+ <H2>{title}</H2>
+ <ShareTable
+ labelHeader={labelHeader}
+ valueHeader="Sessions"
+ rows={rows.map(item => ({
+ label: labelFor(item),
+ value: formatCount(item.count),
+ share: item.percentage,
+ bar: (item.count / largest) * 100,
+ }))}
+ />
+ </>
);
};
-export const WeeklyReportEmail = ({ userName, organizationName, site }: WeeklyReportEmailProps) => {
- const currentYear = new Date().getFullYear();
+const DEVICE_FILLS = [color.data, color.dataMid, color.dataLight];
+const Devices = ({ items }: { items: MetricData[] }) => {
+ const devices = items.filter(item => (item.percentage ?? 0) > 0).slice(0, 3);
+ if (devices.length === 0) return null;
+ const total = devices.reduce((sum, d) => sum + (d.percentage ?? 0), 0);
return (
- <Html>
- <Head />
- <Preview>Weekly Analytics Report for {organizationName}</Preview>
- <Tailwind
- config={{
- presets: [pixelBasedPreset],
- theme: {
- extend: {
- colors: {
- brand: "#10b981",
- cardBg: "#f9fafb",
- darkText: "#111827",
- mutedText: "#6b7280",
- borderColor: "#e5e7eb",
- positive: "#10b981",
- negative: "#ef4444",
- },
- },
- },
- }}
- >
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-8 px-6 max-w-[600px]">
- <Img
- src="https://app.rybbit.io/rybbit/horizontal_black.svg"
- alt="Rybbit"
- width="120"
- height="28"
- className="mb-8"
- />
-
- <Text className="text-darkText text-base leading-relaxed mb-4">Hi {userName},</Text>
-
- <Text className="text-darkText text-base leading-relaxed mb-8">
- Here's your weekly analytics summary for{" "}
- <span className="font-semibold">{site.siteDomain}</span>.
- </Text>
-
- <Section className="mb-10">
- {/* Metrics Cards */}
- <table style={{ width: "100%", marginBottom: "24px" }}>
- <tbody>
- <tr>
- <td style={{ width: "50%", paddingRight: "6px", paddingBottom: "12px" }}>
- <MetricCard
- label="Sessions"
- currentValue={formatNumber(site.currentWeek.sessions)}
- growth={calculateGrowth(site.currentWeek.sessions, site.previousWeek.sessions)}
- isPositive={site.currentWeek.sessions >= site.previousWeek.sessions}
- />
- </td>
- <td style={{ width: "50%", paddingLeft: "6px", paddingBottom: "12px" }}>
- <MetricCard
- label="Pageviews"
- currentValue={formatNumber(site.currentWeek.pageviews)}
- growth={calculateGrowth(site.currentWeek.pageviews, site.previousWeek.pageviews)}
- isPositive={site.currentWeek.pageviews >= site.previousWeek.pageviews}
- />
- </td>
- </tr>
- <tr>
- <td style={{ width: "50%", paddingRight: "6px", paddingBottom: "12px" }}>
- <MetricCard
- label="Unique Users"
- currentValue={formatNumber(site.currentWeek.users)}
- growth={calculateGrowth(site.currentWeek.users, site.previousWeek.users)}
- isPositive={site.currentWeek.users >= site.previousWeek.users}
- />
- </td>
- <td style={{ width: "50%", paddingLeft: "6px", paddingBottom: "12px" }}>
- <MetricCard
- label="Avg Duration"
- currentValue={formatDuration(site.currentWeek.session_duration)}
- growth={calculateGrowth(
- site.currentWeek.session_duration,
- site.previousWeek.session_duration
- )}
- isPositive={site.currentWeek.session_duration >= site.previousWeek.session_duration}
- />
- </td>
- </tr>
- <tr>
- <td style={{ width: "50%", paddingRight: "6px" }}>
- <MetricCard
- label="Pages/Session"
- currentValue={safeToFixed(site.currentWeek.pages_per_session, 1)}
- growth={calculateGrowth(
- site.currentWeek.pages_per_session,
- site.previousWeek.pages_per_session
- )}
- isPositive={
- (site.currentWeek.pages_per_session ?? 0) >= (site.previousWeek.pages_per_session ?? 0)
- }
- />
- </td>
- <td style={{ width: "50%", paddingLeft: "6px" }}>
- <MetricCard
- label="Bounce Rate"
- currentValue={`${safeToFixed(site.currentWeek.bounce_rate, 1)}%`}
- growth={calculateGrowth(site.currentWeek.bounce_rate, site.previousWeek.bounce_rate)}
- isPositive={(site.currentWeek.bounce_rate ?? 0) <= (site.previousWeek.bounce_rate ?? 0)}
- />
- </td>
- </tr>
- </tbody>
- </table>
-
- {/* Top Lists Section */}
- <div className="mb-6">
- <TopListSection
- title="Top Countries"
- items={site.topCountries}
- renderLabel={item => getCountryDisplay(item.value)}
- />
- <TopListSection
- title="Top Pages"
- items={site.topPages}
- renderLabel={item => item.value}
- labelClassName="text-darkText text-sm m-0 truncate max-w-[280px]"
- />
- <TopListSection
- title="Top Referrers"
- items={site.topReferrers}
- renderLabel={item => item.value}
- showFavicon={true}
- labelClassName="text-darkText text-sm m-0 truncate"
- />
- <TopListSection
- title="Device Breakdown"
- items={site.deviceBreakdown}
- renderLabel={item => item.value}
- labelClassName="text-darkText text-sm m-0 capitalize"
- className="bg-cardBg border border-borderColor rounded-lg p-4"
- />
- </div>
-
- <Text className="text-darkText text-base leading-relaxed mb-4">
- <Link href={`https://app.rybbit.io/${site.siteId}`} className="text-brand underline">
- View full dashboard
- </Link>
- </Text>
- </Section>
-
- <Text className="text-mutedText text-sm leading-relaxed">
- This report covers the last 7 days of analytics data.
- </Text>
-
- <Hr className="border-borderColor my-8" />
+ <>
+ <H2>Devices</H2>
+ <table {...tableAttrs} width="100%" style={{ marginTop: 14, borderCollapse: "separate" }}>
+ <tbody>
+ <tr>
+ {devices.map((d, i) => (
+ <td
+ key={d.value}
+ width={`${Math.max(1, Math.round(((d.percentage ?? 0) / total) * 100))}%`}
+ style={{
+ height: 10,
+ lineHeight: "10px",
+ fontSize: 0,
+ backgroundColor: DEVICE_FILLS[i],
+ borderLeft: i > 0 ? `2px solid ${color.page}` : undefined,
+ }}
+ >
+ &nbsp;
+ </td>
+ ))}
+ </tr>
+ </tbody>
+ </table>
+ <p style={{ margin: "10px 0 0", fontSize: 13, lineHeight: "20px", color: color.body }}>
+ {devices.map((d, i) => (
+ <span key={d.value} style={{ paddingRight: 24, whiteSpace: "nowrap" }}>
+ <LegendSwatch fill={DEVICE_FILLS[i]} outline={i === 2 ? color.dataMid : undefined} />
+ {capitalize(d.value)} <span style={{ fontWeight: 600 }}>{(d.percentage ?? 0).toFixed(1)}%</span>
+ </span>
+ ))}
+ </p>
+ </>
+ );
+};
- <Text className="text-mutedText text-xs mb-2">
- <Link href="https://app.rybbit.io/settings/account" className="text-mutedText underline">
- Unsubscribe from weekly reports
- </Link>
- </Text>
- <Text className="text-mutedText text-xs">Β© {currentYear} Rybbit Analytics</Text>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+export const WeeklyReportEmail = ({ site, unsubscribeUrl }: WeeklyReportEmailProps) => {
+ const words = changeWords(visitorChange(site));
+ return (
+ <LedgerLayout
+ preview={weeklyReportPreview(site)}
+ footer={[
+ { label: "Turn off weekly reports", href: unsubscribeUrl },
+ { label: "Account settings", href: `${appUrl()}/settings/account` },
+ ]}
+ >
+ <H1>
+ {site.siteDomain} had {visitorsPhrase(site.currentWeek.users)} last week
+ {words === "flat" ? ", the same as the week before" : words ? `, ${words}` : ""}.
+ </H1>
+ <Note top={8}>
+ {formatWeekRange(site.weekStart, site.weekEnd)}, compared with {previousRange(site)}
+ </Note>
+ <StatGrid stats={stats(site)} />
+ {site.daily.length > 0 && <DailyChart site={site} />}
+ <Breakdown title="Top pages" labelHeader="Page" items={site.topPages} labelFor={item => truncate(item.value)} />
+ <Breakdown
+ title="Top sources"
+ labelHeader="Referrer"
+ items={site.topReferrers}
+ labelFor={item => truncate(item.value)}
+ />
+ <Breakdown
+ title="Countries"
+ labelHeader="Country"
+ items={site.topCountries}
+ labelFor={item => countryName(item.value)}
+ />
+ <Devices items={site.deviceBreakdown} />
+ <PrimaryButton top={40} label={`Open ${site.siteDomain} in Rybbit`} href={`${appUrl()}/${site.siteId}`} />
+ </LedgerLayout>
);
};
diff --git a/server/src/lib/email/templates/ledger.tsx b/server/src/lib/email/templates/ledger.tsx
new file mode 100644
index 000000000..a79b4f399
--- /dev/null
+++ b/server/src/lib/email/templates/ledger.tsx
@@ -0,0 +1,669 @@
+import { Body, Button, Head, Html, Img, Link, Preview } from "@react-email/components";
+import * as React from "react";
+
+/**
+ * Ledger: the shared look of every Rybbit email. A white page, a 560px column,
+ * a sentence heading, facts as hairline label/value rows and one emerald
+ * button. Layout is table-based and every style is inline, because Gmail and
+ * Outlook drop flexbox, grid and most of <head>.
+ */
+
+export const color = {
+ page: "#ffffff",
+ text: "#0a0a0a",
+ body: "#262626",
+ muted: "#666666",
+ rule: "#e6e6e6",
+ ruleSoft: "#efefef",
+ fill: "#fafafa",
+ track: "#f0f0f0",
+ data: "#99aaff",
+ dataMid: "#c2caff",
+ dataLight: "#e3e7ff",
+ previous: "#dedede",
+ axis: "#d4d4d4",
+ up: "#047857",
+ down: "#b91c1c",
+ action: "#047857",
+ warning: "#eab308",
+ danger: "#dc2626",
+ dangerText: "#b91c1c",
+ dangerFill: "#fee2e2",
+ linkUnderline: "#bdbdbd",
+};
+
+export const fontFamily = "Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";
+export const monoFamily = "ui-monospace,SFMono-Regular,Menlo,Consolas,'Liberation Mono',monospace";
+
+// A PNG, not the SVG logo: Gmail and Outlook don't render SVG images.
+const LOGO_URL = "https://app.rybbit.io/rybbit/email-logo.png";
+
+export const HELP_URL = "https://rybbit.com/docs";
+
+// Phones get a narrower stat grid and drop the share bars so labels keep their room.
+const responsiveCss = `
+@media only screen and (max-width: 480px) {
+ .ledger-bar { display: none !important; }
+ .ledger-stat { padding: 12px 10px !important; }
+ .ledger-label { width: 112px !important; }
+}
+`;
+
+export interface FooterLink {
+ label: string;
+ href: string;
+}
+
+interface LedgerLayoutProps {
+ preview: string;
+ footer?: FooterLink[];
+ children: React.ReactNode;
+}
+
+const table = { cellPadding: 0, cellSpacing: 0, border: 0, role: "presentation" } as const;
+
+export const LedgerLayout = ({ preview, footer = [], children }: LedgerLayoutProps) => (
+ <Html lang="en">
+ <Head>
+ <meta name="color-scheme" content="light only" />
+ <meta name="supported-color-schemes" content="light" />
+ <style>{responsiveCss}</style>
+ </Head>
+ <Preview>{preview}</Preview>
+ <Body style={{ margin: 0, padding: 0, backgroundColor: color.page }}>
+ <table {...table} width="100%" style={{ backgroundColor: color.page }}>
+ <tbody>
+ <tr>
+ <td align="center" style={{ padding: "0 20px" }}>
+ <table {...table} width="560" style={{ width: "100%", maxWidth: 560 }}>
+ <tbody>
+ <tr>
+ <td
+ style={{
+ padding: "40px 0 48px",
+ fontFamily,
+ color: color.text,
+ textAlign: "left",
+ fontVariantNumeric: "tabular-nums",
+ }}
+ >
+ <Img
+ src={LOGO_URL}
+ alt="Rybbit"
+ width="100"
+ height="20"
+ style={{ display: "block", border: 0 }}
+ />
+ {children}
+ {footer.length > 0 && <Footer links={footer} />}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </Body>
+ </Html>
+);
+
+const Footer = ({ links }: { links: FooterLink[] }) => (
+ <div
+ style={{
+ marginTop: 48,
+ paddingTop: 20,
+ borderTop: `1px solid ${color.rule}`,
+ fontSize: 12,
+ lineHeight: "18px",
+ color: color.muted,
+ }}
+ >
+ <p style={{ margin: 0 }}>
+ {links.map((link, i) => (
+ <React.Fragment key={link.href}>
+ {i > 0 && <span style={{ padding: "0 8px" }}>Β·</span>}
+ <Link href={link.href} style={{ color: color.muted, textDecoration: "underline" }}>
+ {link.label}
+ </Link>
+ </React.Fragment>
+ ))}
+ </p>
+ </div>
+);
+
+export const H1 = ({ children }: { children: React.ReactNode }) => (
+ <h1
+ style={{
+ margin: "36px 0 0",
+ fontSize: 24,
+ lineHeight: "30px",
+ fontWeight: 600,
+ letterSpacing: "-0.015em",
+ color: color.text,
+ }}
+ >
+ {children}
+ </h1>
+);
+
+export const H2 = ({ children, top = 40 }: { children: React.ReactNode; top?: number }) => (
+ <h2
+ style={{
+ margin: `${top}px 0 0`,
+ fontSize: 15,
+ lineHeight: "20px",
+ fontWeight: 600,
+ letterSpacing: "-0.005em",
+ color: color.text,
+ }}
+ >
+ {children}
+ </h2>
+);
+
+export const P = ({ children, top = 12 }: { children: React.ReactNode; top?: number }) => (
+ <p style={{ margin: `${top}px 0 0`, fontSize: 15, lineHeight: "24px", color: color.body }}>{children}</p>
+);
+
+export const Note = ({ children, top = 24 }: { children: React.ReactNode; top?: number }) => (
+ <p style={{ margin: `${top}px 0 0`, fontSize: 13, lineHeight: "20px", color: color.muted }}>{children}</p>
+);
+
+export const Strong = ({ children }: { children: React.ReactNode }) => (
+ <strong style={{ fontWeight: 600, color: color.text }}>{children}</strong>
+);
+
+export const TextLink = ({ href, children }: { href: string; children: React.ReactNode }) => (
+ <Link
+ href={href}
+ style={{ color: color.text, textDecoration: "underline", textDecorationColor: color.linkUnderline }}
+ >
+ {children}
+ </Link>
+);
+
+export interface LedgerRow {
+ label: string;
+ value: React.ReactNode;
+ strong?: boolean;
+}
+
+/** Facts as label/value rows between hairlines. */
+export const Rows = ({ rows, top = 28 }: { rows: LedgerRow[]; top?: number }) => (
+ <div style={{ marginTop: top }}>
+ <table {...table} width="100%" style={{ borderTop: `1px solid ${color.rule}`, borderCollapse: "collapse" }}>
+ <tbody>
+ {rows.map(row => (
+ <tr key={row.label}>
+ <td
+ className="ledger-label"
+ width="144"
+ valign="top"
+ style={{
+ width: 144,
+ padding: "12px 16px 12px 0",
+ borderBottom: `1px solid ${color.rule}`,
+ fontSize: 14,
+ lineHeight: "20px",
+ color: color.muted,
+ verticalAlign: "top",
+ }}
+ >
+ {row.label}
+ </td>
+ <td
+ valign="top"
+ style={{
+ padding: "12px 0",
+ borderBottom: `1px solid ${color.rule}`,
+ fontSize: 14,
+ lineHeight: "20px",
+ color: color.text,
+ fontWeight: row.strong ? 600 : 400,
+ verticalAlign: "top",
+ wordBreak: "break-word",
+ }}
+ >
+ {row.value}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+);
+
+export interface Step {
+ title: string;
+ detail: string;
+}
+
+/** A numbered checklist in the same hairline rows. */
+export const Steps = ({ steps, top = 28 }: { steps: Step[]; top?: number }) => (
+ <div style={{ marginTop: top }}>
+ <table {...table} width="100%" style={{ borderTop: `1px solid ${color.rule}`, borderCollapse: "collapse" }}>
+ <tbody>
+ {steps.map((step, i) => (
+ <tr key={step.title}>
+ <td
+ width="32"
+ valign="top"
+ style={{
+ width: 32,
+ padding: "12px 0",
+ borderBottom: `1px solid ${color.rule}`,
+ fontSize: 14,
+ lineHeight: "20px",
+ color: color.muted,
+ verticalAlign: "top",
+ }}
+ >
+ {i + 1}
+ </td>
+ <td
+ valign="top"
+ style={{ padding: "12px 0", borderBottom: `1px solid ${color.rule}`, fontSize: 14, lineHeight: "20px" }}
+ >
+ <span style={{ display: "block", fontWeight: 500, color: color.text }}>{step.title}</span>
+ <span style={{ display: "block", fontSize: 13, color: color.muted }}>{step.detail}</span>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+);
+
+interface ButtonRowProps {
+ label: string;
+ href: string;
+ secondary?: { label: string; href: string };
+ top?: number;
+}
+
+/** The one emerald action, with an optional plain link beside it. */
+export const PrimaryButton = ({ label, href, secondary, top = 32 }: ButtonRowProps) => (
+ <div style={{ marginTop: top }}>
+ <Button
+ href={href}
+ style={{
+ backgroundColor: color.action,
+ borderRadius: 4,
+ color: "#ffffff",
+ fontSize: 15,
+ lineHeight: "20px",
+ fontWeight: 600,
+ textDecoration: "none",
+ padding: "12px 20px",
+ display: "inline-block",
+ }}
+ >
+ {label}
+ </Button>
+ {secondary && (
+ <Link
+ href={secondary.href}
+ style={{
+ marginLeft: 20,
+ fontSize: 14,
+ lineHeight: "20px",
+ color: color.text,
+ textDecoration: "underline",
+ textDecorationColor: color.linkUnderline,
+ }}
+ >
+ {secondary.label}
+ </Link>
+ )}
+ </div>
+);
+
+/** A one-time code, split in two groups for reading; copying it gives the bare digits. */
+export const CodeBox = ({ code }: { code: string }) => {
+ const half = code.length === 6 || code.length === 8 ? code.length / 2 : code.length;
+ return (
+ <div style={{ marginTop: 24 }}>
+ <table {...table}>
+ <tbody>
+ <tr>
+ <td
+ style={{
+ padding: "16px 24px",
+ border: `1px solid ${color.rule}`,
+ borderRadius: 4,
+ backgroundColor: color.fill,
+ fontFamily: monoFamily,
+ fontSize: 32,
+ lineHeight: "40px",
+ fontWeight: 600,
+ letterSpacing: "0.16em",
+ color: color.text,
+ }}
+ >
+ {code.slice(0, half)}
+ {half < code.length && <span style={{ paddingLeft: 16 }}>{code.slice(half)}</span>}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+/** A block of code to copy, such as the tracking script. */
+export const Snippet = ({ code, top = 16 }: { code: string; top?: number }) => (
+ <div
+ style={{
+ marginTop: top,
+ padding: "14px 16px",
+ border: `1px solid ${color.rule}`,
+ borderRadius: 4,
+ backgroundColor: color.fill,
+ fontFamily: monoFamily,
+ fontSize: 13,
+ lineHeight: "20px",
+ color: color.text,
+ whiteSpace: "pre-wrap",
+ // Wrap at spaces first so an attribute like data-site-id stays whole.
+ overflowWrap: "anywhere",
+ wordBreak: "break-word",
+ }}
+ >
+ {code}
+ </div>
+);
+
+/** A long URL printed as a paste-able fallback under a button. */
+export const UrlFallback = ({ url }: { url: string }) => (
+ <>
+ <Note>Or paste this link into your browser:</Note>
+ <p
+ style={{
+ margin: "4px 0 0",
+ fontFamily: monoFamily,
+ fontSize: 12,
+ lineHeight: "18px",
+ color: color.muted,
+ wordBreak: "break-all",
+ }}
+ >
+ {url}
+ </p>
+ </>
+);
+
+export const Badge = ({ children, tone }: { children: React.ReactNode; tone: "danger" }) => (
+ <span
+ style={{
+ display: "inline-block",
+ padding: "2px 8px",
+ borderRadius: 3,
+ fontSize: 12,
+ lineHeight: "16px",
+ fontWeight: 600,
+ backgroundColor: tone === "danger" ? color.dangerFill : color.fill,
+ color: tone === "danger" ? color.dangerText : color.text,
+ }}
+ >
+ {children}
+ </span>
+);
+
+interface MeterProps {
+ used: string;
+ of: string;
+ percent: number;
+ barColor: string;
+ startLabel: string;
+ endLabel: string;
+ top?: number;
+}
+
+/** A usage bar with its scale underneath. */
+export const Meter = ({ used, of, percent, barColor, startLabel, endLabel, top = 24 }: MeterProps) => {
+ const filled = Math.max(1, Math.min(100, Math.round(percent)));
+ return (
+ <div style={{ marginTop: top }}>
+ <table {...table} width="100%">
+ <tbody>
+ <tr>
+ <td style={{ fontSize: 13, lineHeight: "20px", color: color.muted }}>
+ <span style={{ fontWeight: 600, color: color.text }}>{used}</span> of {of}
+ </td>
+ <td align="right" style={{ fontSize: 13, lineHeight: "20px", fontWeight: 600, color: color.text }}>
+ {Math.round(percent)}%
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <table {...table} width="100%" style={{ marginTop: 8, borderCollapse: "separate" }}>
+ <tbody>
+ <tr>
+ <td
+ width={`${filled}%`}
+ style={{
+ width: `${filled}%`,
+ height: 8,
+ lineHeight: "8px",
+ fontSize: 0,
+ backgroundColor: barColor,
+ borderRadius: filled === 100 ? 4 : "4px 0 0 4px",
+ }}
+ >
+ &nbsp;
+ </td>
+ {filled < 100 && (
+ <td
+ style={{
+ height: 8,
+ lineHeight: "8px",
+ fontSize: 0,
+ backgroundColor: color.track,
+ borderRadius: "0 4px 4px 0",
+ }}
+ >
+ &nbsp;
+ </td>
+ )}
+ </tr>
+ </tbody>
+ </table>
+ <table {...table} width="100%" style={{ marginTop: 8 }}>
+ <tbody>
+ <tr>
+ <td style={{ fontSize: 12, lineHeight: "16px", color: color.muted }}>{startLabel}</td>
+ <td align="right" style={{ fontSize: 12, lineHeight: "16px", color: color.muted }}>
+ {endLabel}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+export interface Stat {
+ label: string;
+ value: string;
+ change?: React.ReactNode;
+}
+
+/** Headline numbers in a bordered grid, three to a row. */
+export const StatGrid = ({ stats, top = 28 }: { stats: Stat[]; top?: number }) => {
+ const rows: Stat[][] = [];
+ for (let i = 0; i < stats.length; i += 3) rows.push(stats.slice(i, i + 3));
+ return (
+ <div style={{ marginTop: top }}>
+ <table
+ {...table}
+ width="100%"
+ style={{ border: `1px solid ${color.rule}`, borderRadius: 4, borderCollapse: "separate", tableLayout: "fixed" }}
+ >
+ <tbody>
+ {rows.map((row, r) => (
+ <tr key={r}>
+ {row.map((stat, c) => (
+ <td
+ key={stat.label}
+ className="ledger-stat"
+ width="33%"
+ valign="top"
+ style={{
+ width: "33.33%",
+ padding: "14px 16px",
+ verticalAlign: "top",
+ borderLeft: c > 0 ? `1px solid ${color.rule}` : undefined,
+ borderTop: r > 0 ? `1px solid ${color.rule}` : undefined,
+ }}
+ >
+ <div style={{ fontSize: 12, lineHeight: "16px", fontWeight: 500, color: color.muted }}>
+ {stat.label}
+ </div>
+ <div
+ style={{
+ marginTop: 6,
+ fontSize: 20,
+ lineHeight: "26px",
+ fontWeight: 600,
+ letterSpacing: "-0.01em",
+ color: color.text,
+ }}
+ >
+ {stat.value}
+ </div>
+ {stat.change && (
+ <div style={{ marginTop: 2, fontSize: 12, lineHeight: "16px", color: color.muted }}>
+ {stat.change}
+ </div>
+ )}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+export interface ShareRow {
+ label: string;
+ value: string;
+ /** 0–100, this row's share of the total. */
+ share: number | null;
+ /** 0–100, bar length relative to the largest row. */
+ bar: number;
+}
+
+interface ShareTableProps {
+ labelHeader: string;
+ valueHeader: string;
+ rows: ShareRow[];
+ top?: number;
+}
+
+/** A ranked breakdown: label, a periwinkle share bar, the count and its share. */
+export const ShareTable = ({ labelHeader, valueHeader, rows, top = 12 }: ShareTableProps) => {
+ const header = { fontSize: 12, lineHeight: "16px", fontWeight: 500, color: color.muted, paddingBottom: 8 };
+ const cell = { padding: "10px 0", borderBottom: `1px solid ${color.ruleSoft}` };
+ return (
+ <div style={{ marginTop: top }}>
+ <table {...table} width="100%" style={{ borderCollapse: "collapse", tableLayout: "fixed" }}>
+ <tbody>
+ <tr>
+ <td style={{ ...header, borderBottom: `1px solid ${color.rule}` }}>{labelHeader}</td>
+ <td
+ className="ledger-bar"
+ width="112"
+ style={{ ...header, width: 112, borderBottom: `1px solid ${color.rule}` }}
+ />
+ <td
+ width="72"
+ align="right"
+ style={{ ...header, width: 72, textAlign: "right", borderBottom: `1px solid ${color.rule}` }}
+ >
+ {valueHeader}
+ </td>
+ <td
+ width="60"
+ align="right"
+ style={{ ...header, width: 60, textAlign: "right", borderBottom: `1px solid ${color.rule}` }}
+ >
+ Share
+ </td>
+ </tr>
+ {rows.map(row => (
+ <tr key={row.label}>
+ <td style={{ ...cell, fontSize: 14, lineHeight: "20px", color: color.text, wordBreak: "break-all" }}>
+ {row.label}
+ </td>
+ <td className="ledger-bar" style={{ ...cell, paddingLeft: 16 }}>
+ <table {...table} width="96" style={{ width: 96, borderCollapse: "separate" }}>
+ <tbody>
+ <tr>
+ <td
+ width={`${Math.max(2, Math.round(row.bar))}%`}
+ style={{
+ height: 6,
+ lineHeight: "6px",
+ fontSize: 0,
+ backgroundColor: color.data,
+ borderRadius: 3,
+ }}
+ >
+ &nbsp;
+ </td>
+ {row.bar < 98 && (
+ <td
+ style={{
+ height: 6,
+ lineHeight: "6px",
+ fontSize: 0,
+ backgroundColor: color.track,
+ borderRadius: 3,
+ }}
+ >
+ &nbsp;
+ </td>
+ )}
+ </tr>
+ </tbody>
+ </table>
+ </td>
+ <td
+ align="right"
+ style={{
+ ...cell,
+ textAlign: "right",
+ fontSize: 14,
+ lineHeight: "20px",
+ fontWeight: 500,
+ color: color.text,
+ }}
+ >
+ {row.value}
+ </td>
+ <td
+ align="right"
+ style={{ ...cell, textAlign: "right", fontSize: 13, lineHeight: "20px", color: color.muted }}
+ >
+ {row.share == null ? "" : `${row.share.toFixed(1)}%`}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+export const Signoff = () => (
+ <P top={28}>
+ Bill
+ <br />
+ <span style={{ color: color.muted }}>Founder, Rybbit</span>
+ </P>
+);
+
+export { table as tableAttrs };
diff --git a/server/src/lib/email/templates/templates.test.ts b/server/src/lib/email/templates/templates.test.ts
new file mode 100644
index 000000000..e2f56e448
--- /dev/null
+++ b/server/src/lib/email/templates/templates.test.ts
@@ -0,0 +1,197 @@
+import { render as renderEmail } from "@react-email/components";
+import { DateTime } from "luxon";
+import { describe, expect, it } from "vitest";
+import type { SiteReport } from "../../../services/weekyReports/weeklyReportTypes.js";
+import { installSnippet, welcome } from "../../../services/lifecycleEmails/lifecycleContent.js";
+import { formatChange, percentChange } from "../format.js";
+import { ApproachingLimitEmail, approachingLimitSubject, projectedLimitDate } from "./ApproachingLimitEmail.js";
+import { ChangeEmailEmail } from "./ChangeEmailEmail.js";
+import { InvitationEmail } from "./InvitationEmail.js";
+import { LetterEmail } from "./LetterEmail.js";
+import { LimitExceededEmail } from "./LimitExceededEmail.js";
+import { OtpEmail } from "./OtpEmail.js";
+import { SiteTransferEmail } from "./SiteTransferEmail.js";
+import { VerifyEmailEmail } from "./VerifyEmailEmail.js";
+import { WeeklyReportEmail, weeklyReportSubject } from "./WeeklyReportEmail.js";
+
+/** Rendered HTML without the <!-- --> markers React puts between adjacent text nodes. */
+const render = async (element: Parameters<typeof renderEmail>[0]) =>
+ (await renderEmail(element)).replace(/<!-- -->/g, "");
+
+const overview = (users: number) => ({
+ sessions: users * 2,
+ pageviews: users * 5,
+ users,
+ pages_per_session: 2.5,
+ bounce_rate: 40,
+ session_duration: 120,
+});
+
+const report = (users: number, previousUsers: number): SiteReport => ({
+ siteId: 7,
+ siteName: "Acme",
+ siteDomain: "acme.com",
+ weekStart: "2026-10-12",
+ weekEnd: "2026-10-18",
+ currentWeek: overview(users),
+ previousWeek: overview(previousUsers),
+ daily: Array.from({ length: 7 }, (_, i) => ({ date: `2026-10-${12 + i}`, sessions: 10 + i, previousSessions: 5 })),
+ topCountries: [{ value: "DE", count: 40, percentage: 40 }],
+ topPages: [{ value: "/pricing", count: 30, percentage: 30 }],
+ topReferrers: [{ value: "news.ycombinator.com", count: 20, percentage: 20 }],
+ deviceBreakdown: [{ value: "desktop", count: 60, percentage: 60 }],
+});
+
+const usage = {
+ organizationName: "Acme Inc",
+ eventCount: 91_000,
+ eventLimit: 100_000,
+ sites: [
+ { domain: "acme.com", events: 61_000 },
+ { domain: "docs.acme.com", events: 30_000 },
+ ],
+ now: DateTime.fromISO("2026-10-24T12:00:00Z") as DateTime<true>,
+};
+
+describe("Ledger templates", () => {
+ it("use the PNG logo, which Gmail and Outlook can display", async () => {
+ const html = await render(OtpEmail({ otp: "381924", type: "forget-password", email: "[email protected]" }));
+ expect(html).toContain("/rybbit/email-logo.png");
+ expect(html).not.toContain(".svg");
+ });
+
+ it("show the reset code and the account it belongs to", async () => {
+ const html = await render(OtpEmail({ otp: "381924", type: "forget-password", email: "[email protected]" }));
+ expect(html).toContain("Reset your password");
+ expect(html).toContain("381");
+ expect(html).toContain("924");
+ expect(html).toContain("[email protected]");
+ });
+
+ it("print verification and change links as a paste-able fallback", async () => {
+ const verify = await render(
+ VerifyEmailEmail({ email: "[email protected]", verificationUrl: "https://x.test/verify?t=1" })
+ );
+ expect(verify).toContain("https://x.test/verify?t=1");
+
+ const change = await render(
+ ChangeEmailEmail({ currentEmail: "[email protected]", newEmail: "[email protected]", confirmUrl: "https://x.test/confirm" })
+ );
+ expect(change).toContain("[email protected]");
+ expect(change).toContain("[email protected]");
+ expect(change).toContain("https://x.test/confirm");
+ });
+
+ it("name the inviter and the role in an invitation", async () => {
+ const html = await render(
+ InvitationEmail({
+ inviterName: "Sam Chen",
+ inviterEmail: "[email protected]",
+ organizationName: "Acme Inc",
+ role: "admin",
+ expiresAt: new Date("2026-10-26T14:02:00Z"),
+ inviteLink: "https://x.test/invite",
+ })
+ );
+ expect(html).toContain("Sam Chen ([email protected])");
+ expect(html).toContain("Admin");
+ expect(html).toContain("Oct 26, 2026 at 14:02 UTC");
+ });
+
+ it("show the site and expiry in a transfer", async () => {
+ const html = await render(
+ SiteTransferEmail({
+ email: "[email protected]",
+ sentBy: "[email protected]",
+ sentByEmail: "[email protected]",
+ siteDomain: "acme.com",
+ organizationName: "Acme Inc",
+ expiresAt: "2026-10-31T10:00:00.000Z",
+ transferLink: "https://x.test/transfer",
+ })
+ );
+ expect(html).toContain("acme.com");
+ expect(html).toContain("Oct 31, 2026");
+ });
+});
+
+describe("usage emails", () => {
+ it("project the date the limit will be reached at this month's rate", () => {
+ // 91,000 events in 23.5 days is ~3,872 a day, so the last 9,000 take ~2.3 days.
+ expect(projectedLimitDate(91_000, 100_000, usage.now)?.toISODate()).toBe("2026-10-26");
+ // A pace that only reaches the limit after the reset projects nothing.
+ expect(projectedLimitDate(10_000, 100_000, usage.now)).toBeNull();
+ });
+
+ it("put the share used in the subject", () => {
+ expect(approachingLimitSubject("Acme Inc", 91_000, 100_000, usage.now)).toBe(
+ "Acme Inc has used 91% of its October events"
+ );
+ });
+
+ it("break usage down by site", async () => {
+ const html = await render(ApproachingLimitEmail(usage));
+ expect(html).toContain("docs.acme.com");
+ expect(html).toContain("Resets Nov 1");
+ });
+
+ it("say tracking stopped, not that data became unavailable", async () => {
+ const html = await render(LimitExceededEmail({ ...usage, eventCount: 100_412 }));
+ expect(html).toContain("Tracking is paused for Acme Inc");
+ expect(html).toContain("Your dashboards and existing data are still available.");
+ expect(html).not.toContain("access your data");
+ });
+});
+
+describe("weekly report", () => {
+ it("leads with visitors and their change in the subject", () => {
+ expect(weeklyReportSubject(report(6105, 5560))).toBe("acme.com: 6,105 visitors last week, up 9.8%");
+ expect(weeklyReportSubject(report(90, 100))).toBe("acme.com: 90 visitors last week, down 10.0%");
+ });
+
+ it("doesn't call growth from zero +100%", async () => {
+ expect(percentChange(50, 0)).toBeNull();
+ expect(weeklyReportSubject(report(50, 0))).toBe("acme.com: 50 visitors last week");
+ const html = await render(WeeklyReportEmail({ site: report(50, 0), unsubscribeUrl: "https://x.test/off" }));
+ expect(html).not.toContain("+100");
+ expect(html).toContain("from 0");
+ });
+
+ it("formats changes with a real minus sign", () => {
+ expect(formatChange(9.84)).toBe("+9.8%");
+ expect(formatChange(-5.4)).toBe("βˆ’5.4%");
+ expect(formatChange(0.01)).toBe("0%");
+ });
+
+ it("names countries without emoji flags and links referrers without third-party favicons", async () => {
+ const html = await render(WeeklyReportEmail({ site: report(10, 8), unsubscribeUrl: "https://x.test/off" }));
+ expect(html).toContain("Germany");
+ expect(html).not.toContain("\u{1F1E9}");
+ expect(html).not.toContain("google.com/s2/favicons");
+ });
+
+ it("carries the one-click link to turn reports off", async () => {
+ const html = await render(WeeklyReportEmail({ site: report(10, 8), unsubscribeUrl: "https://x.test/off" }));
+ expect(html).toContain("Turn off weekly reports");
+ expect(html).toContain("https://x.test/off");
+ });
+});
+
+describe("letters", () => {
+ it("render the welcome email as Ledger HTML with Bill's sign-off", async () => {
+ const html = await render(LetterEmail({ letter: welcome("Ada Lovelace") }));
+ expect(html).toContain("Hi Ada,");
+ expect(html).toContain("Founder, Rybbit");
+ });
+
+ it("render a site's tracking script in the snippet email", async () => {
+ const html = await render(
+ LetterEmail({
+ letter: installSnippet([{ domain: "acme.com", siteId: 42, platform: null }], "Ada"),
+ footer: [{ label: "Unsubscribe from these emails", href: "https://x.test/unsub" }],
+ })
+ );
+ expect(html).toContain("data-site-id=&quot;42&quot;");
+ expect(html).toContain("https://x.test/unsub");
+ });
+});
diff --git a/server/src/services/lifecycleEmails/lifecycleContent.ts b/server/src/services/lifecycleEmails/lifecycleContent.ts
index a557d8c28..a82a0024e 100644
--- a/server/src/services/lifecycleEmails/lifecycleContent.ts
+++ b/server/src/services/lifecycleEmails/lifecycleContent.ts
@@ -1,19 +1,10 @@
+import { appUrl, formatCount, plural } from "../../lib/email/format.js";
+import { greeting, type Letter, type LetterBlock } from "../../lib/email/letter.js";
import type { PlatformInfo } from "./platformDetect.js";
-export interface LifecycleEmail {
- subject: string;
- text: string;
-}
-
-const appUrl = () => (process.env.BASE_URL || "https://app.rybbit.io").replace(/\/$/, "");
+export type LifecycleEmail = Letter;
-const greeting = (name?: string | null) => {
- // Email-signup users have their email prefix stored as their name - don't greet with that
- const clean = name && !name.includes("@") ? name.split(" ")[0] : "";
- return clean ? `Hi ${clean},` : "Hi,";
-};
-
-const signoff = `\n\nBill\nFounder, Rybbit`;
+const SETUP_GUIDES_URL = "https://rybbit.com/docs/script";
/**
* Multi-site emails list at most this many sites in the body; the rest are
@@ -29,38 +20,72 @@ export const subjectDomains = (domains: string[]): string => {
return `${domains[0]} and ${others} other site${others === 1 ? "" : "s"}`;
};
-const overflowLine = (total: number, noun: string) => {
+const overflow = (total: number): LetterBlock[] => {
const hidden = total - MAX_LISTED_SITES;
- return hidden > 0 ? `\n...and ${hidden} more ${noun}${hidden === 1 ? "" : "s"}.` : "";
+ return hidden > 0 ? [{ type: "note", text: `Plus ${plural(hidden, "more site")}.` }] : [];
};
export const snippetFor = (siteId: number) =>
`<script src="${appUrl()}/api/script.js" data-site-id="${siteId}" defer></script>`;
+// ---------------------------------------------------------------------------
+// Signup
+// ---------------------------------------------------------------------------
+
+export const welcome = (name?: string | null): LifecycleEmail => ({
+ subject: "Welcome to Rybbit!",
+ preview: "Thanks for signing up! Here's how to get started.",
+ greeting: greeting(name),
+ blocks: [
+ { type: "p", text: "Welcome to Rybbit, and thanks for signing up! I'm Bill, the founder." },
+ { type: "p", text: "Rybbit is fully self-funded, so we only answer to the people who use it." },
+ { type: "p", text: "Getting set up takes about a minute:" },
+ {
+ type: "steps",
+ steps: [
+ { title: "Add your site", detail: "Just the domain" },
+ { title: "Paste one script tag", detail: "In your site's <head>" },
+ { title: "See your first visitor", detail: "Live on your dashboard" },
+ ],
+ },
+ { type: "button", label: "Add your site", href: appUrl() },
+ { type: "p", text: "If you have any questions or run into problems, just reply to this email." },
+ ],
+});
+
// ---------------------------------------------------------------------------
// Stage 1: signed up, no site
// ---------------------------------------------------------------------------
export const noSite1 = (name?: string | null): LifecycleEmail => ({
subject: "Finish setting up Rybbit",
- text: `${greeting(name)}
-
-Looks like you haven't added your website yet. It takes about a minute - you give us the domain, we give you one script tag.
-
-Pick up where you left off: ${appUrl()}
-
-If anything was confusing or got in your way, just reply and tell me - I read every response.${signoff}`,
+ preview: "You haven't added a site yet. It only takes a minute.",
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: "Looks like you haven't added your website yet. It only takes a minute. Enter your domain and we'll give you a script tag to paste.",
+ },
+ { type: "button", label: "Add your site", href: appUrl() },
+ { type: "p", text: "If something got in the way, just reply and let me know." },
+ ],
});
export const noSite2 = (name?: string | null): LifecycleEmail => ({
subject: "Was something unclear?",
- text: `${greeting(name)}
-
-You signed up for Rybbit a few days ago but haven't added a site. That usually means something got in the way - a question about pricing, self-hosting, privacy, or just timing.
-
-Whatever it was, I'd genuinely like to know. Reply with one line and I'll help, or tell me what we could have done better.
-
-This is the last email I'll send unless you start using Rybbit.${signoff}`,
+ preview: "Just reply and I'll help. This is my last email about it.",
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: "You signed up for Rybbit a few days ago but haven't added a site yet. Did something get in the way?",
+ },
+ {
+ type: "p",
+ text: "If you have a question about pricing, privacy or anything else, just reply and I'll help. And if we could have done something better, I'd like to hear that too.",
+ },
+ { type: "p", text: "This is the last email I'll send about it." },
+ ],
});
// ---------------------------------------------------------------------------
@@ -75,39 +100,67 @@ export interface SnippetSite {
export const installSnippet = (sitesIn: SnippetSite[], name?: string | null): LifecycleEmail => {
const domains = sitesIn.map(s => s.domain);
+ const preview = "Add one script tag to your site's <head> and you're done.";
if (sitesIn.length === 1) {
const [{ domain, siteId, platform }] = sitesIn;
return {
subject: `One step left for ${domain}`,
- text: `${greeting(name)}
-
-${domain} is set up on Rybbit - it just needs the tracking snippet. Add this to the <head> of every page:
-
-${snippetFor(siteId)}
-${
- platform
- ? `\nYour site looks like it runs on ${platform.label}. Here's the exact guide for it:\n${platform.guideUrl}\n`
- : `\nUsing a framework or CMS? We have step-by-step guides for most of them:\nhttps://rybbit.com/docs/script\n`
-}
-As soon as the first pageview arrives you'll see it live on your dashboard. If it's not working after a few minutes, reply and I'll help you debug it.${signoff}`,
+ preview,
+ greeting: greeting(name),
+ blocks: [
+ { type: "p", text: `${domain} is set up. Now add this script to the <head> of every page:` },
+ { type: "code", code: snippetFor(siteId) },
+ {
+ type: "rows",
+ rows: [
+ { label: "Site", value: domain },
+ { label: "Site ID", value: String(siteId), strong: true },
+ ...(platform ? [{ label: "Platform", value: platform.label }] : []),
+ ],
+ },
+ ...(platform
+ ? ([
+ { type: "p", text: `Your site looks like it's built with ${platform.label}. Here's our guide for it.` },
+ { type: "button", label: `Open the ${platform.label} guide`, href: platform.guideUrl },
+ ] as LetterBlock[])
+ : ([
+ { type: "p", text: "Using a framework or CMS? We have setup guides for most of them." },
+ { type: "button", label: "Open the setup guides", href: SETUP_GUIDES_URL },
+ ] as LetterBlock[])),
+ {
+ type: "p",
+ text: "Once it's installed, visits show up on your dashboard right away. If it's not working, just reply and I'll help.",
+ },
+ ],
};
}
- const listed = sitesIn
- .slice(0, MAX_LISTED_SITES)
- .map(s => `${s.domain}${s.platform ? ` (${s.platform.label}: ${s.platform.guideUrl})` : ""}\n${snippetFor(s.siteId)}`)
- .join("\n\n");
return {
subject: `One step left for ${subjectDomains(domains)}`,
- text: `${greeting(name)}
-
-You've added ${sitesIn.length} sites to Rybbit - each one just needs its tracking snippet in the <head> of every page. The snippets differ only by site id:
-
-${listed}${overflowLine(sitesIn.length, "site")}
-
-Every site's snippet is also on its dashboard under Settings. Framework and CMS guides: https://rybbit.com/docs/script
-
-As soon as the first pageview arrives you'll see it live on your dashboard. If something isn't working, reply and I'll help you debug it.${signoff}`,
+ preview,
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: `You've added ${sitesIn.length} sites to Rybbit. Each one needs its own script in the <head> of every page:`,
+ },
+ ...sitesIn.slice(0, MAX_LISTED_SITES).map((s): LetterBlock => ({
+ type: "site",
+ domain: s.domain,
+ code: snippetFor(s.siteId),
+ ...(s.platform ? { guide: { label: s.platform.label, url: s.platform.guideUrl } } : {}),
+ })),
+ ...overflow(sitesIn.length),
+ {
+ type: "p",
+ text: "Every site's script is also in its site settings, and we have setup guides for most frameworks and CMSs.",
+ },
+ { type: "button", label: "Open the setup guides", href: SETUP_GUIDES_URL },
+ {
+ type: "p",
+ text: "Once it's installed, visits show up on your dashboard right away. If something isn't working, just reply and I'll help.",
+ },
+ ],
};
};
@@ -116,64 +169,82 @@ export interface CheckSite {
checkInstallUrl: string;
}
+const INSTALL_CAUSES = [
+ { title: "The script isn't on the live site", detail: "Check the page source of your live site" },
+ { title: "The site hasn't been redeployed since you added it", detail: "Redeploy, then reload the page" },
+ { title: "An adblocker is blocking your own test visit", detail: "Try a private window" },
+];
+
export const installCheck = (sitesIn: CheckSite[], name?: string | null): LifecycleEmail => {
const domains = sitesIn.map(s => s.domain);
+ const preview = "Here's how to check that the script is installed.";
if (sitesIn.length === 1) {
const [{ domain, checkInstallUrl }] = sitesIn;
return {
- subject: `Still nothing from ${domain}`,
- text: `${greeting(name)}
-
-Your Rybbit snippet hasn't sent any data from ${domain} yet. The three most common causes:
-
-1. The snippet isn't in the <head> of the deployed site (check view-source on the live page)
-2. The site hasn't been redeployed since you added it
-3. An adblocker on your own browser is blocking your test visit - try a private window
-
-Click here and we'll fetch ${domain} right now and tell you whether the snippet is there:
-${checkInstallUrl}
-
-Stuck? Reply to this email and I'll take a look personally.${signoff}`,
+ subject: `No data from ${domain} yet`,
+ preview,
+ greeting: greeting(name),
+ blocks: [
+ { type: "p", text: `We haven't received any data from ${domain} yet. Usually it's one of these:` },
+ { type: "steps", steps: INSTALL_CAUSES },
+ { type: "p", text: `Or click below and we'll check ${domain} for the script.` },
+ { type: "button", label: `Check ${domain} now`, href: checkInstallUrl },
+ { type: "p", text: "Still stuck? Just reply and I'll take a look." },
+ ],
};
}
- const listed = sitesIn
- .slice(0, MAX_LISTED_SITES)
- .map(s => `${s.domain}\n${s.checkInstallUrl}`)
- .join("\n\n");
return {
- subject: `Still nothing from ${subjectDomains(domains)}`,
- text: `${greeting(name)}
-
-Your Rybbit snippets haven't sent any data from ${sitesIn.length} of your sites yet. The three most common causes:
-
-1. The snippet isn't in the <head> of the deployed site (check view-source on the live page)
-2. The site hasn't been redeployed since you added it
-3. An adblocker on your own browser is blocking your test visit - try a private window
-
-Click a link and we'll fetch that site right now and tell you whether the snippet is there:
-
-${listed}${overflowLine(sitesIn.length, "site")}
-
-Stuck? Reply to this email and I'll take a look personally.${signoff}`,
+ subject: `No data from ${subjectDomains(domains)} yet`,
+ preview,
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: `We haven't received any data from ${sitesIn.length} of your sites yet. Usually it's one of these:`,
+ },
+ { type: "steps", steps: INSTALL_CAUSES },
+ { type: "p", text: "Or click a site below and we'll check it for the script." },
+ {
+ type: "rows",
+ rows: sitesIn
+ .slice(0, MAX_LISTED_SITES)
+ .map(s => ({ label: s.domain, value: "Check now", href: s.checkInstallUrl })),
+ },
+ ...overflow(sitesIn.length),
+ { type: "p", text: "Still stuck? Just reply and I'll take a look." },
+ ],
};
};
export const installFinal = (domains: string[], name?: string | null): LifecycleEmail => {
const single = domains.length === 1;
- const which = single ? domains[0] : `${domains.length} of your sites`;
- const listed = single ? "" : `\n\n${domains.slice(0, MAX_LISTED_SITES).join("\n")}${overflowLine(domains.length, "site")}`;
return {
subject: `Need a hand with ${subjectDomains(domains)}?`,
- text: `${greeting(name)}
-
-${which} still ${single ? "isn't" : "aren't"} sending data to Rybbit.${listed}
-
-I won't keep nudging you - this is the last one.
-
-If you hit a technical wall, reply with your platform (WordPress, Next.js, Shopify...) and I'll send you exact instructions. If you decided Rybbit isn't for you, I'd honestly love to know why.
-
-Either way, thanks for giving us a try.${signoff}`,
+ preview: "Reply with your platform and I'll send you setup steps.",
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: single
+ ? `${domains[0]} still isn't sending data to Rybbit. This is my last reminder.`
+ : `${domains.length} of your sites still aren't sending data to Rybbit. This is my last reminder.`,
+ },
+ ...(single
+ ? []
+ : ([
+ {
+ type: "rows",
+ rows: domains.slice(0, MAX_LISTED_SITES).map(domain => ({ label: domain, value: "No data yet" })),
+ },
+ ...overflow(domains.length),
+ ] as LetterBlock[])),
+ {
+ type: "p",
+ text: "If you got stuck, reply with what your site runs on (WordPress, Next.js, Shopify…) and I'll send you step-by-step instructions. And if Rybbit isn't for you, I'd love to know why.",
+ },
+ { type: "p", text: "Thanks for trying Rybbit either way." },
+ ],
};
};
@@ -186,35 +257,60 @@ export interface LiveSite {
siteId: number;
}
-export const siteLive = (sitesIn: LiveSite[], country: string | null, name?: string | null): LifecycleEmail => {
+/** What we know about a site's first pageview, each field optional. */
+export interface FirstPageview {
+ receivedAt: string | null;
+ country: string | null;
+ pathname: string | null;
+ device: string | null;
+}
+
+export const siteLive = (sitesIn: LiveSite[], first: FirstPageview | null, name?: string | null): LifecycleEmail => {
const domains = sitesIn.map(s => s.domain);
+ const closing: LetterBlock = {
+ type: "p",
+ text: "In a few days I'll send you a quick summary of what's coming in.",
+ };
if (sitesIn.length === 1) {
const [{ domain, siteId }] = sitesIn;
+ const country = first?.country ?? null;
+ const facts = [
+ first?.receivedAt && { label: "Received", value: first.receivedAt },
+ country && { label: "Country", value: country },
+ first?.pathname && { label: "Page", value: first.pathname },
+ first?.device && { label: "Device", value: first.device },
+ ].filter((row): row is { label: string; value: string } => !!row);
return {
subject: `Rybbit is live on ${domain}`,
- text: `${greeting(name)}
-
-Rybbit just received its first pageview from ${domain}${country ? ` - a visitor from ${country}` : ""}. Everything is working.
-
-Watch your traffic live: ${appUrl()}/${siteId}
-
-Let it collect data for a couple of days, then I'll send you the first patterns worth looking at.${signoff}`,
+ preview: country ? `Your first visitor just arrived, from ${country}.` : "Your first visitor just arrived.",
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: `You just got your first visitor on ${domain}${country ? `, from ${country}` : ""}. Tracking is working.`,
+ },
+ ...(facts.length > 0 ? [{ type: "rows", rows: facts } as LetterBlock] : []),
+ { type: "button", label: "Watch your traffic live", href: `${appUrl()}/${siteId}` },
+ closing,
+ ],
};
}
- const listed = sitesIn
- .slice(0, MAX_LISTED_SITES)
- .map(s => `${s.domain}: ${appUrl()}/${s.siteId}`)
- .join("\n");
return {
subject: `Rybbit is live on ${subjectDomains(domains)}`,
- text: `${greeting(name)}
-
-Rybbit has received its first pageviews from ${sitesIn.length} of your sites. Everything is working.
-
-${listed}${overflowLine(sitesIn.length, "site")}
-
-Let them collect data for a couple of days, then I'll send you the first patterns worth looking at.${signoff}`,
+ preview: `Data is coming in from ${sitesIn.length} of your sites.`,
+ greeting: greeting(name),
+ blocks: [
+ { type: "p", text: `Rybbit is now getting data from ${sitesIn.length} of your sites. Tracking is working.` },
+ {
+ type: "rows",
+ rows: sitesIn
+ .slice(0, MAX_LISTED_SITES)
+ .map(s => ({ label: s.domain, value: "Open dashboard", href: `${appUrl()}/${s.siteId}` })),
+ },
+ ...overflow(sitesIn.length),
+ closing,
+ ],
};
};
@@ -225,49 +321,100 @@ export interface FirstDaysStats {
topPage: string | null;
}
-export const firstDays = (domain: string, siteId: number, stats: FirstDaysStats, name?: string | null): LifecycleEmail => ({
+export const firstDays = (
+ domain: string,
+ siteId: number,
+ stats: FirstDaysStats,
+ days: number,
+ name?: string | null
+): LifecycleEmail => ({
subject: `Your first days of data on ${domain}`,
- text: `${greeting(name)}
-
-${domain} has been on Rybbit for a few days. So far:
-
-- ${stats.sessions.toLocaleString()} visit${stats.sessions === 1 ? "" : "s"}, ${stats.pageviews.toLocaleString()} pageview${stats.pageviews === 1 ? "" : "s"}${
- stats.topReferrer ? `\n- Top source: ${stats.topReferrer}` : ""
- }${stats.topPage ? `\n- Most viewed page: ${stats.topPage}` : ""}
-
-One thing worth knowing: adblockers hide roughly 10-30% of real visitors from Google Analytics, but they rarely block Rybbit. If these numbers look higher than what you're used to, that's your actual traffic.
-
-See the full picture: ${appUrl()}/${siteId}${signoff}`,
+ preview: `${plural(stats.sessions, "visit")} so far.${stats.topReferrer ? ` Your top source is ${stats.topReferrer}.` : ""}`,
+ greeting: greeting(name),
+ blocks: [
+ { type: "p", text: `Here's how ${domain}'s first ${plural(days, "day")} on Rybbit went:` },
+ {
+ type: "stats",
+ stats: [
+ { label: "Visits", value: formatCount(stats.sessions) },
+ { label: "Pageviews", value: formatCount(stats.pageviews) },
+ { label: "Days tracked", value: formatCount(days) },
+ ],
+ },
+ ...(stats.topReferrer || stats.topPage
+ ? [
+ {
+ type: "rows",
+ rows: [
+ ...(stats.topReferrer ? [{ label: "Top source", value: stats.topReferrer }] : []),
+ ...(stats.topPage ? [{ label: "Most viewed page", value: stats.topPage }] : []),
+ ],
+ } as LetterBlock,
+ ]
+ : []),
+ {
+ type: "p",
+ text: "If these numbers look higher than in Google Analytics, that's expected. Adblockers hide 10–30% of visitors from GA, but they rarely block Rybbit.",
+ },
+ { type: "button", label: "Open your dashboard", href: `${appUrl()}/${siteId}` },
+ ],
});
export const nudgeEvents = (domain: string, siteId: number, name?: string | null): LifecycleEmail => ({
- subject: `See what visitors actually do on ${domain}`,
- text: `${greeting(name)}
-
-Pageviews tell you where people go. Custom events tell you what they do - button clicks, signups, downloads. One line:
-
-window.rybbit.event("signup_clicked")
-
-Or straight from HTML, no code:
-
-<button data-rybbit-event="signup_clicked">Sign up</button>
-
-Events show up on your dashboard and work as funnel steps and goals.
-
-Guide: https://rybbit.com/docs/track-events${signoff}`,
+ subject: `Track clicks and signups on ${domain}`,
+ preview: "It takes one line of code, or none.",
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: "You can track things like button clicks, signups and downloads with custom events. It's one line of JavaScript:",
+ },
+ { type: "code", code: 'window.rybbit.event("signup_clicked")' },
+ { type: "p", text: "Or add an attribute to your HTML:" },
+ { type: "code", code: '<button data-rybbit-event="signup_clicked">Sign up</button>' },
+ { type: "p", text: "Events show up on your dashboard, and you can use them in goals and funnels." },
+ { type: "button", label: "Read the events guide", href: "https://rybbit.com/docs/track-events" },
+ ],
});
-export const nudgeGoals = (domain: string, siteId: number, convertingPath: string, name?: string | null): LifecycleEmail => ({
- subject: `Visitors are reaching ${convertingPath} - measure it`,
- text: `${greeting(name)}
-
-Visitors on ${domain} are landing on ${convertingPath}. That looks like a conversion - worth measuring properly.
-
-Set a goal on that path and Rybbit shows your conversion rate broken down by source, country, and device. Funnels go further: define the steps leading up to it and see exactly where people drop off.
-
-Create your first goal: ${appUrl()}/${siteId}/goals
+export interface ConvertingPath {
+ pathname: string;
+ /** Sessions that reached the page in the lookback window. */
+ sessions: number;
+}
-Guide: https://rybbit.com/docs/goals${signoff}`,
+export const nudgeGoals = (
+ domain: string,
+ siteId: number,
+ converting: ConvertingPath,
+ name?: string | null
+): LifecycleEmail => ({
+ subject: `Turn ${converting.pathname} into a goal`,
+ preview: "See your conversion rate by source, country and device.",
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: `${plural(converting.sessions, "session")} on ${domain} reached ${converting.pathname} in the last two weeks. That looks like a conversion page.`,
+ },
+ {
+ type: "rows",
+ rows: [
+ { label: "Page", value: converting.pathname },
+ { label: "Reached in 14 days", value: plural(converting.sessions, "session"), strong: true },
+ ],
+ },
+ {
+ type: "p",
+ text: "If you make it a goal, Rybbit will show your conversion rate by source, country and device. You can also build a funnel to see where people drop off on the way there.",
+ },
+ {
+ type: "button",
+ label: `Create a goal for ${converting.pathname}`,
+ href: `${appUrl()}/${siteId}/goals`,
+ secondary: { label: "Goals guide", href: "https://rybbit.com/docs/goals" },
+ },
+ ],
});
// ---------------------------------------------------------------------------
@@ -285,31 +432,45 @@ export const wentQuiet = (sitesIn: QuietSite[], name?: string | null): Lifecycle
if (sitesIn.length === 1) {
const [{ domain, siteId, lastEventAt }] = sitesIn;
return {
- subject: `We stopped hearing from ${domain}`,
- text: `${greeting(name)}
-
-${domain} was sending data to Rybbit, but we haven't received anything since ${lastEventAt}.
-
-A quiet period can be normal if your site has fewer visits. If you expected traffic, check that the tracking snippet is still loading on your site, or see your dashboard: ${appUrl()}/${siteId}
-
-If you removed it on purpose, ignore this - I won't email about it again.${signoff}`,
+ subject: `${domain} stopped sending data`,
+ preview: `Nothing since ${lastEventAt}.`,
+ greeting: greeting(name),
+ blocks: [
+ { type: "p", text: `We haven't received any data from ${domain} since ${lastEventAt}.` },
+ {
+ type: "rows",
+ rows: [
+ { label: "Site", value: domain },
+ { label: "Last event", value: lastEventAt, strong: true },
+ ],
+ },
+ { type: "p", text: "If you were expecting traffic, check that the tracking script is still on your site." },
+ { type: "button", label: "Open the dashboard", href: `${appUrl()}/${siteId}` },
+ { type: "p", text: "If you removed it on purpose, you can ignore this. I won't email about it again." },
+ ],
};
}
- const listed = sitesIn
- .slice(0, MAX_LISTED_SITES)
- .map(s => `${s.domain} - last event ${s.lastEventAt}: ${appUrl()}/${s.siteId}`)
- .join("\n");
return {
- subject: `We stopped hearing from ${subjectDomains(domains)}`,
- text: `${greeting(name)}
-
-${sitesIn.length} of your sites were sending data to Rybbit, but we haven't received anything from them for two days or more:
-
-${listed}${overflowLine(sitesIn.length, "site")}
-
-A quiet period can be normal for sites with fewer visits. If you expected traffic, check that the tracking snippet is still loading on each site.
-
-If you removed it on purpose, ignore this - I won't email about these sites again.${signoff}`,
+ subject: `${subjectDomains(domains)} stopped sending data`,
+ preview: `Nothing from ${sitesIn.length} of your sites for two days or more.`,
+ greeting: greeting(name),
+ blocks: [
+ {
+ type: "p",
+ text: `We haven't received any data from ${sitesIn.length} of your sites for two days or more:`,
+ },
+ {
+ type: "rows",
+ rows: sitesIn.slice(0, MAX_LISTED_SITES).map(s => ({ label: s.domain, value: `Last event ${s.lastEventAt}` })),
+ },
+ ...overflow(sitesIn.length),
+ { type: "p", text: "If you were expecting traffic, check that the tracking script is still on each site." },
+ { type: "button", label: "Open Rybbit", href: appUrl() },
+ {
+ type: "p",
+ text: "If you removed them on purpose, you can ignore this. I won't email about these sites again.",
+ },
+ ],
};
};
diff --git a/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts b/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts
index cd0803658..b8f8049dc 100644
--- a/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts
+++ b/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts
@@ -38,7 +38,7 @@ const state = vi.hoisted(() => ({
firstPageview: [] as Array<{ country: string }>,
overview: [] as Array<{ sessions: number; pageviews: number }>,
topRows: [] as Array<{ value: string }>,
- convertingPaths: [] as Array<{ pathname: string }>,
+ convertingPaths: [] as Array<{ pathname: string; sessions?: number }>,
quietCandidates: [] as Array<{ site_id: number; last_event: string }>,
establishedSites: [] as Array<{ site_id: number; total: number }>,
/** unique-key guard mirroring the DB constraint */
@@ -46,7 +46,7 @@ const state = vi.hoisted(() => ({
}));
const mocks = vi.hoisted(() => ({
- sendLifecycleEmail: vi.fn(async (_email: string, _subject: string, _text: string, _idempotencyKey?: string) => true),
+ sendLifecycleEmail: vi.fn(async (_email: string, _letter: Letter, _idempotencyKey?: string) => true),
isContactUnsubscribed: vi.fn(async (_email: string) => false),
detectPlatform: vi.fn(async () => null),
}));
@@ -140,6 +140,7 @@ vi.mock("../../db/clickhouse/clickhouse.js", () => ({
const rows = (() => {
if (query.includes("custom_events")) return state.siteStats;
if (query.includes("ORDER BY timestamp ASC")) return state.firstPageview;
+ if (query.includes("match(pathname")) return state.convertingPaths;
if (query.includes("uniq(session_id)")) return state.overview;
if (query.includes("GROUP BY value")) return state.topRows;
if (query.includes("INTERVAL 14 DAY")) return state.convertingPaths;
@@ -173,10 +174,13 @@ vi.mock("./platformDetect.js", async importOriginal => {
return { ...original, detectPlatform: mocks.detectPlatform };
});
+import { letterText, type Letter } from "../../lib/email/letter.js";
import { lifecycleEmailService } from "./lifecycleEmailService.js";
const run = () => lifecycleEmailService.processLifecycleEmails();
-const sentSubjects = () => mocks.sendLifecycleEmail.mock.calls.map(call => call[1]);
+const sentSubjects = () => mocks.sendLifecycleEmail.mock.calls.map(call => call[1].subject);
+/** The plain-text part of the nth email sent, which carries the same content as the HTML. */
+const sentBody = (n = 0) => letterText(mocks.sendLifecycleEmail.mock.calls[n][1]);
const addUser = (id: string, createdAt: string) => {
state.users.push({ id, email: `${id}@example.com`, name: "Ada", createdAt });
@@ -275,7 +279,7 @@ describe("state: site created, no data", () => {
addOwnedSite("u1", 42, "acme.com", hoursAgo(2));
await run();
expect(sentSubjects()).toEqual(["One step left for acme.com"]);
- const body = mocks.sendLifecycleEmail.mock.calls[0][2];
+ const body = sentBody();
expect(body).toContain('data-site-id="42"');
});
@@ -292,8 +296,8 @@ describe("state: site created, no data", () => {
state.logs.length = 0;
markSent("u1", "install_snippet:42", hoursAgo(25));
await run();
- expect(sentSubjects()).toEqual(["Still nothing from acme.com"]);
- const body = mocks.sendLifecycleEmail.mock.calls[0][2];
+ expect(sentSubjects()).toEqual(["No data from acme.com yet"]);
+ const body = sentBody();
expect(body).toContain("/api/site/check-install?siteId=42&domain=acme.com&exp=");
});
@@ -332,7 +336,7 @@ describe("transition: first data arrives", () => {
state.firstPageview.push({ country: "DE" });
await run();
expect(sentSubjects()).toEqual(["Rybbit is live on acme.com"]);
- const body = mocks.sendLifecycleEmail.mock.calls[0][2];
+ const body = sentBody();
expect(body).toContain("Germany");
});
@@ -343,7 +347,7 @@ describe("transition: first data arrives", () => {
await run();
// Bundled kinds key on the cooldown window, not the member sites, so a
// retry after a lost response reuses it even if membership changed.
- expect(mocks.sendLifecycleEmail.mock.calls[0][3]).toBe("lifecycle:u1:site_live:first");
+ expect(mocks.sendLifecycleEmail.mock.calls[0][2]).toBe("lifecycle:u1:site_live:first");
});
it("does not send it for sites whose first event is old (pre-existing traffic)", async () => {
@@ -364,7 +368,7 @@ describe("transition: first data arrives", () => {
// next run attempts the same key again.
await run();
expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(2);
- expect(mocks.sendLifecycleEmail.mock.calls[1][1]).toBe("Rybbit is live on acme.com");
+ expect(mocks.sendLifecycleEmail.mock.calls[1][1].subject).toBe("Rybbit is live on acme.com");
});
});
@@ -382,8 +386,8 @@ describe("state: data flowing", () => {
state.topRows.push({ value: "google.com" });
await run();
expect(sentSubjects()).toEqual(["Your first days of data on acme.com"]);
- const body = mocks.sendLifecycleEmail.mock.calls[0][2];
- expect(body).toContain("120 visits");
+ const body = sentBody();
+ expect(body).toContain("Visits: 120");
expect(body).toContain("google.com");
});
@@ -402,16 +406,16 @@ describe("state: data flowing", () => {
state.siteStats.push({ site_id: 42, first_event: daysAgo(8), last_event: hoursAgo(2), total: 2000, pageviews: 1900, custom_events: 4 });
markSent("u1", "site_live:42", daysAgo(4));
markSent("u1", "first_days:42", daysAgo(4));
- state.convertingPaths.push({ pathname: "/thank-you" });
+ state.convertingPaths.push({ pathname: "/thank-you", sessions: 86 });
await run();
- expect(sentSubjects()).toEqual(["Visitors are reaching /thank-you - measure it"]);
+ expect(sentSubjects()).toEqual(["Turn /thank-you into a goal"]);
// With a goal already configured, the nudge never fires
state.sentKeys.delete("u1:nudge_goals:42");
mocks.sendLifecycleEmail.mockClear();
state.goals.push({ siteId: 42 });
await run();
- expect(sentSubjects()).not.toContain("Visitors are reaching /thank-you - measure it");
+ expect(sentSubjects()).not.toContain("Turn /thank-you into a goal");
});
it("nudges custom events only when the site has none", async () => {
@@ -421,7 +425,7 @@ describe("state: data flowing", () => {
markSent("u1", "site_live:42", daysAgo(5));
markSent("u1", "first_days:42", daysAgo(5));
await run();
- expect(sentSubjects()).toEqual(["See what visitors actually do on acme.com"]);
+ expect(sentSubjects()).toEqual(["Track clicks and signups on acme.com"]);
});
});
@@ -441,7 +445,7 @@ describe("state: went quiet", () => {
it("alerts the owner when an established site stops sending data, once per outage", async () => {
quietSite();
await run();
- expect(sentSubjects()).toEqual(["We stopped hearing from quiet.com"]);
+ expect(sentSubjects()).toEqual(["quiet.com stopped sending data"]);
// Hourly cadence: force the next run to include the went-quiet pass again.
(lifecycleEmailService as any).lastWentQuietAt = null;
await run();
@@ -470,8 +474,8 @@ describe("state: went quiet", () => {
state.establishedSites.push({ site_id: 8, total: 3000 });
state.sites.push({ siteId: 8, domain: "quiet2.com", createdAt: daysAgo(200), organizationId: "org-x", detectedPlatform: null });
await run();
- expect(sentSubjects()).toEqual(["We stopped hearing from quiet.com and 1 other site"]);
- const body = mocks.sendLifecycleEmail.mock.calls[0][2];
+ expect(sentSubjects()).toEqual(["quiet.com and 1 other site stopped sending data"]);
+ const body = sentBody();
expect(body).toContain("quiet.com");
expect(body).toContain("quiet2.com");
expect(state.logs.map(l => l.emailKey).filter(k => k.startsWith("went_quiet:")).length).toBe(2);
@@ -492,7 +496,7 @@ describe("state: went quiet", () => {
quietSite();
state.recentQuietLogs.push({ siteId: 99, userId: "owner1", sentAt: daysAgo(7) });
await run();
- expect(sentSubjects()).toEqual(["We stopped hearing from quiet.com"]);
+ expect(sentSubjects()).toEqual(["quiet.com stopped sending data"]);
});
it("bundles sites that stayed quiet during the weekly cooldown, including sites in another organization", async () => {
@@ -518,8 +522,8 @@ describe("state: went quiet", () => {
vi.setSystemTime(new Date("2026-10-14T12:00:00Z"));
await run();
expect(sentSubjects()).toEqual([
- "We stopped hearing from quiet.com",
- "We stopped hearing from quiet2.com and 1 other site",
+ "quiet.com stopped sending data",
+ "quiet2.com and 1 other site stopped sending data",
]);
expect(state.logs.filter(l => l.emailKey.startsWith("went_quiet:")).map(l => l.siteId)).toEqual([7, 8, 9]);
});
@@ -546,12 +550,12 @@ describe("multi-site owners", () => {
for (let i = 1; i <= 13; i++) addOwnedSite("agency", i, `client${i}.com`, hoursAgo(3));
await run();
expect(sentSubjects()).toEqual(["One step left for client1.com and 12 other sites"]);
- const body = mocks.sendLifecycleEmail.mock.calls[0][2];
+ const body = sentBody();
// Ten listed with their own snippet, the rest summarised
expect(body).toContain('data-site-id="1"');
expect(body).toContain('data-site-id="10"');
expect(body).not.toContain('data-site-id="11"');
- expect(body).toContain("...and 3 more sites.");
+ expect(body).toContain("Plus 3 more sites.");
expect(siteIds("install_snippet:")).toEqual(Array.from({ length: 13 }, (_, i) => i + 1));
// Nothing further on the next tick: every site is logged
@@ -582,8 +586,8 @@ describe("multi-site owners", () => {
markSent("agency", `install_snippet:${i}`, hoursAgo(30));
}
await run();
- expect(sentSubjects()).toEqual(["Still nothing from client1.com and 2 other sites"]);
- const body = mocks.sendLifecycleEmail.mock.calls[0][2];
+ expect(sentSubjects()).toEqual(["No data from client1.com and 2 other sites yet"]);
+ const body = sentBody();
expect(body).toContain("/api/site/check-install?siteId=1&");
expect(body).toContain("/api/site/check-install?siteId=3&");
expect(siteIds("install_check:")).toEqual([1, 2, 3]);
@@ -606,7 +610,7 @@ describe("multi-site owners", () => {
}
await run();
expect(sentSubjects()).toEqual(["Rybbit is live on client1.com and 3 other sites"]);
- const body = mocks.sendLifecycleEmail.mock.calls[0][2];
+ const body = sentBody();
expect(body).toContain("client4.com: https://app.rybbit.io/4");
expect(siteIds("site_live:")).toEqual([1, 2, 3, 4]);
});
@@ -649,10 +653,10 @@ describe("multi-site owners", () => {
await run();
expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(2);
const [failed, retried] = mocks.sendLifecycleEmail.mock.calls;
- expect(retried[1]).toBe("Rybbit is live on client1.com and 2 other sites");
+ expect(retried[1].subject).toBe("Rybbit is live on client1.com and 2 other sites");
// Same key: Resend dedupes against the possibly-accepted first attempt
// instead of delivering a second email.
- expect(retried[3]).toBe(failed[3]);
+ expect(retried[2]).toBe(failed[2]);
expect(siteIds("site_live:")).toEqual([1, 2, 3]);
// After a successful send the next window gets a different key.
@@ -662,14 +666,14 @@ describe("multi-site owners", () => {
state.siteStats.length = 0;
state.siteStats.push({ site_id: 2, first_event: hoursAgo(1), last_event: hoursAgo(0.1), total: 5, pageviews: 5, custom_events: 0 });
await run();
- const next = mocks.sendLifecycleEmail.mock.calls[2][3];
+ const next = mocks.sendLifecycleEmail.mock.calls[2][2];
expect(next).toMatch(/^lifecycle:agency:site_live:\d+$/);
- expect(next).not.toBe(failed[3]);
+ expect(next).not.toBe(failed[2]);
});
it("single-key emails keep the per-key idempotency form", async () => {
addUser("u1", hoursAgo(4));
await run();
- expect(mocks.sendLifecycleEmail.mock.calls[0][3]).toBe("lifecycle:u1:no_site_1");
+ expect(mocks.sendLifecycleEmail.mock.calls[0][2]).toBe("lifecycle:u1:no_site_1");
});
});
diff --git a/server/src/services/lifecycleEmails/lifecycleEmailService.ts b/server/src/services/lifecycleEmails/lifecycleEmailService.ts
index 813bda4d9..3ba4061ba 100644
--- a/server/src/services/lifecycleEmails/lifecycleEmailService.ts
+++ b/server/src/services/lifecycleEmails/lifecycleEmailService.ts
@@ -6,6 +6,7 @@ import { db } from "../../db/postgres/postgres.js";
import { goals, lifecycleEmailLog, member, sites, user } from "../../db/postgres/schema.js";
import { IS_CLOUD } from "../../lib/const.js";
import { isContactUnsubscribed, sendLifecycleEmail } from "../../lib/email/email.js";
+import { formatDateTime } from "../../lib/email/format.js";
import { createServiceLogger } from "../../lib/logger/logger.js";
import { signExpiringPayload } from "../../lib/signedToken.js";
import * as content from "./lifecycleContent.js";
@@ -74,6 +75,13 @@ interface BundleEntry {
siteId: number | null;
}
+/** "Desktop, Chrome on macOS" from whichever parts the event recorded. */
+const describeDevice = (deviceType?: string, browser?: string, os?: string): string | null => {
+ const client = [browser, os].filter(Boolean).join(" on ");
+ const parts = [deviceType, client].filter(Boolean);
+ return parts.length > 0 ? parts.join(", ") : null;
+};
+
const countryName = (code: string | null): string | null => {
if (!code) return null;
try {
@@ -142,10 +150,10 @@ class LifecycleEmailService {
return stats;
}
- private async fetchFirstPageview(siteId: number): Promise<{ country: string | null } | null> {
+ private async fetchFirstPageview(siteId: number): Promise<content.FirstPageview | null> {
const result = await clickhouse.query({
query: `
- SELECT country FROM events
+ SELECT timestamp, country, pathname, device_type, browser, operating_system FROM events
WHERE site_id = {siteId:Int32} AND type = 'pageview'
AND timestamp > now() - INTERVAL 7 DAY
ORDER BY timestamp ASC
@@ -154,9 +162,23 @@ class LifecycleEmailService {
format: "JSONEachRow",
query_params: { siteId },
});
- const rows = await result.json<{ country: string }>();
+ const rows = await result.json<{
+ timestamp?: string;
+ country?: string;
+ pathname?: string;
+ device_type?: string;
+ browser?: string;
+ operating_system?: string;
+ }>();
if (rows.length === 0) return null;
- return { country: rows[0].country || null };
+ const row = rows[0];
+ const receivedAt = row.timestamp ? parseTs(row.timestamp) : null;
+ return {
+ receivedAt: receivedAt?.isValid ? formatDateTime(receivedAt) : null,
+ country: countryName(row.country || null),
+ pathname: row.pathname || null,
+ device: describeDevice(row.device_type, row.browser, row.operating_system),
+ };
}
private async fetchFirstDaysStats(siteId: number): Promise<content.FirstDaysStats | null> {
@@ -199,30 +221,33 @@ class LifecycleEmailService {
};
}
- private async fetchConvertingPath(siteId: number): Promise<string | null> {
+ private async fetchConvertingPath(siteId: number): Promise<content.ConvertingPath | null> {
const cacheKey = `conv:${siteId}`;
const retryAfter = this.negativeCache.get(cacheKey);
if (retryAfter && retryAfter > Date.now()) return null;
const result = await clickhouse.query({
query: `
- SELECT pathname, count() AS c
+ SELECT pathname, uniq(session_id) AS sessions
FROM events
WHERE site_id = {siteId:Int32}
AND type = 'pageview'
AND timestamp > now() - INTERVAL 14 DAY
AND match(pathname, '(thank|success|checkout|confirmation|purchase|order-complete|welcome)')
GROUP BY pathname
- ORDER BY c DESC
+ ORDER BY sessions DESC
LIMIT 1
`,
format: "JSONEachRow",
query_params: { siteId },
});
- const rows = await result.json<{ pathname: string }>();
+ const rows = await result.json<{ pathname: string; sessions?: string | number }>();
const path = rows[0]?.pathname || null;
- if (!path) this.negativeCache.set(cacheKey, Date.now() + NEGATIVE_CACHE_TTL_MS);
- return path;
+ if (!path) {
+ this.negativeCache.set(cacheKey, Date.now() + NEGATIVE_CACHE_TTL_MS);
+ return null;
+ }
+ return { pathname: path, sessions: Number(rows[0].sessions ?? 0) };
}
private async resolvePlatform(site: OwnedSite): Promise<PlatformInfo | null> {
@@ -281,7 +306,7 @@ class LifecycleEmailService {
await rollback();
return false;
}
- const sent = await sendLifecycleEmail(email, message.subject, message.text, idempotencyKey);
+ const sent = await sendLifecycleEmail(email, message, idempotencyKey);
if (!sent) {
await rollback();
return false;
@@ -449,7 +474,7 @@ class LifecycleEmailService {
async claimed => {
const chosen = liveSites.filter(site => claimed.some(e => e.siteId === site.siteId));
const first = chosen.length === 1 ? await this.fetchFirstPageview(chosen[0].siteId) : null;
- return content.siteLive(chosen, countryName(first?.country ?? null), u.name);
+ return content.siteLive(chosen, first, u.name);
}
);
if (sent) return;
@@ -574,7 +599,9 @@ class LifecycleEmailService {
if (await unsubscribed()) return;
const sent = await this.sendOnce(u.id, u.email, `first_days:${site.siteId}`, site.siteId, async () => {
const report = await this.fetchFirstDaysStats(site.siteId);
- return report ? content.firstDays(site.domain, site.siteId, report, u.name) : null;
+ return report
+ ? content.firstDays(site.domain, site.siteId, report, Math.max(1, Math.floor(dataAgeDays)), u.name)
+ : null;
});
if (sent) return;
}
@@ -719,7 +746,7 @@ class LifecycleEmailService {
.map(site => ({
domain: site.domain,
siteId: site.siteId,
- lastEventAt: lastEventBySite.get(site.siteId)?.toFormat("MMMM d 'at' HH:mm 'UTC'") ?? "two days ago",
+ lastEventAt: lastEventBySite.get(site.siteId)?.toFormat("LLL d 'at' HH:mm 'UTC'") ?? "two days ago",
})),
owner.name
)
diff --git a/server/src/services/usageService.test.ts b/server/src/services/usageService.test.ts
index 80c176949..af198ea58 100644
--- a/server/src/services/usageService.test.ts
+++ b/server/src/services/usageService.test.ts
@@ -352,7 +352,10 @@ describe("updateOrganizationsMonthlyUsage β€” limit exceeded email", () => {
await usageService.updateOrganizationsMonthlyUsage();
expect(mocks.sendLimitExceededEmail).toHaveBeenCalledTimes(2);
- expect(mocks.sendLimitExceededEmail).toHaveBeenCalledWith("[email protected]", "Org org_1", 101, 100);
+ expect(mocks.sendLimitExceededEmail).toHaveBeenCalledWith(
+ expect.objectContaining({ organizationName: "Org org_1", eventCount: 101, eventLimit: 100 })
+ );
});
it("does not re-email an org that was already over its limit", async () => {
@@ -394,7 +397,10 @@ describe("updateOrganizationsMonthlyUsage β€” approaching limit email", () => {
await usageService.updateOrganizationsMonthlyUsage();
- expect(mocks.sendApproachingLimitEmail).toHaveBeenCalledWith("[email protected]", "Org org_1", 90_000, 100_000);
+ expect(mocks.sendApproachingLimitEmail).toHaveBeenCalledWith(
+ expect.objectContaining({ organizationName: "Org org_1", eventCount: 90_000, eventLimit: 100_000 })
+ );
expect(state.updates[0]).toMatchObject({ approachingLimitNotifiedPeriodStart: "2026-08-01" });
});
diff --git a/server/src/services/usageService.ts b/server/src/services/usageService.ts
index e40fc0084..c16c64f27 100644
--- a/server/src/services/usageService.ts
+++ b/server/src/services/usageService.ts
@@ -9,6 +9,7 @@ import { db } from "../db/postgres/postgres.js";
import { member, organization, sites, user } from "../db/postgres/schema.js";
import { IS_CLOUD, USAGE_COUNTED_EVENT_TYPES } from "../lib/const.js";
import { sendApproachingLimitEmail, sendLimitExceededEmail } from "../lib/email/email.js";
+import type { SiteUsage } from "../lib/email/templates/ApproachingLimitEmail.js";
import { createServiceLogger } from "../lib/logger/logger.js";
import {
getAllStripeSubscriptionsByCustomer,
@@ -214,17 +215,20 @@ class UsageService {
* Gets all sites with their organization IDs (excludes sites without an organization).
* Throws on failure for the same reason as getAllSiteEventCounts: no sites means zero usage.
*/
- private async getAllSites(): Promise<Array<OrgSite & { organizationId: string }>> {
+ private async getAllSites(): Promise<Array<OrgSite & { organizationId: string; domain: string }>> {
const allSites = await db
.select({
siteId: sites.siteId,
organizationId: sites.organizationId,
createdAt: sites.createdAt,
+ domain: sites.domain,
})
.from(sites);
// Filter out sites without an organization ID
- return allSites.filter(site => site.organizationId !== null) as Array<OrgSite & { organizationId: string }>;
+ return allSites.filter(site => site.organizationId !== null) as Array<
+ OrgSite & { organizationId: string; domain: string }
+ >;
}
/**
@@ -375,11 +379,21 @@ class UsageService {
}
// Step 3: Build a map of organizationId -> { sites, eventCount, replayCount }
- const orgDataMap = new Map<string, { sites: OrgSite[]; eventCount: number; replayCount: number }>();
+ const orgDataMap = new Map<
+ string,
+ { sites: OrgSite[]; siteUsage: SiteUsage[]; eventCount: number; replayCount: number }
+ >();
for (const site of allSites) {
- const orgData = orgDataMap.get(site.organizationId) || { sites: [], eventCount: 0, replayCount: 0 };
+ const orgData = orgDataMap.get(site.organizationId) || {
+ sites: [],
+ siteUsage: [],
+ eventCount: 0,
+ replayCount: 0,
+ };
+ const siteEvents = eventCountMap.get(site.siteId) || 0;
orgData.sites.push({ siteId: site.siteId, createdAt: site.createdAt });
- orgData.eventCount += eventCountMap.get(site.siteId) || 0;
+ orgData.siteUsage.push({ domain: site.domain ?? String(site.siteId), events: siteEvents });
+ orgData.eventCount += siteEvents;
orgData.replayCount += replayCountMap.get(site.siteId) || 0;
orgDataMap.set(site.organizationId, orgData);
}
@@ -415,6 +429,12 @@ class UsageService {
const subscription = await this.getOrganizationSubscriptionInfo(orgData, stripeSubscriptions);
if (this.refreshedSince(orgData.id, runStartedAt)) continue;
const eventLimit = subscription.eventLimit;
+ const usageEmail = {
+ organizationName: orgData.name,
+ eventCount,
+ eventLimit,
+ sites: [...(orgStats?.siteUsage ?? [])].sort((a, b) => b.events - a.events),
+ };
const isOverLimit = eventCount > eventLimit;
const replayCount = orgStats?.replayCount || 0;
@@ -446,7 +466,7 @@ class UsageService {
if (ownerEmails.length > 0) {
for (const ownerEmail of ownerEmails) {
try {
- await sendLimitExceededEmail(ownerEmail, orgData.name, eventCount, eventLimit);
+ await sendLimitExceededEmail(ownerEmail, usageEmail);
this.logger.info({ organizationId: orgData.id }, "Sent limit-exceeded email to organization owner");
} catch (error) {
this.logger.error(
@@ -468,7 +488,7 @@ class UsageService {
if (ownerEmails.length > 0) {
for (const ownerEmail of ownerEmails) {
try {
- await sendApproachingLimitEmail(ownerEmail, orgData.name, eventCount, eventLimit);
+ await sendApproachingLimitEmail(ownerEmail, usageEmail);
this.logger.info(
{ organizationId: orgData.id },
"Sent approaching-limit email to organization owner"
diff --git a/server/src/services/weekyReports/weeklyReportService.ts b/server/src/services/weekyReports/weeklyReportService.ts
index dc0774bd6..1bb6f150c 100644
--- a/server/src/services/weekyReports/weeklyReportService.ts
+++ b/server/src/services/weekyReports/weeklyReportService.ts
@@ -14,10 +14,11 @@ import { IS_CLOUD } from "../../lib/const.js";
import {
BreakdownDimension,
buildBreakdownQuery,
+ buildChartQuery,
buildOverviewQuery,
SiteMetricsSpec,
} from "../siteMetrics/siteMetrics.js";
-import type { OverviewData, MetricData, SiteReport, OrganizationReport } from "./weeklyReportTypes.js";
+import type { DailySessions, OverviewData, MetricData, SiteReport, OrganizationReport } from "./weeklyReportTypes.js";
const MAX_SITE_REPORTS_PER_ORG = 10;
@@ -63,14 +64,46 @@ class WeeklyReportService {
}
}
+ /**
+ * Sessions per UTC day across both weeks, paired weekday to weekday. Days
+ * with no sessions are absent from the query result and read as zero.
+ */
+ private async fetchDailySessions(
+ siteId: number,
+ spec: SiteMetricsSpec,
+ currentWeekStart: DateTime
+ ): Promise<DailySessions[]> {
+ try {
+ const result = await clickhouse.query({
+ query: buildChartQuery(spec, "toStartOfDay"),
+ format: "JSONEachRow",
+ query_params: { siteId, timeZone: "UTC" },
+ });
+ const rows = await processResults<{ time: string; sessions: number }>(result);
+ const byDay = new Map(rows.map(row => [row.time.slice(0, 10), Number(row.sessions) || 0]));
+ return Array.from({ length: 7 }, (_, i) => {
+ const date = currentWeekStart.plus({ days: i });
+ return {
+ date: date.toISODate()!,
+ sessions: byDay.get(date.toISODate()!) ?? 0,
+ previousSessions: byDay.get(date.minus({ days: 7 }).toISODate()!) ?? 0,
+ };
+ });
+ } catch (error) {
+ this.logger.error({ err: error, siteId }, "Error fetching daily sessions");
+ return [];
+ }
+ }
+
private async generateSiteReport(siteId: number, siteName: string, siteDomain: string): Promise<SiteReport | null> {
try {
- // Use UTC timezone for consistency
- const now = DateTime.utc();
+ // Whole UTC days, so the report covers exactly Monday to Sunday when the
+ // cron fires at Monday midnight and the chart has one bar per day.
+ const today = DateTime.utc().startOf("day");
- // Calculate current week (last 7 days)
- const currentWeekEnd = now;
- const currentWeekStart = now.minus({ days: 7 });
+ // Calculate current week (the last 7 full days)
+ const currentWeekEnd = today;
+ const currentWeekStart = today.minus({ days: 7 });
// Calculate previous week (8-14 days ago)
const previousWeekEnd = currentWeekStart;
@@ -91,14 +124,16 @@ class WeeklyReportService {
const currentSpec = specFor(currentWeekStart, currentWeekEnd);
const previousSpec = specFor(previousWeekStart, previousWeekEnd);
- const [currentWeek, previousWeek, topCountries, topPages, topReferrers, deviceBreakdown] = await Promise.all([
- this.fetchOverviewData(siteId, currentSpec),
- this.fetchOverviewData(siteId, previousSpec),
- this.fetchTopN(siteId, "country", currentSpec),
- this.fetchTopN(siteId, "pathname", currentSpec),
- this.fetchTopN(siteId, "referrer", currentSpec),
- this.fetchTopN(siteId, "device_type", currentSpec),
- ]);
+ const [currentWeek, previousWeek, daily, topCountries, topPages, topReferrers, deviceBreakdown] =
+ await Promise.all([
+ this.fetchOverviewData(siteId, currentSpec),
+ this.fetchOverviewData(siteId, previousSpec),
+ this.fetchDailySessions(siteId, specFor(previousWeekStart, currentWeekEnd), currentWeekStart),
+ this.fetchTopN(siteId, "country", currentSpec),
+ this.fetchTopN(siteId, "pathname", currentSpec),
+ this.fetchTopN(siteId, "referrer", currentSpec),
+ this.fetchTopN(siteId, "device_type", currentSpec),
+ ]);
if (!currentWeek) {
return null;
@@ -113,6 +148,8 @@ class WeeklyReportService {
siteId,
siteName,
siteDomain,
+ weekStart: currentWeekStart.toISODate()!,
+ weekEnd: currentWeekEnd.minus({ days: 1 }).toISODate()!,
currentWeek,
previousWeek: previousWeek || {
sessions: 0,
@@ -122,6 +159,7 @@ class WeeklyReportService {
bounce_rate: 0,
session_duration: 0,
},
+ daily,
topCountries,
topPages,
topReferrers,
@@ -230,7 +268,7 @@ class WeeklyReportService {
for (const site of allowedSites) {
try {
- await sendWeeklyReportEmail(memberData.email, memberData.name, report.organizationName, site);
+ await sendWeeklyReportEmail({ email: memberData.email, userId: memberData.userId, site });
this.logger.info(
{
organizationId: report.organizationId,
diff --git a/server/src/services/weekyReports/weeklyReportTypes.ts b/server/src/services/weekyReports/weeklyReportTypes.ts
index e4216941d..1571f1032 100644
--- a/server/src/services/weekyReports/weeklyReportTypes.ts
+++ b/server/src/services/weekyReports/weeklyReportTypes.ts
@@ -5,12 +5,24 @@ import type { BreakdownRow, OverviewRow } from "../siteMetrics/siteMetrics.js";
export type OverviewData = OverviewRow;
export type MetricData = BreakdownRow;
+/** One day of the reported week next to the same weekday a week earlier. */
+export interface DailySessions {
+ /** ISO date (UTC) of the day in the reported week. */
+ date: string;
+ sessions: number;
+ previousSessions: number;
+}
+
export interface SiteReport {
siteId: number;
siteName: string;
siteDomain: string;
+ /** ISO dates (UTC): the first and last day of the reported week. */
+ weekStart: string;
+ weekEnd: string;
currentWeek: OverviewData;
previousWeek: OverviewData;
+ daily: DailySessions[];
topCountries: MetricData[];
topPages: MetricData[];
topReferrers: MetricData[];