|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { user } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { task } from '@trigger.dev/sdk' |
| 5 | +import { eq } from 'drizzle-orm' |
| 6 | +import { getEmailSubject, renderOnboardingFollowupEmail } from '@/components/emails' |
| 7 | +import { getHighestPrioritySubscription } from '@/lib/billing/core/subscription' |
| 8 | +import { checkEnterprisePlan } from '@/lib/billing/subscriptions/utils' |
| 9 | +import { sendEmail } from '@/lib/messaging/email/mailer' |
| 10 | +import { getPersonalEmailFrom } from '@/lib/messaging/email/utils' |
| 11 | +import { LIFECYCLE_EMAIL_TASK_ID, type LifecycleEmailType } from '@/lib/messaging/lifecycle' |
| 12 | + |
| 13 | +const logger = createLogger('LifecycleEmail') |
| 14 | + |
| 15 | +interface LifecycleEmailParams { |
| 16 | + userId: string |
| 17 | + type: LifecycleEmailType |
| 18 | +} |
| 19 | + |
| 20 | +async function sendLifecycleEmail({ userId, type }: LifecycleEmailParams): Promise<void> { |
| 21 | + const [userData] = await db.select().from(user).where(eq(user.id, userId)).limit(1) |
| 22 | + |
| 23 | + if (!userData?.email) { |
| 24 | + logger.warn('[lifecycle-email] User not found or has no email', { userId, type }) |
| 25 | + return |
| 26 | + } |
| 27 | + |
| 28 | + const subscription = await getHighestPrioritySubscription(userId) |
| 29 | + if (checkEnterprisePlan(subscription)) { |
| 30 | + logger.info('[lifecycle-email] Skipping lifecycle email for enterprise user', { userId, type }) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + const { from, replyTo } = getPersonalEmailFrom() |
| 35 | + |
| 36 | + let html: string |
| 37 | + |
| 38 | + switch (type) { |
| 39 | + case 'onboarding-followup': |
| 40 | + html = await renderOnboardingFollowupEmail(userData.name || undefined) |
| 41 | + break |
| 42 | + default: |
| 43 | + logger.warn('[lifecycle-email] Unknown lifecycle email type', { type }) |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + await sendEmail({ |
| 48 | + to: userData.email, |
| 49 | + subject: getEmailSubject(type), |
| 50 | + html, |
| 51 | + from, |
| 52 | + replyTo, |
| 53 | + emailType: 'transactional', |
| 54 | + }) |
| 55 | + |
| 56 | + logger.info('[lifecycle-email] Sent lifecycle email', { userId, type }) |
| 57 | +} |
| 58 | + |
| 59 | +export const lifecycleEmailTask = task({ |
| 60 | + id: LIFECYCLE_EMAIL_TASK_ID, |
| 61 | + retry: { maxAttempts: 2 }, |
| 62 | + run: async (params: LifecycleEmailParams) => { |
| 63 | + await sendLifecycleEmail(params) |
| 64 | + }, |
| 65 | +}) |
0 commit comments