# Email Templates - Usage Guide

## 📁 File Structure

```
emailtemplates/
├── index.ts                              ✅ Central export file
├── types.ts                              ✅ TypeScript type definitions
├── helpers.ts                            ✅ Reusable helper functions
│
├── requestCreated.template.ts            ✅ Request created email
├── approvalRequest.template.ts           ✅ Single approver email
├── multiApproverRequest.template.ts      ✅ Multi-approver email
│
├── approvalConfirmation.template.ts      ✅ DONE
├── rejectionNotification.template.ts     ✅ DONE
├── tatReminder.template.ts               ✅ DONE
├── tatBreached.template.ts               ✅ DONE
├── workflowPaused.template.ts            ✅ DONE
├── workflowResumed.template.ts           ✅ DONE
├── participantAdded.template.ts          ✅ DONE
├── approverSkipped.template.ts           ✅ DONE
└── requestClosed.template.ts             ✅ DONE
```

---

## 🚀 Quick Start

### 1. Import the template function

```typescript
import { 
  getRequestCreatedEmail,
  getApprovalRequestEmail,
  RequestCreatedData,
  ApprovalRequestData
} from '@/emailtemplates';
```

### 2. Prepare the data

```typescript
const data: RequestCreatedData = {
  recipientName: 'John Doe',
  requestId: 'REQ-2025-12-0013',
  requestTitle: 'New Equipment Purchase',
  initiatorName: 'John Doe',
  firstApproverName: 'Jane Smith',
  requestType: 'Purchase',
  priority: 'HIGH',
  requestDate: 'Dec 04, 2025',
  requestTime: '02:30 PM',
  totalApprovers: 3,
  expectedTAT: 48,
  viewDetailsLink: 'https://workflow.{{APP_DOMAIN}}/request/REQ-2025-12-0013',
  companyName: 'Royal Enfield'
};
```

### 3. Generate the HTML

```typescript
const htmlContent = getRequestCreatedEmail(data);
```

### 4. Send the email

```typescript
await emailService.sendEmail({
  to: 'john.doe@example.com',
  subject: '[REQ-2025-12-0013] Request Created Successfully',
  html: htmlContent
});
```

---

## 📧 Complete Example

```typescript
import nodemailer from 'nodemailer';
import { getApprovalRequestEmail, ApprovalRequestData } from '@/emailtemplates';

// Setup email transporter
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: parseInt(process.env.SMTP_PORT || '587'),
  secure: false,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASSWORD
  }
});

// Function to send approval request
async function sendApprovalRequest(request: any, approver: any) {
  // Prepare data
  const data: ApprovalRequestData = {
    recipientName: approver.name,
    requestId: request.requestNumber,
    approverName: approver.name,
    initiatorName: request.initiator.name,
    requestType: request.type,
    requestDescription: request.description,
    priority: request.priority,
    requestDate: new Date(request.createdAt).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    }),
    requestTime: new Date(request.createdAt).toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit'
    }),
    viewDetailsLink: `${process.env.BASE_URL}/request/${request.requestNumber}`,
    companyName: process.env.COMPANY_NAME || 'Royal Enfield'
  };

  // Generate HTML
  const html = getApprovalRequestEmail(data);

  // Send email
  await transporter.sendMail({
    from: process.env.EMAIL_FROM,
    to: approver.email,
    subject: `[${request.requestNumber}] Approval Request - Action Required`,
    html: html
  });

  console.log(`✅ Approval request email sent to ${approver.email}`);
}

// Usage
await sendApprovalRequest(requestData, approverData);
```

---

## 🎨 Template Features

### Type Safety
All templates have strongly typed data structures:
```typescript
// TypeScript will catch errors at compile time
const data: RequestCreatedData = {
  recipientName: 'John',
  requestId: 'REQ-001',
  // TypeScript error if you miss required fields!
  // TypeScript error if you use wrong types!
};
```

