All files / src/lib/email/templates index.ts

0% Statements 0/361
100% Branches 0/0
0% Functions 0/1
0% Lines 0/361

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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Email Template Renderer
 *
 * Renders email templates using Handlebars with caching.
 * Provides helpers for formatting currency, dates, and other common patterns.
 */

import Handlebars from 'handlebars';
import { readFileSync, existsSync } from 'fs';
import { join } from 'path';
import { logger } from '@/lib/logging';

// ============================================================================
// HANDLEBARS HELPERS
// ============================================================================

/**
 * Format currency
 */
Handlebars.registerHelper('formatCurrency', (value: number) => {
  if (typeof value !== 'number' || isNaN(value)) {
    return '$0.00';
  }
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  }).format(value);
});

/**
 * Format date
 */
Handlebars.registerHelper('formatDate', (date: Date | string) => {
  if (!date) return '';
  const d = typeof date === 'string' ? new Date(date) : date;
  return d.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
});

/**
 * Format date with time
 */
Handlebars.registerHelper('formatDateTime', (date: Date | string) => {
  if (!date) return '';
  const d = typeof date === 'string' ? new Date(date) : date;
  return d.toLocaleString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  });
});

/**
 * Format number with commas
 */
Handlebars.registerHelper('formatNumber', (value: number) => {
  if (typeof value !== 'number' || isNaN(value)) {
    return '0';
  }
  return new Intl.NumberFormat('en-US').format(value);
});

/**
 * Conditional helper
 */
Handlebars.registerHelper('ifEquals', function (
  this: unknown,
  arg1: unknown,
  arg2: unknown,
  options: Handlebars.HelperOptions
) {
  return arg1 === arg2 ? options.fn(this) : options.inverse(this);
});

/**
 * Greater than helper
 */
Handlebars.registerHelper('ifGt', function (
  this: unknown,
  arg1: number,
  arg2: number,
  options: Handlebars.HelperOptions
) {
  return arg1 > arg2 ? options.fn(this) : options.inverse(this);
});

/**
 * Pluralize helper
 */
Handlebars.registerHelper('pluralize', (count: number, singular: string, plural?: string) => {
  return count === 1 ? singular : (plural || `${singular}s`);
});

// ============================================================================
// TEMPLATE CACHE & LOADING
// ============================================================================

const templateCache = new Map<string, HandlebarsTemplateDelegate>();
const TEMPLATE_DIR = join(process.cwd(), 'src/lib/email/templates');

/**
 * Load and compile a template
 */
function loadTemplate(name: string): HandlebarsTemplateDelegate | null {
  // Check cache first
  if (templateCache.has(name)) {
    return templateCache.get(name)!;
  }

  const templatePath = join(TEMPLATE_DIR, `${name}.hbs`);

  // Check if template file exists
  if (!existsSync(templatePath)) {
    logger.warn(`Template not found: ${name}`, { category: 'EXTERNAL' });
    return null;
  }

  try {
    const templateSource = readFileSync(templatePath, 'utf-8');
    const template = Handlebars.compile(templateSource);
    templateCache.set(name, template);
    return template;
  } catch (error) {
    logger.error(`Failed to load template: ${name}`, error as Error, { category: 'EXTERNAL' });
    return null;
  }
}

/**
 * Clear template cache (useful for development)
 */
export function clearTemplateCache(): void {
  templateCache.clear();
  logger.info('Template cache cleared', { category: 'EXTERNAL' });
}

// ============================================================================
// BASE LAYOUT
// ============================================================================

/**
 * Default base layout (inline when file not available)
 */
