Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 116 additions & 28 deletions apps/sim/app/api/emails/preview/route.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import {
renderAbandonedCheckoutEmail,
renderBatchInvitationEmail,
renderCreditPurchaseEmail,
renderCreditsExhaustedEmail,
renderEnterpriseSubscriptionEmail,
renderExistingAccountEmail,
renderFreeTierUpgradeEmail,
renderHelpConfirmationEmail,
renderInvitationEmail,
renderLimitThresholdEmail,
renderOnboardingFollowupEmail,
renderOTPEmail,
renderPasswordResetEmail,
renderPaymentFailedEmail,
Expand All @@ -15,20 +20,27 @@ import {
renderUsageLimitReachedEmail,
renderUsageThresholdEmail,
renderWelcomeEmail,
renderWorkspaceAddedEmail,
renderWorkspaceInvitationEmail,
} from '@/components/emails'
import { colors, typography } from '@/components/emails/_styles'
import { emailPreviewQuerySchema } from '@/lib/api/contracts/common'
import { validationErrorResponse } from '@/lib/api/server'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'

const emailTemplates = {
// Auth emails
otp: () => renderOTPEmail('123456', 'user@example.com', 'email-verification'),
'otp-sign-in': () => renderOTPEmail('123456', 'user@example.com', 'sign-in'),
'reset-password': () => renderPasswordResetEmail('John', 'https://sim.ai/reset?token=abc123'),
'existing-account': () => renderExistingAccountEmail('John'),
welcome: () => renderWelcomeEmail('John'),
'onboarding-followup': () => renderOnboardingFollowupEmail('John'),

// Invitation emails
invitation: () => renderInvitationEmail('Jane Doe', 'Acme Corp', 'https://sim.ai/invite/abc123'),
'workspace-added': () =>
renderWorkspaceAddedEmail('Jane Doe', 'Engineering', 'https://sim.ai/workspace/ws_123'),
'batch-invitation': () =>
renderBatchInvitationEmail(
'Jane Doe',
Expand Down Expand Up @@ -87,6 +99,43 @@ const emailTemplates = {
amount: 50,
newBalance: 75,
}),
'credits-exhausted': () =>
renderCreditsExhaustedEmail({
userName: 'John',
limit: 10,
upgradeLink: 'https://sim.ai/settings/billing',
}),
'abandoned-checkout': () => renderAbandonedCheckoutEmail('John'),
'limit-threshold-storage-warning': () =>
renderLimitThresholdEmail({
kind: 'warning',
reason: 'storage',
userName: 'John',
usageLabel: '4.2 GB',
limitLabel: '5 GB',
percentUsed: 84,
upgradeLink: 'https://sim.ai/settings/billing',
}),
'limit-threshold-tables-reached': () =>
renderLimitThresholdEmail({
kind: 'reached',
reason: 'tables',
userName: 'John',
usageLabel: '50,000 rows',
limitLabel: '50,000 rows',
percentUsed: 100,
upgradeLink: 'https://sim.ai/settings/billing',
}),
'limit-threshold-seats-reached': () =>
renderLimitThresholdEmail({
kind: 'reached',
reason: 'seats',
userName: 'John',
usageLabel: '10 seats',
limitLabel: '10 seats',
percentUsed: 100,
upgradeLink: 'https://sim.ai/settings/billing',
}),
'payment-failed': () =>
renderPaymentFailedEmail({
userName: 'John',
Expand Down Expand Up @@ -138,6 +187,40 @@ function isEmailTemplate(template: string): template is EmailTemplate {
return template in emailTemplates
}

const CATEGORIZED = {
Auth: ['otp', 'otp-sign-in', 'reset-password', 'existing-account', 'welcome'],
Invitations: ['invitation', 'batch-invitation', 'workspace-invitation', 'workspace-added'],
Support: ['help-confirmation'],
Billing: [
'usage-threshold',
'usage-limit-reached',
'usage-limit-reached-org',
'free-tier-upgrade',
'credits-exhausted',
'limit-threshold-storage-warning',
'limit-threshold-tables-reached',
'limit-threshold-seats-reached',
'payment-failed',
'credit-purchase',
'plan-welcome-pro',
'plan-welcome-team',
'enterprise-subscription',
],
Notifications: ['schedule-disabled', 'schedule-disabled-auth'],
'Plain (unbranded)': ['onboarding-followup', 'abandoned-checkout'],
} satisfies Record<string, EmailTemplate[]>

/**
* Category map for the gallery, with any template missing from {@link CATEGORIZED}
* appended rather than dropped — so a newly registered template always shows up
* even if nobody remembers to file it.
*/
const PREVIEW_CATEGORIES: Record<string, EmailTemplate[]> = (() => {
const filed = new Set<string>(Object.values(CATEGORIZED).flat())
const unfiled = (Object.keys(emailTemplates) as EmailTemplate[]).filter((t) => !filed.has(t))
return unfiled.length > 0 ? { ...CATEGORIZED, Uncategorized: unfiled } : CATEGORIZED
})()

export const GET = withRouteHandler(async (request: NextRequest) => {
const { searchParams } = new URL(request.url)
const queryValidation = emailPreviewQuerySchema.safeParse(
Expand All @@ -147,48 +230,53 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
const { template } = queryValidation.data

if (!template) {
const categories = {
Auth: ['otp', 'reset-password', 'welcome'],
Invitations: ['invitation', 'batch-invitation', 'workspace-invitation'],
Support: ['help-confirmation'],
Billing: [
'usage-threshold',
'enterprise-subscription',
'free-tier-upgrade',
'plan-welcome-pro',
'plan-welcome-team',
'credit-purchase',
'payment-failed',
'usage-limit-reached',
'usage-limit-reached-org',
],
Notifications: ['schedule-disabled', 'schedule-disabled-auth'],
}

const categoryHtml = Object.entries(categories)
const categoryHtml = Object.entries(PREVIEW_CATEGORIES)
.map(
([category, templates]) => `
<h2 style="margin-top: 24px; margin-bottom: 12px; font-size: 14px; color: #666; text-transform: uppercase; letter-spacing: 0.5px;">${category}</h2>
<ul style="list-style: none; padding: 0; margin: 0;">
${templates.map((t) => `<li style="margin: 8px 0;"><a href="?template=${t}" style="color: #33C482; text-decoration: none; font-size: 16px;">${t}</a></li>`).join('')}
</ul>
`
<section>
<h2>${category}</h2>
<div class="grid">
${templates
.map(
(t) => `
<figure>
<figcaption><span>${t}</span><a href="?template=${t}" target="_blank" rel="noreferrer">open ↗</a></figcaption>
<iframe src="?template=${t}" title="${t}" loading="lazy"></iframe>
</figure>`
)
.join('')}
</div>
</section>`
)
.join('')

return new NextResponse(
`<!DOCTYPE html>
<html>
<head>
<title>Email Previews</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Email Templates</title>
<style>
body { font-family: system-ui, -apple-system, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; }
h1 { color: #333; margin-bottom: 32px; }
a:hover { text-decoration: underline; }
:root { color-scheme: light; }
body { font-family: ${typography.systemFontFamily}; margin: 0; padding: 40px 24px 80px; background: ${colors.bgCard}; color: ${colors.textPrimary}; }
h1 { font-size: 24px; font-weight: 600; margin: 0 0 4px; }
.count { color: ${colors.textMuted}; font-size: 14px; margin: 0 0 40px; }
h2 { font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacing: .06em; color: ${colors.textMuted}; margin: 48px 0 16px; padding-bottom: 8px; border-bottom: 1px solid ${colors.border}; }
section { max-width: 1400px; margin: 0 auto; }
section > h2:first-child { margin-top: 0; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(640px, 1fr)); gap: 32px; }
figure { margin: 0 0 32px; }
figcaption { display: flex; justify-content: space-between; align-items: baseline; font-size: 13px; margin-bottom: 8px; }
figcaption span { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: ${colors.textBody}; }
figcaption a { color: ${colors.textMuted}; text-decoration: none; font-size: 12px; }
figcaption a:hover { color: ${colors.textPrimary}; }
iframe { width: 100%; height: 900px; border: 1px solid ${colors.border}; border-radius: 8px; background: ${colors.bgCard}; display: block; }
</style>
</head>
<body>
<h1>Email Templates</h1>
<p class="count">Every email Sim sends — ${Object.keys(emailTemplates).length} previews.</p>
${categoryHtml}
</body>
</html>`,
Expand Down
129 changes: 129 additions & 0 deletions apps/sim/components/emails/_styles/base.tokens.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/**
* Email styles cannot use CSS variables — clients strip them — so `base.ts`
* hardcodes hex copies of the platform tokens. Nothing else detects it when
* `globals.css`, `tailwind.config.ts`, or the chip chrome moves and the copies
* go stale, which is exactly how they drifted before. This suite is that
* detector.
*
* @vitest-environment node
*/
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { baseStyles, colors, typography } from '@/components/emails/_styles'

const APP_ROOT = join(__dirname, '../../..')

const globalsCss = readFileSync(join(APP_ROOT, 'app/_styles/globals.css'), 'utf8')
const tailwindConfig = readFileSync(join(APP_ROOT, 'tailwind.config.ts'), 'utf8')
const chipChrome = readFileSync(
join(APP_ROOT, '../../packages/emcn/src/components/chip/chip-chrome.ts'),
'utf8'
)

/**
* The light-mode `:root` block. Dark mode redefines the same names later in the
* file, and emails are light-only, so the FIRST definition is the one to read.
*/
function readCssVar(name: string): string {
const match = globalsCss.match(new RegExp(`--${name}:\\s*([^;]+);`))
if (!match) throw new Error(`--${name} not found in globals.css`)
return match[1].trim()
}

function readTailwindFontSize(name: string): string {
const match = tailwindConfig.match(new RegExp(`\\b${name}:\\s*'([^']+)'`))
if (!match) throw new Error(`fontSize.${name} not found in tailwind.config.ts`)
return match[1]
}

/** Every email color token and the platform variable it copies. */
const COLOR_MIRROR: Record<string, string> = {
bgOuter: 'surface-1',
bgCard: 'surface-2',
surfaceSubtle: 'surface-3',
textPrimary: 'text-primary',
textBody: 'text-body',
textMuted: 'text-muted',
textInverse: 'text-inverse',
border: 'border',
errorBg: 'terminal-status-error-bg',
errorBorder: 'error-muted',
footerBg: 'surface-1',
}

/**
* Tokens with no single CSS variable behind them. Each needs a stated reason —
* an entry here is a deliberate exception, not an oversight.
*/
const UNMIRRORED_COLORS: Record<string, string> = {
brandTertiary: 'Runtime-conditional on getBrandConfig(); neutral default equals --text-primary.',
}

describe('email color tokens mirror globals.css', () => {
for (const [token, cssVar] of Object.entries(COLOR_MIRROR)) {
it(`colors.${token} equals --${cssVar}`, () => {
expect(colors[token as keyof typeof colors]).toBe(readCssVar(cssVar))
})
}

it('every color token is either mirrored or has a written exemption', () => {
const accounted = new Set([...Object.keys(COLOR_MIRROR), ...Object.keys(UNMIRRORED_COLORS)])
const unaccounted = Object.keys(colors).filter((key) => !accounted.has(key))
expect(unaccounted).toEqual([])
})

it('exemptions state a reason', () => {
for (const reason of Object.values(UNMIRRORED_COLORS)) {
expect(reason.trim().length).toBeGreaterThan(0)
}
})
})

describe('email type scale mirrors tailwind.config.ts', () => {
it.each(['caption', 'base', 'md'])('fontSize.%s matches the Tailwind token', (name) => {
expect(typography.fontSize[name as 'caption' | 'base' | 'md']).toBe(readTailwindFontSize(name))
})

it('sm is Tailwind stock 14px — the size text-sm resolves to in chip chrome', () => {
expect(typography.fontSize.sm).toBe('14px')
expect(chipChrome).toContain('text-sm')
})

it('display is deliberately off-scale (no platform headline-numeral token)', () => {
expect(typography.fontSize.display).toBe('24px')
expect(tailwindConfig).not.toContain("'24px'")
})
})

describe('email geometry mirrors the platform', () => {
it('the card radius equals --radius', () => {
// --radius is authored in rem; emails need px.
expect(readCssVar('radius')).toBe('0.5rem')
expect(baseStyles.container.borderRadius).toBe('8px')
})

it('the CTA transcribes chipGeometryClass', () => {
const geometry = chipChrome.match(/chipGeometryClass = `([^`]+)`/)?.[1]
expect(geometry).toBeDefined()
expect(geometry).toContain('h-[30px]')
expect(geometry).toContain('rounded-lg')
expect(geometry).toContain('px-2')
expect(geometry).toContain('text-sm')

expect(baseStyles.button.lineHeight).toBe('30px')
expect(baseStyles.button.borderRadius).toBe('8px')
expect(baseStyles.button.padding).toBe('0 8px')
expect(baseStyles.button.fontSize).toBe(typography.fontSize.sm)
})
})

describe('email font weights stay on the platform scale', () => {
it('no token uses a weight outside 400/500/600', () => {
const offScale = Object.entries(baseStyles).filter(([, style]) => {
const weight = (style as { fontWeight?: unknown }).fontWeight
return weight !== undefined && ![400, 500, 600].includes(weight as number)
})
expect(offScale.map(([name]) => name)).toEqual([])
})
})
Loading
Loading