### Dynamic Sections
Templates automatically show/hide sections based on data:
```typescript
// Priority alert only shows for HIGH/CRITICAL
getPrioritySection(data.priority);  // Returns HTML or empty string

// Approval chain visualization
getApprovalChain(data.approversList);  // Generates chain HTML

// Next steps based on approval status
getNextStepsSection(isFinalApproval, nextApproverName);
```

### Reusable Helpers
Common functions in `helpers.ts`:
- `getPrioritySection()` - Priority alert boxes
- `getApprovalChain()` - Approval chain visualization
- `getNextStepsSection()` - Next steps guidance
- `getPermissionsContent()` - Role-based permissions
- `getConclusionSection()` - Conclusion remarks
- `getEmailFooter()` - Consistent footer

---

## 🔧 Environment Variables

Required in your `.env`:

```env
# SMTP Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your-email@domain.com
SMTP_PASSWORD=your-app-password

# Email Settings
EMAIL_FROM=Royal Enfield Workflow <notifications@{{APP_DOMAIN}}>

# Application Settings
BASE_URL=https://workflow.{{APP_DOMAIN}}
COMPANY_NAME=Royal Enfield
```

---

## 🎯 Best Practices

### 1. Date Formatting
Use consistent date formatting:
```typescript
const date = new Date(request.createdAt);

// Date format: "Dec 04, 2025"
const requestDate = date.toLocaleDateString('en-US', {
  year: 'numeric',
  month: 'short',
  day: 'numeric'
});

// Time format: "02:30 PM"
const requestTime = date.toLocaleTimeString('en-US', {
  hour: '2-digit',
  minute: '2-digit'
});
```

### 2. URL Generation
Always use environment variable for base URL:
```typescript
const viewDetailsLink = `${process.env.BASE_URL}/request/${requestNumber}`;
```

### 3. Error Handling
Wrap email sending in try-catch:
```typescript
try {
  const html = getApprovalRequestEmail(data);
  await sendEmail(recipientEmail, subject, html);
  console.log('✅ Email sent successfully');
} catch (error) {
  console.error('❌ Failed to send email:', error);
  // Log to monitoring service
  // Add to retry queue
}
```

### 4. Email Queue (Recommended)
Use a queue for reliable delivery:
```typescript
import Queue from 'bull';

const emailQueue = new Queue('emails', {
  redis: { host: 'localhost', port: 6379 }
});

// Add to queue
await emailQueue.add('send-approval-request', {
  recipientEmail: approver.email,
  data: approvalRequestData
}, {
  attempts: 3,
  backoff: { type: 'exponential', delay: 5000 }
});

// Process queue
emailQueue.process('send-approval-request', async (job) => {
  const { recipientEmail, data } = job.data;
  const html = getApprovalRequestEmail(data);
  await sendEmail(recipientEmail, subject, html);
});
```

---

## ✅ Checklist Before Sending

- [ ] All required data fields provided
- [ ] ViewDetailsLink points to correct environment
- [ ] CompanyName is set correctly
- [ ] Dates are properly formatted
- [ ] Priority section logic is correct
- [ ] Email subject includes request number
- [ ] Recipient email is valid
- [ ] SMTP credentials are configured
- [ ] Error handling is in place

---

## 🐛 Troubleshooting

### TypeScript Errors
```
Property 'requestId' is missing in type
```
**Solution:** Ensure all required fields in the type definition are provided.

### Email Not Sending
**Check:**
1. SMTP credentials in `.env`
2. Network connectivity
3. Email service logs
4. Recipient email address validity

### HTML Not Rendering
**Check:**
1. Email client compatibility (Gmail, Outlook, etc.)
2. Inline styles are present
3. No JavaScript in templates

---

## 📞 Need Help?

For questions or issues:
1. Check type definitions in `types.ts`
2. Review helper functions in `helpers.ts`
3. See examples in this guide
4. Review `TEMPLATE_MAPPING.md` for detailed documentation

---

**Last Updated:** December 4, 2025  
**Version:** 2.0 (Template Literals)