const DEFAULT_BASE_LAYOUT = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>{{title}}</title>
  <style>
    body, table, td, p, a, li { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
    table, td { mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
    img { -ms-interpolation-mode: bicubic; border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; }
    body {
      margin: 0;
      padding: 0;
      width: 100%;
      background-color: #f4f4f4;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    }
    .container { max-width: 600px; margin: 0 auto; background-color: #ffffff; }
    .header { background-color: #1a1a2e; padding: 24px; text-align: center; }
    .header img { max-width: 150px; height: auto; }
    .content { padding: 32px 24px; }
    .footer { background-color: #f8f9fa; padding: 24px; text-align: center; font-size: 12px; color: #6c757d; }
    .button { display: inline-block; padding: 12px 24px; background-color: #3b82f6; color: #ffffff !important; text-decoration: none; border-radius: 6px; font-weight: 600; }
    h1 { font-size: 24px; color: #1a1a2e; margin: 0 0 16px; }
    h2 { font-size: 20px; color: #1a1a2e; margin: 0 0 12px; }
    p { font-size: 16px; color: #4a5568; line-height: 1.6; margin: 0 0 16px; }
    @media only screen and (max-width: 600px) {
      .container { width: 100% !important; }
      .content { padding: 24px 16px !important; }
    }
  </style>
</head>
<body>
  {{#if preheader}}
  <div style="display: none; max-height: 0; overflow: hidden;">{{preheader}}</div>
  {{/if}}
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0">
    <tr>
      <td align="center" style="padding: 24px 0;">
        <table class="container" role="presentation" width="600" cellspacing="0" cellpadding="0">
          <tr>
            <td class="header">
              <h1 style="color: #ffffff; margin: 0; font-size: 24px;">{{companyName}}</h1>
            </td>
          </tr>
          <tr>
            <td class="content">{{{content}}}</td>
          </tr>
          <tr>
            <td class="footer">
              <p>&copy; {{year}} {{companyName}}. All rights reserved.</p>
              <p>
                <a href="{{siteUrl}}/unsubscribe" style="color: #6c757d;">Unsubscribe</a> |
                <a href="{{siteUrl}}/privacy-policy" style="color: #6c757d;">Privacy Policy</a>
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
`;

const compiledDefaultLayout = Handlebars.compile(DEFAULT_BASE_LAYOUT);

// ============================================================================
// INLINE TEMPLATES (FALLBACK)
// ============================================================================

/**
 * Inline templates for when .hbs files don't exist
 */
const INLINE_TEMPLATES: Record<string, string> = {
  'order-confirmation': `
<h1>Order Confirmed!</h1>
<p>Hi {{customerName}},</p>
<p>Thank you for your order! We're getting it ready for you.</p>
<div style="background-color: #f8fafc; padding: 16px; border-radius: 8px; margin: 24px 0;">
  <strong>Order #{{orderNumber}}</strong><br>
  <span style="color: #64748b;">Placed on {{formatDate orderDate}}</span>
</div>
<h2>Order Summary</h2>
<table role="presentation" width="100%" cellspacing="0" cellpadding="0">
  {{#each items}}
  <tr>
    <td style="padding: 12px 0; border-bottom: 1px solid #e2e8f0;">
      <strong>{{this.name}}</strong> x {{this.quantity}}<br>
      <span style="color: #64748b;">{{formatCurrency this.total}}</span>
    </td>
  </tr>
  {{/each}}
</table>
<div style="margin-top: 16px; padding-top: 16px; border-top: 2px solid #1a1a2e;">
  <strong>Total: {{formatCurrency total}}</strong>
</div>
<div style="text-align: center; margin-top: 32px;">
  <a href="{{siteUrl}}/orders/{{orderId}}" class="button">Track Your Order</a>
</div>
`,

  'password-reset': `
<h1>Reset Your Password</h1>
<p>Hi {{name}},</p>
<p>We received a request to reset your password. Click the button below to create a new password:</p>
<div style="text-align: center; margin: 32px 0;">
  <a href="{{resetLink}}" class="button">Reset Password</a>
</div>
<p style="color: #6b7280; font-size: 14px;">
  This link will expire in {{expiresIn}}. If you didn't request a password reset, you can safely ignore this email.
</p>
`,

  'welcome': `
<h1>Welcome to {{companyName}}!</h1>
<p>Hi {{name}},</p>
<p>Thank you for joining us! We're excited to have you as part of our community.</p>
<p>Start exploring our products and enjoy exclusive member benefits.</p>
<div style="text-align: center; margin: 32px 0;">
  <a href="{{siteUrl}}/shop" class="button">Start Shopping</a>
</div>
`,

  'shipping-notification': `
<h1>Your Order Has Shipped!</h1>
<p>Hi {{customerName}},</p>
<p>Great news! Your order #{{orderNumber}} is on its way.</p>
<div style="background-color: #f0fdf4; padding: 16px; border-radius: 8px; margin: 24px 0;">
  <strong>Tracking Number:</strong> {{trackingNumber}}<br>
  <strong>Carrier:</strong> {{carrier}}<br>
  <strong>Estimated Delivery:</strong> {{formatDate estimatedDelivery}}
</div>
<div style="text-align: center; margin: 32px 0;">
  <a href="{{trackingLink}}" class="button">Track Package</a>
</div>
`,
};

// ============================================================================
// MAIN RENDER FUNCTION
// ============================================================================

/**
 * Render an email template with data
 */
export async function renderEmailTemplate(
  templateName: string,
  data: Record<string, unknown>
): Promise<string> {
  // Common data for all templates
  const commonData = {
    ...data,
    year: new Date().getFullYear(),
    companyName: process.env.COMPANY_NAME || 'Elite Events',
    siteUrl: process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000',
    supportEmail: process.env.SUPPORT_EMAIL || 'support@elite-events.com',
  };

  // Try to load template from file
  const template = loadTemplate(templateName);
  let content: string;

  if (template) {
    content = template(commonData);
  } else if (INLINE_TEMPLATES[templateName]) {
    // Use inline template as fallback
    const inlineTemplate = Handlebars.compile(INLINE_TEMPLATES[templateName]);
    content = inlineTemplate(commonData);
    logger.info(`Using inline template for: ${templateName}`, { category: 'EXTERNAL' });
  } else {
    // No template found - use generic fallback
    logger.warn(`No template found for: ${templateName}, using generic`, { category: 'EXTERNAL' });
    content = `<h1>${data.title || 'Notification'}</h1><p>${data.message || 'You have a new notification from Elite Events.'}</p>`;
  }

  // Try to load base layout, fall back to default
  const layoutTemplate = loadTemplate('layouts/base');

  if (layoutTemplate) {
    return layoutTemplate({
      ...commonData,
      content,
      title: data.title || 'Elite Events',
      preheader: data.preheader || '',
    });
  }

  // Use default inline layout
  return compiledDefaultLayout({
    ...commonData,
    content,
    title: data.title || 'Elite Events',
    preheader: data.preheader || '',
  });
}

/**
 * Get list of available templates
 */
export function getAvailableTemplates(): string[] {
  return Object.keys(INLINE_TEMPLATES);
}

/**
 * Check if a template exists
 */
export function templateExists(templateName: string): boolean {
  const templatePath = join(TEMPLATE_DIR, `${templateName}.hbs`);
  return existsSync(templatePath) || templateName in INLINE_TEMPLATES;
}