feat: Added platform emails for billing limits and disabled projects

This commit is contained in:
Dries Augustyns
2025-12-12 12:28:53 +01:00
parent cb40669385
commit 2485d2ff1d
29 changed files with 768 additions and 67 deletions
+9
View File
@@ -112,6 +112,15 @@ SMTP_DOMAIN=smtp.example.com
# Maximum recipients per email (default: 5) # Maximum recipients per email (default: 5)
# MAX_RECIPIENTS=5 # MAX_RECIPIENTS=5
# ========================================
# OPTIONAL: Platform emails
# ========================================
# Your Plunk instance will send emails if you provide a Plunk API key and a from address
# These emails include system notifications, for example when your project hits billing limits
# PLUNK_API_KEY=
# PLUNK_FROM_ADDRESS=
# ======================================== # ========================================
# ADVANCED (rarely needed) # ADVANCED (rarely needed)
# ======================================== # ========================================
+2
View File
@@ -145,6 +145,8 @@ Required for builds and deployment (see turbo.json and .env.example):
- Stripe (optional): `STRIPE_SK`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_PRICE_ONBOARDING`, `STRIPE_PRICE_EMAIL_USAGE`, - Stripe (optional): `STRIPE_SK`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_PRICE_ONBOARDING`, `STRIPE_PRICE_EMAIL_USAGE`,
`STRIPE_METER_EVENT_NAME` `STRIPE_METER_EVENT_NAME`
- Notifications (optional): `NTFY_URL` (ntfy.sh topic URL or self-hosted server for system notifications) - Notifications (optional): `NTFY_URL` (ntfy.sh topic URL or self-hosted server for system notifications)
- Platform Email Notifications (optional): `PLUNK_API_KEY` (enables email notifications to users for critical events like
project disabled, billing limits, etc. If not set, only ntfy notifications are sent)
**Important Notes:** **Important Notes:**
@@ -80,6 +80,7 @@ describe('Actions API Integration Tests', () => {
it('should validate subject and body required when no template', () => { it('should validate subject and body required when no template', () => {
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
to: '[email protected]', to: '[email protected]',
from: '[email protected]',
// Missing subject, body, and template // Missing subject, body, and template
}); });
@@ -169,6 +170,7 @@ describe('Actions API Integration Tests', () => {
it('should accept to as string (backward compatible)', () => { it('should accept to as string (backward compatible)', () => {
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
to: '[email protected]', to: '[email protected]',
from: '[email protected]',
subject: 'Test', subject: 'Test',
body: 'Test', body: 'Test',
}); });
@@ -182,6 +184,7 @@ describe('Actions API Integration Tests', () => {
name: 'Jane Doe', name: 'Jane Doe',
email: '[email protected]', email: '[email protected]',
}, },
from: '[email protected]',
subject: 'Test', subject: 'Test',
body: 'Test', body: 'Test',
}); });
@@ -194,6 +197,7 @@ describe('Actions API Integration Tests', () => {
to: { to: {
email: '[email protected]', email: '[email protected]',
}, },
from: '[email protected]',
subject: 'Test', subject: 'Test',
body: 'Test', body: 'Test',
}); });
@@ -204,6 +208,7 @@ describe('Actions API Integration Tests', () => {
it('should accept to as array of strings', () => { it('should accept to as array of strings', () => {
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
to: ['[email protected]', '[email protected]'], to: ['[email protected]', '[email protected]'],
from: '[email protected]',
subject: 'Test', subject: 'Test',
body: 'Test', body: 'Test',
}); });
@@ -217,6 +222,7 @@ describe('Actions API Integration Tests', () => {
{name: 'Jane Doe', email: '[email protected]'}, {name: 'Jane Doe', email: '[email protected]'},
{name: 'John Smith', email: '[email protected]'}, {name: 'John Smith', email: '[email protected]'},
], ],
from: '[email protected]',
subject: 'Test', subject: 'Test',
body: 'Test', body: 'Test',
}); });
@@ -227,6 +233,7 @@ describe('Actions API Integration Tests', () => {
it('should accept to as mixed array of strings and objects', () => { it('should accept to as mixed array of strings and objects', () => {
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
to: ['[email protected]', {name: 'John Smith', email: '[email protected]'}], to: ['[email protected]', {name: 'John Smith', email: '[email protected]'}],
from: '[email protected]',
subject: 'Test', subject: 'Test',
body: 'Test', body: 'Test',
}); });
+7 -1
View File
@@ -14,12 +14,13 @@ import {
GOOGLE_OAUTH_ENABLED, GOOGLE_OAUTH_ENABLED,
LANDING_URI, LANDING_URI,
NODE_ENV, NODE_ENV,
PLUNK_ENABLED,
PORT, PORT,
S3_ENABLED, S3_ENABLED,
SMTP_ENABLED, SMTP_ENABLED,
STRIPE_ENABLED, STRIPE_ENABLED,
TRACKING_TOGGLE_ENABLED, TRACKING_TOGGLE_ENABLED,
WIKI_URI, WIKI_URI
} from './app/constants.js'; } from './app/constants.js';
import {Actions} from './controllers/Actions.js'; import {Actions} from './controllers/Actions.js';
import {Activity} from './controllers/Activity.js'; import {Activity} from './controllers/Activity.js';
@@ -351,6 +352,11 @@ void prisma.$connect().then(async () => {
? 'Per-project tracking toggle enabled' ? 'Per-project tracking toggle enabled'
: 'Always tracking or always no-tracking', : 'Always tracking or always no-tracking',
}, },
{
name: 'Platform emails',
enabled: PLUNK_ENABLED,
details: PLUNK_ENABLED ? 'Platform email notifications enabled' : 'PLUNK_API_KEY not configured',
},
]; ];
const rows = features.map(f => ({ const rows = features.map(f => ({
+4
View File
@@ -94,3 +94,7 @@ export const SMTP_PORT_SUBMISSION = Number(validateEnv('PORT_SUBMISSION', '587')
// Enable SMTP features only when explicitly enabled via env or when a non-default domain is configured // Enable SMTP features only when explicitly enabled via env or when a non-default domain is configured
export const SMTP_ENABLED = export const SMTP_ENABLED =
process.env.SMTP_ENABLED === 'true' || (SMTP_DOMAIN !== 'localhost' && NODE_ENV !== 'development'); process.env.SMTP_ENABLED === 'true' || (SMTP_DOMAIN !== 'localhost' && NODE_ENV !== 'development');
export const PLUNK_API_KEY = validateEnv('PLUNK_API_KEY', '');
export const PLUNK_FROM_ADDRESS = validateEnv('PLUNK_FROM_ADDRESS', '');
export const PLUNK_ENABLED = PLUNK_API_KEY !== '' && PLUNK_FROM_ADDRESS !== '';
+15 -8
View File
@@ -9,7 +9,7 @@ import {ContactService} from '../services/ContactService.js';
import {DomainService} from '../services/DomainService.js'; import {DomainService} from '../services/DomainService.js';
import {EmailService} from '../services/EmailService.js'; import {EmailService} from '../services/EmailService.js';
import {EventService} from '../services/EventService.js'; import {EventService} from '../services/EventService.js';
import {NotFound} from '../exceptions/index.js'; import {NotFound, ValidationError} from '../exceptions/index.js';
import {CatchAsync} from '../utils/asyncHandler.js'; import {CatchAsync} from '../utils/asyncHandler.js';
/** /**
@@ -223,14 +223,21 @@ export class Actions {
templateId = templateRecord.id; templateId = templateRecord.id;
} }
// Verify 'from' domain is verified if provided if (!emailFrom) {
const senderEmail = emailFrom || '[email protected]'; // Default sender throw new ValidationError(
[
// Only verify custom domains (not the default [email protected]) {
if (emailFrom && emailFrom !== '[email protected]') { field: 'from',
await DomainService.verifyEmailDomain(emailFrom, auth.projectId); message: 'Sender email is required either in request or template',
code: 'required',
},
],
'Could not parse sender email',
);
} }
await DomainService.verifyEmailDomain(emailFrom, auth.projectId);
const replyToEmail = emailReplyTo; const replyToEmail = emailReplyTo;
const timestamp = new Date(); const timestamp = new Date();
@@ -281,7 +288,7 @@ export class Actions {
contactId: contact.id, contactId: contact.id,
subject: renderedSubject, subject: renderedSubject,
body: renderedBody, body: renderedBody,
from: senderEmail, from: emailFrom,
fromName: emailFromName, fromName: emailFromName,
toName: recipient.name, toName: recipient.name,
replyTo: replyToEmail, replyTo: replyToEmail,
+2 -1
View File
@@ -3,6 +3,7 @@ import signale from 'signale';
import {prisma} from '../database/prisma.js'; import {prisma} from '../database/prisma.js';
import {redis} from '../database/redis.js'; import {redis} from '../database/redis.js';
import {Keys} from './keys.js';
/** /**
* Activity types that can be tracked * Activity types that can be tracked
@@ -171,7 +172,7 @@ export class ActivityService {
*/ */
public static async getStats(projectId: string, startDate?: Date, endDate?: Date): Promise<ActivityStats> { public static async getStats(projectId: string, startDate?: Date, endDate?: Date): Promise<ActivityStats> {
// Try to get from cache // Try to get from cache
const cacheKey = `activity:stats:${projectId}:${startDate?.getTime() || 'all'}:${endDate?.getTime() || 'now'}`; const cacheKey = Keys.Activity.stats(projectId, startDate?.getTime() || 'all', endDate?.getTime() || 'now');
try { try {
const cached = await redis.get(cacheKey); const cached = await redis.get(cacheKey);
+4 -3
View File
@@ -1,5 +1,6 @@
import {prisma} from '../database/prisma.js'; import {prisma} from '../database/prisma.js';
import {redis} from '../database/redis.js'; import {redis} from '../database/redis.js';
import {Keys} from './keys.js';
/** /**
* Time series data point for analytics * Time series data point for analytics
@@ -57,7 +58,7 @@ export class AnalyticsService {
const limitedStartDate = effectiveStartDate < maxStartDate ? maxStartDate : effectiveStartDate; const limitedStartDate = effectiveStartDate < maxStartDate ? maxStartDate : effectiveStartDate;
// Check cache first // Check cache first
const cacheKey = `analytics:timeseries:${projectId}:${limitedStartDate.toISOString()}:${effectiveEndDate.toISOString()}`; const cacheKey = Keys.Analytics.timeseries(projectId, limitedStartDate.toISOString(), effectiveEndDate.toISOString());
const cached = await redis.get(cacheKey); const cached = await redis.get(cacheKey);
if (cached) { if (cached) {
return JSON.parse(cached); return JSON.parse(cached);
@@ -190,7 +191,7 @@ export class AnalyticsService {
const effectiveEndDate = endDate || now; const effectiveEndDate = endDate || now;
// Check cache // Check cache
const cacheKey = `analytics:campaignStats:${projectId}:${effectiveStartDate.toISOString()}:${effectiveEndDate.toISOString()}`; const cacheKey = Keys.Analytics.campaignStats(projectId, effectiveStartDate.toISOString(), effectiveEndDate.toISOString());
const cached = await redis.get(cacheKey); const cached = await redis.get(cacheKey);
if (cached) { if (cached) {
return JSON.parse(cached); return JSON.parse(cached);
@@ -294,7 +295,7 @@ export class AnalyticsService {
const effectiveEndDate = endDate || now; const effectiveEndDate = endDate || now;
// Check cache // Check cache
const cacheKey = `analytics:topEvents:${projectId}:${limit}:${effectiveStartDate.toISOString()}:${effectiveEndDate.toISOString()}`; const cacheKey = Keys.Analytics.topEvents(projectId, limit, effectiveStartDate.toISOString(), effectiveEndDate.toISOString());
const cached = await redis.get(cacheKey); const cached = await redis.get(cacheKey);
if (cached) { if (cached) {
return JSON.parse(cached); return JSON.parse(cached);
+138 -3
View File
@@ -1,10 +1,13 @@
import {EmailSourceType} from '@plunk/db'; import {EmailSourceType} from '@plunk/db';
import {BillingLimitExceededEmail, BillingLimitWarningEmail, sendPlatformEmail} from '@plunk/email';
import React from 'react';
import signale from 'signale'; import signale from 'signale';
import {STRIPE_ENABLED} from '../app/constants.js'; import {DASHBOARD_URI, LANDING_URI, STRIPE_ENABLED} from '../app/constants.js';
import {stripe} from '../app/stripe.js'; import {stripe} from '../app/stripe.js';
import {prisma} from '../database/prisma.js'; import {prisma} from '../database/prisma.js';
import {redis} from '../database/redis.js'; import {redis} from '../database/redis.js';
import {Keys} from './keys.js';
import {NtfyService} from './NtfyService.js'; import {NtfyService} from './NtfyService.js';
/** /**
@@ -238,6 +241,9 @@ export class BillingLimitService {
EmailSourceType.TRANSACTIONAL, // Use generic type for notification EmailSourceType.TRANSACTIONAL, // Use generic type for notification
); );
// Send email notification
await this.sendLimitExceededEmail(projectId, project.name, totalUsage, freeLimit, 'Free Tier (All Types)');
return { return {
allowed: false, allowed: false,
warning: false, warning: false,
@@ -259,6 +265,16 @@ export class BillingLimitService {
percentage, percentage,
EmailSourceType.TRANSACTIONAL, // Use generic type for notification EmailSourceType.TRANSACTIONAL, // Use generic type for notification
); );
// Send email notification (only once per month)
await this.sendWarningEmail(
projectId,
project.name,
totalUsage,
freeLimit,
percentage,
'Free Tier (All Types)',
);
} }
return { return {
@@ -299,6 +315,9 @@ export class BillingLimitService {
if (project) { if (project) {
// Send notification about limit exceeded // Send notification about limit exceeded
await NtfyService.notifyBillingLimitExceeded(project.name, projectId, usage, limit, sourceType); await NtfyService.notifyBillingLimitExceeded(project.name, projectId, usage, limit, sourceType);
// Send email notification
await this.sendLimitExceededEmail(projectId, project.name, usage, limit, sourceType);
} }
return { return {
@@ -322,7 +341,17 @@ export class BillingLimitService {
}); });
if (project) { if (project) {
await NtfyService.notifyBillingLimitApproaching(project.name, projectId, usage, limit, percentage, sourceType); await NtfyService.notifyBillingLimitApproaching(
project.name,
projectId,
usage,
limit,
percentage,
sourceType,
);
// Send email notification (only once per month)
await this.sendWarningEmail(projectId, project.name, usage, limit, percentage, sourceType);
} }
} }
@@ -484,7 +513,7 @@ export class BillingLimitService {
const now = new Date(); const now = new Date();
const year = now.getFullYear(); const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); const month = String(now.getMonth() + 1).padStart(2, '0');
return `billing:usage:${projectId}:${sourceType}:${year}-${month}`; return Keys.Billing.usage(projectId, sourceType, year, month);
} }
/** /**
@@ -496,4 +525,110 @@ export class BillingLimitService {
const end = new Date(now.getFullYear(), now.getMonth() + 1, 1); const end = new Date(now.getFullYear(), now.getMonth() + 1, 1);
return {start, end}; return {start, end};
} }
/**
* Send billing limit warning email to project members
*/
private static async sendWarningEmail(
projectId: string,
projectName: string,
usage: number,
limit: number,
percentage: number,
sourceType: string,
): Promise<void> {
try {
// Check if we've already sent this warning email this month
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const cacheKey = Keys.Billing.warningEmail(projectId, sourceType, year, month);
const alreadySent = await redis.get(cacheKey);
if (alreadySent === '1') {
return;
}
const members = await prisma.membership.findMany({
where: {projectId},
include: {user: {select: {email: true}}},
});
const emails = members.map(m => m.user.email);
if (emails.length === 0) {
return;
}
const template = React.createElement(BillingLimitWarningEmail, {
projectName,
projectId,
usage,
limit,
percentage,
sourceType,
dashboardUrl: DASHBOARD_URI,
landingUrl: LANDING_URI,
});
await Promise.all(emails.map(email => sendPlatformEmail(email, 'Billing Limit Warning', template)));
// Mark that we've sent the warning email (expires at end of month)
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
await redis.setex(cacheKey, ttl, '1');
} catch (error) {
signale.error(`[BILLING_LIMIT] Failed to send warning email:`, error);
}
}
/**
* Send billing limit exceeded email to project members
*/
private static async sendLimitExceededEmail(
projectId: string,
projectName: string,
usage: number,
limit: number,
sourceType: string,
): Promise<void> {
try {
// Check if we've already sent this warning email this month
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const cacheKey = Keys.Billing.limitEmail(projectId, sourceType, year, month);
const alreadySent = await redis.get(cacheKey);
if (alreadySent === '1') {
return;
}
const members = await prisma.membership.findMany({
where: {projectId},
include: {user: {select: {email: true}}},
});
const emails = members.map(m => m.user.email);
if (emails.length === 0) {
return;
}
const template = React.createElement(BillingLimitExceededEmail, {
projectName,
projectId,
usage,
limit,
sourceType,
dashboardUrl: DASHBOARD_URI,
landingUrl: LANDING_URI,
});
await Promise.all(emails.map(email => sendPlatformEmail(email, 'Billing Limit Exceeded', template)));
// Mark that we've sent the limit email (expires at end of month)
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
await redis.setex(cacheKey, ttl, '1');
} catch (error) {
signale.error(`[BILLING_LIMIT] Failed to send limit exceeded email:`, error);
}
}
} }
+3 -2
View File
@@ -5,6 +5,7 @@ import signale from 'signale';
import {prisma} from '../database/prisma.js'; import {prisma} from '../database/prisma.js';
import {redis} from '../database/redis.js'; import {redis} from '../database/redis.js';
import {Keys} from './keys.js';
import {WorkflowExecutionService} from './WorkflowExecutionService.js'; import {WorkflowExecutionService} from './WorkflowExecutionService.js';
@@ -49,7 +50,7 @@ export class EventService {
* Should be called when workflows are enabled/disabled or updated * Should be called when workflows are enabled/disabled or updated
*/ */
public static async invalidateWorkflowCache(projectId: string): Promise<void> { public static async invalidateWorkflowCache(projectId: string): Promise<void> {
const cacheKey = `workflows:enabled:${projectId}`; const cacheKey = Keys.Workflow.enabled(projectId);
try { try {
await redis.del(cacheKey); await redis.del(cacheKey);
} catch (error) { } catch (error) {
@@ -323,7 +324,7 @@ export class EventService {
data?: Record<string, unknown>, data?: Record<string, unknown>,
): Promise<void> { ): Promise<void> {
// Try to get workflows from cache // Try to get workflows from cache
const cacheKey = `workflows:enabled:${projectId}`; const cacheKey = Keys.Workflow.enabled(projectId);
let workflows; let workflows;
try { try {
+29 -10
View File
@@ -1,9 +1,13 @@
import {ProjectDisabledEmail, sendPlatformEmail} from '@plunk/email';
import React from 'react';
import signale from 'signale'; import signale from 'signale';
import {prisma} from '../database/prisma.js'; import {prisma} from '../database/prisma.js';
import {redis} from '../database/redis.js'; import {redis} from '../database/redis.js';
import {Keys} from './keys.js';
import {NtfyService} from './NtfyService.js'; import {NtfyService} from './NtfyService.js';
import {QueueService} from './QueueService.js'; import {QueueService} from './QueueService.js';
import {DASHBOARD_URI, LANDING_URI} from '../app/constants.js';
/** /**
* Security thresholds for bounce and complaint rates * Security thresholds for bounce and complaint rates
@@ -45,7 +49,6 @@ interface SecurityStatus {
} }
export class SecurityService { export class SecurityService {
private static readonly CACHE_PREFIX = 'security';
private static readonly CACHE_TTL = 300; // 5 minutes private static readonly CACHE_TTL = 300; // 5 minutes
/** /**
@@ -54,7 +57,7 @@ export class SecurityService {
public static async getSecurityStatus(projectId: string): Promise<SecurityStatus> { public static async getSecurityStatus(projectId: string): Promise<SecurityStatus> {
try { try {
// Try to get from cache first // Try to get from cache first
const cacheKey = this.getCacheKey(projectId, 'rates'); const cacheKey = Keys.Security.rates(projectId);
const cached = await redis.get(cacheKey); const cached = await redis.get(cacheKey);
if (cached) { if (cached) {
@@ -137,7 +140,7 @@ export class SecurityService {
*/ */
public static async invalidateCache(projectId: string): Promise<void> { public static async invalidateCache(projectId: string): Promise<void> {
try { try {
const cacheKey = this.getCacheKey(projectId, 'rates'); const cacheKey = Keys.Security.rates(projectId);
await redis.del(cacheKey); await redis.del(cacheKey);
} catch (error) { } catch (error) {
signale.error(`[SECURITY] Failed to invalidate cache for project ${projectId}:`, error); signale.error(`[SECURITY] Failed to invalidate cache for project ${projectId}:`, error);
@@ -167,13 +170,6 @@ export class SecurityService {
}; };
} }
/**
* Get cache key for security metrics
*/
private static getCacheKey(projectId: string, type: 'rates'): string {
return `${this.CACHE_PREFIX}:${projectId}:${type}`;
}
/** /**
* Calculate bounce and complaint rates for a project * Calculate bounce and complaint rates for a project
*/ */
@@ -345,6 +341,29 @@ export class SecurityService {
// Send urgent notification about project suspension // Send urgent notification about project suspension
await NtfyService.notifyProjectDisabledForSecurity(project.name, projectId, status.violations); await NtfyService.notifyProjectDisabledForSecurity(project.name, projectId, status.violations);
// Send email notification to project members
try {
const members = await prisma.membership.findMany({
where: {projectId},
include: {user: {select: {email: true}}},
});
const emails = members.map(m => m.user.email);
if (emails.length > 0) {
const template = React.createElement(ProjectDisabledEmail, {
projectName: project.name,
projectId,
violations: status.violations,
dashboardUrl: DASHBOARD_URI,
landingUrl: LANDING_URI,
});
await Promise.all(
emails.map(email => sendPlatformEmail(email, 'Project Disabled - Security Risk', template)),
);
}
} catch (emailError) {
signale.error(`[SECURITY] Failed to send project disabled email:`, emailError);
}
} catch (error) { } catch (error) {
signale.error(`[SECURITY] Failed to disable project ${projectId}:`, error); signale.error(`[SECURITY] Failed to disable project ${projectId}:`, error);
} }
@@ -1,4 +1,4 @@
import {describe, it, expect, beforeEach, vi} from 'vitest'; import {beforeEach, describe, expect, it, vi} from 'vitest';
import {EmailSourceType, EmailStatus} from '@plunk/db'; import {EmailSourceType, EmailStatus} from '@plunk/db';
import {ActionSchemas} from '@plunk/shared'; import {ActionSchemas} from '@plunk/shared';
import {EmailService} from '../EmailService'; import {EmailService} from '../EmailService';
@@ -669,7 +669,6 @@ describe('EmailService', () => {
// ======================================== // ========================================
describe('Attachment Schema Validation', () => { describe('Attachment Schema Validation', () => {
it('should validate attachment count limit (max 10)', () => { it('should validate attachment count limit (max 10)', () => {
const tooManyAttachments = Array.from({length: 11}, (_, i) => ({ const tooManyAttachments = Array.from({length: 11}, (_, i) => ({
filename: `file${i}.txt`, filename: `file${i}.txt`,
content: Buffer.from('content').toString('base64'), content: Buffer.from('content').toString('base64'),
@@ -690,7 +689,6 @@ describe('EmailService', () => {
}); });
it('should validate attachment size limit (10MB total)', () => { it('should validate attachment size limit (10MB total)', () => {
// Exceeds ~13.3M base64 chars limit // Exceeds ~13.3M base64 chars limit
const largeContent = 'A'.repeat(14000000); const largeContent = 'A'.repeat(14000000);
@@ -711,11 +709,11 @@ describe('EmailService', () => {
}); });
it('should accept attachments within size limit', () => { it('should accept attachments within size limit', () => {
const validContent = Buffer.from('Small file content').toString('base64'); const validContent = Buffer.from('Small file content').toString('base64');
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
to: '[email protected]', to: '[email protected]',
from: '[email protected]',
subject: 'Test', subject: 'Test',
body: 'Test', body: 'Test',
attachments: [ attachments: [
@@ -731,7 +729,6 @@ describe('EmailService', () => {
}); });
it('should reject attachment with missing required fields', () => { it('should reject attachment with missing required fields', () => {
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
to: '[email protected]', to: '[email protected]',
subject: 'Test', subject: 'Test',
@@ -748,7 +745,6 @@ describe('EmailService', () => {
}); });
it('should reject attachment with empty filename', () => { it('should reject attachment with empty filename', () => {
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
to: '[email protected]', to: '[email protected]',
subject: 'Test', subject: 'Test',
@@ -766,7 +762,6 @@ describe('EmailService', () => {
}); });
it('should reject attachment with filename exceeding 255 chars', () => { it('should reject attachment with filename exceeding 255 chars', () => {
const tooLongFilename = 'a'.repeat(256) + '.pdf'; const tooLongFilename = 'a'.repeat(256) + '.pdf';
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
@@ -786,18 +781,12 @@ describe('EmailService', () => {
}); });
it('should accept valid attachment with various content types', () => { it('should accept valid attachment with various content types', () => {
const contentTypes = ['application/pdf', 'image/png', 'image/jpeg', 'text/plain', 'application/zip'];
const contentTypes = [
'application/pdf',
'image/png',
'image/jpeg',
'text/plain',
'application/zip',
];
for (const contentType of contentTypes) { for (const contentType of contentTypes) {
const result = ActionSchemas.send.safeParse({ const result = ActionSchemas.send.safeParse({
to: '[email protected]', to: '[email protected]',
from: '[email protected]',
subject: 'Test', subject: 'Test',
body: 'Test', body: 'Test',
attachments: [ attachments: [
@@ -1,6 +1,7 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {WorkflowExecutionStatus, WorkflowTriggerType} from '@plunk/db'; import {WorkflowExecutionStatus, WorkflowTriggerType} from '@plunk/db';
import {EventService} from '../EventService'; import {EventService} from '../EventService';
import {Keys} from '../keys';
import {factories, getPrismaClient} from '../../../../../test/helpers'; import {factories, getPrismaClient} from '../../../../../test/helpers';
// Mock Redis for caching tests - must be inline to avoid hoisting issues // Mock Redis for caching tests - must be inline to avoid hoisting issues
@@ -503,7 +504,7 @@ describe('EventService', () => {
const {redis} = await import('../../database/redis'); const {redis} = await import('../../database/redis');
// Set cache // Set cache
const cacheKey = `workflows:enabled:${projectId}`; const cacheKey = Keys.Workflow.enabled(projectId);
await redis.set(cacheKey, JSON.stringify([{id: 'test'}])); await redis.set(cacheKey, JSON.stringify([{id: 'test'}]));
// Verify cache exists // Verify cache exists
@@ -1,6 +1,7 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {WorkflowExecutionStatus, WorkflowStepType, WorkflowTriggerType} from '@plunk/db'; import {WorkflowExecutionStatus, WorkflowStepType, WorkflowTriggerType} from '@plunk/db';
import {WorkflowService} from '../WorkflowService'; import {WorkflowService} from '../WorkflowService';
import {Keys} from '../keys';
import {factories, getPrismaClient} from '../../../../../test/helpers'; import {factories, getPrismaClient} from '../../../../../test/helpers';
// Mock Redis for caching tests - must be inline to avoid hoisting issues // Mock Redis for caching tests - must be inline to avoid hoisting issues
@@ -130,7 +131,7 @@ describe('WorkflowService', () => {
it('should invalidate cache when creating enabled workflow', async () => { it('should invalidate cache when creating enabled workflow', async () => {
const {redis} = await import('../../database/redis'); const {redis} = await import('../../database/redis');
const cacheKey = `workflows:enabled:${projectId}`; const cacheKey = Keys.Workflow.enabled(projectId);
// Set cache // Set cache
await redis.set(cacheKey, JSON.stringify([{id: 'old'}])); await redis.set(cacheKey, JSON.stringify([{id: 'old'}]));
@@ -286,7 +287,7 @@ describe('WorkflowService', () => {
it('should invalidate cache when enabling workflow', async () => { it('should invalidate cache when enabling workflow', async () => {
const {redis} = await import('../../database/redis'); const {redis} = await import('../../database/redis');
const cacheKey = `workflows:enabled:${projectId}`; const cacheKey = Keys.Workflow.enabled(projectId);
const workflow = await factories.createWorkflow({ const workflow = await factories.createWorkflow({
projectId, projectId,
@@ -326,7 +327,7 @@ describe('WorkflowService', () => {
it('should invalidate cache when deleting enabled workflow', async () => { it('should invalidate cache when deleting enabled workflow', async () => {
const {redis} = await import('../../database/redis'); const {redis} = await import('../../database/redis');
const cacheKey = `workflows:enabled:${projectId}`; const cacheKey = Keys.Workflow.enabled(projectId);
const workflow = await factories.createWorkflow({ const workflow = await factories.createWorkflow({
projectId, projectId,
+37
View File
@@ -15,4 +15,41 @@ export const Keys = {
return `domain:project:${projectId}`; return `domain:project:${projectId}`;
}, },
}, },
Billing: {
usage(projectId: string, sourceType: string, year: number, month: string): string {
return `billing:usage:${projectId}:${sourceType}:${year}-${month}`;
},
warningEmail(projectId: string, sourceType: string, year: number, month: string): string {
return `billing:warning_email:${projectId}:${sourceType}:${year}-${month}`;
},
limitEmail(projectId: string, sourceType: string, year: number, month: string): string {
return `billing:limit_email:${projectId}:${sourceType}:${year}-${month}`;
},
},
Security: {
rates(projectId: string): string {
return `security:${projectId}:rates`;
},
},
Activity: {
stats(projectId: string, startTime: number | string, endTime: number | string): string {
return `activity:stats:${projectId}:${startTime}:${endTime}`;
},
},
Analytics: {
timeseries(projectId: string, startDate: string, endDate: string): string {
return `analytics:timeseries:${projectId}:${startDate}:${endDate}`;
},
campaignStats(projectId: string, startDate: string, endDate: string): string {
return `analytics:campaignStats:${projectId}:${startDate}:${endDate}`;
},
topEvents(projectId: string, limit: number, startDate: string, endDate: string): string {
return `analytics:topEvents:${projectId}:${limit}:${startDate}:${endDate}`;
},
},
Workflow: {
enabled(projectId: string): string {
return `workflows:enabled:${projectId}`;
},
},
} as const; } as const;
+2 -2
View File
@@ -406,7 +406,7 @@ const UsageDisplay = memo(function UsageDisplay({category, usage, currency}: Usa
<Alert className="mt-3 bg-red-50 border-red-200 text-red-900"> <Alert className="mt-3 bg-red-50 border-red-200 text-red-900">
<AlertCircle className="h-4 w-4" /> <AlertCircle className="h-4 w-4" />
<div className="ml-2"> <div className="ml-2">
<p className="text-xs"> <p className={'text-sm'}>
<strong>Limit reached:</strong> No more {category.toLowerCase()} emails can be sent this month. <strong>Limit reached:</strong> No more {category.toLowerCase()} emails can be sent this month.
</p> </p>
</div> </div>
@@ -417,7 +417,7 @@ const UsageDisplay = memo(function UsageDisplay({category, usage, currency}: Usa
<Alert className="mt-3 bg-orange-50 border-orange-200 text-orange-900"> <Alert className="mt-3 bg-orange-50 border-orange-200 text-orange-900">
<AlertTriangle className="h-4 w-4" /> <AlertTriangle className="h-4 w-4" />
<div className="ml-2"> <div className="ml-2">
<p className="text-xs"> <p className="text-sm">
<strong>Warning:</strong> You&apos;ve used {Math.round(usage.percentage)}% of your{' '} <strong>Warning:</strong> You&apos;ve used {Math.round(usage.percentage)}% of your{' '}
{category.toLowerCase()} email limit. {category.toLowerCase()} email limit.
</p> </p>
+2 -1
View File
@@ -21,7 +21,8 @@
"dependencies": { "dependencies": {
"@plunk/db": "*", "@plunk/db": "*",
"@plunk/types": "*", "@plunk/types": "*",
"@react-email/components": "^1.0.0" "@react-email/components": "^1.0.0",
"@react-email/tailwind": "^2.0.1"
}, },
"exports": { "exports": {
".": "./dist/index.js" ".": "./dist/index.js"
+58
View File
@@ -0,0 +1,58 @@
import {Body, Container, Head, Html, Tailwind} from '@react-email/components';
import * as React from 'react';
interface EmailLayoutProps {
children: React.ReactNode;
}
const tailwindConfig = {
theme: {
extend: {
colors: {
brand: {
50: '#eff6ff',
100: '#dbeafe',
200: '#bfdbfe',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
900: '#1e3a8a',
},
},
fontFamily: {
sans: [
'ui-sans-serif',
'system-ui',
'-apple-system',
'BlinkMacSystemFont',
'Segoe UI',
'Roboto',
'Helvetica Neue',
'Arial',
'sans-serif',
],
},
},
},
};
export function EmailLayout({children}: EmailLayoutProps) {
return (
<Tailwind config={tailwindConfig}>
<Html>
<Head>
<meta name="color-scheme" content="light" />
<meta name="supported-color-schemes" content="light" />
</Head>
<Body className="m-0 bg-gray-50 p-0 font-sans antialiased">
<Container
className="mx-auto my-8 max-w-[600px] overflow-hidden rounded-lg bg-white shadow-sm"
style={{border: '1px solid #e5e7eb'}}
>
{children}
</Container>
</Body>
</Html>
</Tailwind>
);
}
+41
View File
@@ -0,0 +1,41 @@
import {Link, Section, Text} from '@react-email/components';
import * as React from 'react';
interface FooterProps {
projectId?: string;
landingUrl?: string;
}
export function Footer({projectId, landingUrl = 'https://www.useplunk.com'}: FooterProps) {
return (
<Section className="border-t border-gray-100 bg-gray-50 px-8 py-8">
<Text className="mb-4 mt-0 text-center text-xs leading-relaxed text-gray-600">
This email was sent by Plunk. .
</Text>
{projectId && (
<Text className="mb-4 mt-0 text-center text-xs leading-relaxed text-gray-400">
Project ID: <span className="font-mono">{projectId}</span>
</Text>
)}
<Text className="mb-0 mt-0 text-center text-xs leading-relaxed text-gray-500">
<Link href={landingUrl} className="text-gray-500 no-underline hover:text-gray-700">
Plunk
</Link>
{' • '}
<Link
href={`${landingUrl}/privacy`}
className="text-gray-500 no-underline hover:text-gray-700"
>
Privacy
</Link>
{' • '}
<Link
href={`${landingUrl}/terms`}
className="text-gray-500 no-underline hover:text-gray-700"
>
Terms
</Link>
</Text>
</Section>
);
}
+10 -4
View File
@@ -1,10 +1,16 @@
import {Img} from '@react-email/components'; import {Img, Section} from '@react-email/components';
import * as React from 'react'; import * as React from 'react';
export function Header() { export function Header() {
return ( return (
<> <Section className="border-b border-gray-100 bg-white px-8 py-8">
<Img src="https://www.swyp.be/favicon/web-app-manifest-192x192.png" alt="Swyp Logo" width="40" height="40" /> <Img
</> src="https://next.useplunk.com/assets/logo.png"
alt="Plunk"
width="40"
height="40"
className="mx-auto"
/>
</Section>
); );
} }
@@ -0,0 +1,115 @@
import {Heading, Link, Section, Text} from '@react-email/components';
import * as React from 'react';
import {EmailLayout} from '../common/EmailLayout';
import {Footer} from '../common/Footer';
import {Header} from '../common/Header';
interface BillingLimitExceededEmailProps {
projectName: string;
projectId: string;
usage: number;
limit: number;
sourceType: string;
dashboardUrl?: string;
landingUrl?: string;
}
export function BillingLimitExceededEmail({
projectName = 'My Project',
projectId = 'proj_example123',
usage = 10000,
limit = 10000,
sourceType = 'Transactional',
dashboardUrl = 'https://app.useplunk.com',
landingUrl = 'https://www.useplunk.com',
}: BillingLimitExceededEmailProps) {
return (
<EmailLayout>
<Header />
<Section className="px-8 pb-10 pt-10">
<Heading className="mb-2 mt-0 text-2xl font-semibold tracking-tight text-gray-900">
Email sending paused
</Heading>
<Text className="mb-8 mt-0 text-base leading-relaxed text-gray-600">
Your project <strong className="font-medium text-gray-900">{projectName}</strong> has reached your configured
monthly billing limit. Email sending has been paused to prevent charges beyond your set limit.
</Text>
<Section className="mb-8 overflow-hidden rounded-lg" style={{border: '1px solid #e5e7eb'}}>
<Section className="bg-gray-50 px-6 py-4">
<Text className="mb-0 mt-0 text-xs font-medium uppercase tracking-wider text-gray-500">
Usage this month
</Text>
</Section>
<Section className="px-6 py-6">
<Section className="mb-6">
<Section className="mb-2 flex items-baseline justify-between">
<Text className="mb-0 mt-0 text-sm text-gray-600">Emails sent</Text>
<Text className="mb-0 mt-0 text-sm font-medium text-gray-900">
{usage.toLocaleString()} / {limit.toLocaleString()}
</Text>
</Section>
<Section className="h-2 overflow-hidden rounded-full bg-gray-200">
<Section className="h-full bg-gray-900" style={{width: '100%'}} />
</Section>
</Section>
<Text className="mb-0 mt-0 text-xs text-gray-500">{sourceType} emails</Text>
</Section>
</Section>
<Section className="mb-8 rounded-lg bg-red-50 px-6 py-4" style={{border: '1px solid #fca5a5'}}>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-red-900">
All email sending is currently blocked. Your usage will reset at the start of next month, or you can
increase your billing limit to resume immediately.
</Text>
</Section>
<Heading className="mb-4 mt-0 text-lg font-semibold text-gray-900">How to resume sending</Heading>
<Section className="mb-8">
<Section className="mb-3">
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Increase your billing limit</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Resume sending immediately by adjusting your monthly limit in billing settings
</Text>
</Section>
<Section className="mb-3">
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Wait for monthly reset</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Your usage will automatically reset at the start of next month
</Text>
</Section>
<Section>
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Contact support</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Need immediate help? Our team is here to assist you
</Text>
</Section>
</Section>
<Section className="mb-6">
<Link
href={`${dashboardUrl}/settings?tab=billing`}
className="inline-block rounded-md bg-gray-900 px-6 py-3 text-sm font-medium text-white no-underline"
>
Adjust billing limit
</Link>
</Section>
<Section>
<Link href={dashboardUrl} className="text-sm text-gray-500" style={{textDecoration: 'none'}}>
View project dashboard
</Link>
</Section>
</Section>
<Footer projectId={projectId} landingUrl={landingUrl} />
</EmailLayout>
);
}
export default BillingLimitExceededEmail;
@@ -0,0 +1,119 @@
import {Heading, Link, Section, Text} from '@react-email/components';
import * as React from 'react';
import {EmailLayout} from '../common/EmailLayout';
import {Footer} from '../common/Footer';
import {Header} from '../common/Header';
interface BillingLimitWarningEmailProps {
projectName: string;
projectId: string;
usage: number;
limit: number;
percentage: number;
sourceType: string;
dashboardUrl?: string;
landingUrl?: string;
}
export function BillingLimitWarningEmail({
projectName = 'My Project',
projectId = 'proj_example123',
usage = 8500,
limit = 10000,
percentage = 85,
sourceType = 'Transactional',
dashboardUrl = 'https://app.useplunk.com',
landingUrl = 'https://www.useplunk.com',
}: BillingLimitWarningEmailProps) {
const percentageRounded = Math.round(percentage);
const remaining = limit - usage;
return (
<EmailLayout>
<Header />
<Section className="px-8 pb-10 pt-10">
<Heading className="mb-2 mt-0 text-2xl font-semibold tracking-tight text-gray-900">Usage limit warning</Heading>
<Text className="mb-8 mt-0 text-base leading-relaxed text-gray-600">
Your project <strong className="font-medium text-gray-900">{projectName}</strong> has used{' '}
<strong className="font-medium text-gray-900">{percentageRounded}%</strong> of your configured monthly billing
limit.
</Text>
<Section className="mb-8 overflow-hidden rounded-lg" style={{border: '1px solid #e5e7eb'}}>
<Section className="bg-gray-50 px-6 py-4">
<Text className="mb-0 mt-0 text-xs font-medium uppercase tracking-wider text-gray-500">
Usage this month
</Text>
</Section>
<Section className="px-6 py-6">
<Section className="mb-6">
<Section className="mb-2 flex items-baseline justify-between">
<Text className="mb-0 mt-0 text-sm text-gray-600">Emails sent</Text>
<Text className="mb-0 mt-0 text-sm font-medium text-gray-900">
{usage.toLocaleString()} / {limit.toLocaleString()}
</Text>
</Section>
<Section className="h-2 overflow-hidden rounded-full bg-gray-200">
<div className="h-full bg-gray-900" style={{width: `${percentageRounded}%`, height: '100%'}} />
</Section>
</Section>
<Text className="mb-0 mt-0 text-xs text-gray-500">{sourceType} emails</Text>
</Section>
</Section>
<Section className="mb-8 rounded-lg bg-amber-50 px-6 py-4" style={{border: '1px solid #fbbf24'}}>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-amber-900">
When you reach 100%, email sending will be paused to prevent charges beyond your configured limit. Your
usage will reset at the start of next month.
</Text>
</Section>
<Heading className="mb-4 mt-0 text-lg font-semibold text-gray-900">Recommended actions</Heading>
<Section className="mb-8">
<Section className="mb-3">
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Increase your billing limit</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Adjust your monthly limit in billing settings to continue sending
</Text>
</Section>
<Section className="mb-3">
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Monitor your usage</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Track your sending patterns in the dashboard
</Text>
</Section>
<Section>
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Optimize your sending</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Review and reduce email volume where possible
</Text>
</Section>
</Section>
<Section className="mb-6">
<Link
href={`${dashboardUrl}/settings?tab=billing`}
className="inline-block rounded-md bg-gray-900 px-6 py-3 text-sm font-medium text-white no-underline"
>
Adjust billing limit
</Link>
</Section>
<Section>
<Link href={dashboardUrl} className="text-sm text-gray-500" style={{textDecoration: 'none'}}>
View project dashboard
</Link>
</Section>
</Section>
<Footer projectId={projectId} landingUrl={landingUrl} />
</EmailLayout>
);
}
export default BillingLimitWarningEmail;
@@ -0,0 +1,96 @@
import {Heading, Link, Section, Text} from '@react-email/components';
import * as React from 'react';
import {EmailLayout} from '../common/EmailLayout';
import {Footer} from '../common/Footer';
import {Header} from '../common/Header';
interface ProjectDisabledEmailProps {
projectName: string;
projectId: string;
violations: string[];
dashboardUrl?: string;
landingUrl?: string;
}
export function ProjectDisabledEmail({
projectName = 'My Project',
projectId = 'proj_example123',
violations = ['Bounce rate exceeded 10% threshold', 'Complaint rate exceeded 0.5% threshold'],
dashboardUrl = 'https://app.useplunk.com',
landingUrl = 'https://www.useplunk.com',
}: ProjectDisabledEmailProps) {
return (
<EmailLayout>
<Header />
<Section className="px-8 pb-10 pt-10">
<Heading className="mb-2 mt-0 text-2xl font-semibold tracking-tight text-gray-900">Project disabled</Heading>
<Text className="mb-8 mt-0 text-base leading-relaxed text-gray-600">
Your project <strong className="font-medium text-gray-900">{projectName}</strong> has been automatically
disabled to protect your sender reputation.
</Text>
<Section className="mb-8 overflow-hidden rounded-lg" style={{border: '1px solid #e5e7eb'}}>
<Section className="bg-gray-50 px-6 py-4">
<Text className="mb-0 mt-0 text-xs font-medium uppercase tracking-wider text-gray-500">
Issues detected
</Text>
</Section>
<Section className="px-6 py-6">
{violations.map((violation, index) => (
<Section key={index} className="mb-3 last:mb-0">
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-700">{violation}</Text>
</Section>
))}
</Section>
</Section>
<Section className="mb-8 rounded-lg bg-red-50 px-6 py-4" style={{border: '1px solid #fca5a5'}}>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-red-900">
High bounce or complaint rates can severely damage your sender reputation and email deliverability. We've
disabled your project to prevent further issues.
</Text>
</Section>
<Heading className="mb-4 mt-0 text-lg font-semibold text-gray-900">Steps to restore your project</Heading>
<Section className="mb-8">
<Section className="mb-3">
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Review your email lists</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Remove invalid or unengaged contacts
</Text>
</Section>
<Section className="mb-3">
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Verify recipient consent</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Ensure you have proper consent from all recipients
</Text>
</Section>
<Section>
<Text className="mb-1 mt-0 text-sm font-medium text-gray-900">Check email content</Text>
<Text className="mb-0 mt-0 text-sm leading-relaxed text-gray-600">
Verify your content follows best practices and isn't triggering spam filters
</Text>
</Section>
</Section>
<Section className="mb-6">
<Link
href={dashboardUrl}
className="inline-block rounded-md bg-gray-900 px-6 py-3 text-sm font-medium text-white no-underline"
>
View project dashboard
</Link>
</Section>
</Section>
<Footer projectId={projectId} landingUrl={landingUrl} />
</EmailLayout>
);
}
export default ProjectDisabledEmail;
+3
View File
@@ -0,0 +1,3 @@
export {ProjectDisabledEmail} from './ProjectDisabled';
export {BillingLimitWarningEmail} from './BillingLimitWarning';
export {BillingLimitExceededEmail} from './BillingLimitExceeded';
+1
View File
@@ -1 +1,2 @@
export * from './send'; export * from './send';
export * from './notify';
+40
View File
@@ -0,0 +1,40 @@
import {render} from '@react-email/components';
import type {ReactElement} from 'react';
import {sendEmail} from './send';
/**
* Check if platform email notifications are enabled
* Requires PLUNK_API_KEY to be set in environment
*/
export function isPlatformEmailEnabled(): boolean {
return !!process.env.PLUNK_API_KEY && !!process.env.PLUNK_FROM_ADDRESS;
}
/**
* Send a platform notification email (only if PLUNK_API_KEY is configured)
* @param to - Recipient email address
* @param subject - Email subject line
* @param template - React email template component
*/
export async function sendPlatformEmail(to: string, subject: string, template: ReactElement): Promise<void> {
// Skip if platform emails are not enabled
if (!isPlatformEmailEnabled()) {
return;
}
try {
// Render React email template to HTML
const html = await render(template);
// Send email using the platform
await sendEmail({
to,
from: process.env.PLUNK_FROM_ADDRESS as string,
subject,
body: html,
});
} catch (error) {
// Log error but don't throw - notifications should not break the main flow
console.error('[Platform Email] Failed to send notification:', error);
}
}
+4 -2
View File
@@ -1,11 +1,12 @@
interface SendEmailParams { interface SendEmailParams {
to: string; to: string;
from: string;
subject: string; subject: string;
body: string; body: string;
} }
export async function sendEmail({to, subject, body}: SendEmailParams) { export async function sendEmail({to, from, subject, body}: SendEmailParams) {
const apiUrl = process.env.API_URI ?? 'http://localhost:8080'; const apiUrl = process.env.API_URI;
const res = await fetch(`${apiUrl}/v1/send`, { const res = await fetch(`${apiUrl}/v1/send`, {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -14,6 +15,7 @@ export async function sendEmail({to, subject, body}: SendEmailParams) {
}, },
body: JSON.stringify({ body: JSON.stringify({
to, to,
from,
subject, subject,
body, body,
}), }),
+8 -10
View File
@@ -340,16 +340,14 @@ export const ActionSchemas = {
template: uuid.optional(), template: uuid.optional(),
subscribed: z.boolean().optional().default(false), subscribed: z.boolean().optional().default(false),
name: z.string().optional(), name: z.string().optional(),
from: z from: z.union([
.union([ email, // Simple email string (backward compatible)
email, // Simple email string (backward compatible) z.object({
z.object({ // Object with name and email
// Object with name and email name: z.string().optional(),
name: z.string().optional(), email: email,
email: email, }),
}), ]),
])
.optional(),
reply: email.optional(), reply: email.optional(),
headers: z.record(z.string().max(998)).optional(), headers: z.record(z.string().max(998)).optional(),
data: jsonSchema.optional(), data: jsonSchema.optional(),
+2 -1
View File
@@ -3080,6 +3080,7 @@ __metadata:
"@plunk/typescript-config": "npm:*" "@plunk/typescript-config": "npm:*"
"@react-email/components": "npm:^1.0.0" "@react-email/components": "npm:^1.0.0"
"@react-email/preview-server": "npm:5.0.1" "@react-email/preview-server": "npm:5.0.1"
"@react-email/tailwind": "npm:^2.0.1"
"@types/react": "npm:^19.2.7" "@types/react": "npm:^19.2.7"
react-email: "npm:5.0.1" react-email: "npm:5.0.1"
typescript: "npm:^5.7.2" typescript: "npm:^5.7.2"
@@ -4658,7 +4659,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@react-email/tailwind@npm:2.0.1": "@react-email/tailwind@npm:2.0.1, @react-email/tailwind@npm:^2.0.1":
version: 2.0.1 version: 2.0.1
resolution: "@react-email/tailwind@npm:2.0.1" resolution: "@react-email/tailwind@npm:2.0.1"
dependencies: dependencies: