All files / web/src/lib/notifications/channels email-channel.ts

0% Statements 0/138
0% Branches 0/1
0% Functions 0/1
0% Lines 0/138

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139                                                                                                                                                                                                                                                                                     
import type {
  NotificationChannel,
  DeliveryTarget,
  NotificationEvent,
  DeliveryResult,
} from '../types'
import { formatNotificationContent } from '../types'
import { sendEmail } from '../email'
import { escapeHtml, baseUrl } from '../email-utils'

interface EmailHtmlOptions {
  title: string
  body: string
  ctaLabel: string
  ctaUrl: string
  /** Optional image to display above the body text */
  imageUrl?: string
}

/**
 * Build an HTML email for any notification event.
 */
function buildEmailHtml({ title, body, ctaLabel, ctaUrl, imageUrl }: EmailHtmlOptions): string {
  const imageBlock = imageUrl
    ? `<tr>
            <td style="padding:0;">
              <a href="${escapeHtml(ctaUrl)}">
                <img src="${escapeHtml(imageUrl)}" alt="Postcard" width="480"
                     style="display:block;width:100%;height:auto;border-radius:12px 12px 0 0;" />
              </a>
            </td>
          </tr>`
    : ''

  return `<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background-color:#f4f4f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f4f5;padding:32px 16px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px;background-color:#ffffff;border-radius:12px;overflow:hidden;">
          ${imageBlock}
          <tr>
            <td style="padding:32px 24px;text-align:center;">
              <h1 style="margin:0 0 8px;font-size:22px;color:#18181b;">
                ${escapeHtml(title)}
              </h1>
              <p style="margin:0 0 24px;font-size:16px;color:#71717a;">
                ${escapeHtml(body)}
              </p>
              <a href="${escapeHtml(ctaUrl)}"
                 style="display:inline-block;padding:14px 32px;background-color:#2563eb;color:#ffffff;font-size:16px;font-weight:600;text-decoration:none;border-radius:8px;">
                ${escapeHtml(ctaLabel)}
              </a>
            </td>
          </tr>
          <tr>
            <td style="padding:16px 24px;text-align:center;border-top:1px solid #e4e4e7;">
              <a href="${escapeHtml(baseUrl())}/settings?tab=notifications"
                 style="font-size:13px;color:#a1a1aa;text-decoration:underline;">
                Manage notification settings
              </a>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`
}

/** Map event type to email CTA label */
function ctaLabel(event: NotificationEvent): string {
  switch (event.type) {
    case 'session-started':
      return 'Watch Now'
    case 'postcard-ready':
      return 'View Postcard'
    case 'admin-song-failed':
      return 'Open Songs Dashboard'
  }
}

/**
 * Email notification channel implementation.
 *
 * Sends an HTML email via the shared Nodemailer transport.
 * Works with any notification event type.
 */
export const emailChannel: NotificationChannel = {
  name: 'email',

  canDeliver(target: DeliveryTarget): boolean {
    return target.channels.email && target.email != null
  },

  async deliver(target: DeliveryTarget, event: NotificationEvent): Promise<DeliveryResult> {
    if (!target.email) {
      return { success: false, error: 'No email address available' }
    }

    const content = formatNotificationContent(event)

    // For postcard emails, optionally embed the image
    let imageUrl: string | undefined
    if (event.type === 'postcard-ready') {
      const { isEnabled } = await import('@/lib/feature-flags')
      const useFullImage = await isEnabled('postcard.full-image-in-email')
      const rawUrl = useFullImage ? event.data.imageUrl : event.data.thumbnailUrl
      if (rawUrl) {
        // Ensure absolute URL for email clients
        imageUrl = rawUrl.startsWith('http') ? rawUrl : `${baseUrl()}${rawUrl}`
      }
    }

    const html = buildEmailHtml({
      title: content.title,
      body: content.body,
      ctaLabel: ctaLabel(event),
      ctaUrl: content.url.startsWith('http') ? content.url : `${baseUrl()}${content.url}`,
      imageUrl,
    })

    try {
      await sendEmail({
        to: target.email,
        subject: content.title,
        html,
      })
      return { success: true }
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err)
      return { success: false, error: `email: ${message}` }
    }
  },
}