# Email & Slack Notification System

Complete email and Slack notification system for user registration, subscriptions, and custom notifications.

## 📋 Table of Contents
- [Setup](#setup)
- [Email Service](#email-service)
- [Slack Service](#slack-service)
- [Integration Points](#integration-points)
- [Usage Examples](#usage-examples)

---

## 🚀 Setup

### 1. Install Dependencies

```bash
npm install nodemailer
```

### 2. Environment Variables

Add the following to your `.env` file:

```env
# SMTP Email Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password
COMPANY_NAME=Scepter Marketing

# Slack Configuration
SLACK_CLIENT_ID=661afc83906d1442df4d70aa-lwq20y7t
SLACK_CLIENT_SECRET=70874b5b-f323-42e3-900b-f0532ed18cbd
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/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
SLACK_LOGIN_WEBHOOK_URL=https://hooks.slack.com/services/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
ZAPIER_WEBHOOK_URL=https://hooks.zapier.com/hooks/catch/4561771/2yw8u71/
```

### 3. Gmail App Password Setup

For Gmail SMTP:
1. Enable 2-Factor Authentication on your Google account
2. Go to Google Account → Security → App Passwords
3. Generate a new app password for "Mail"
4. Use this password in `SMTP_PASS`

---

## 📧 Email Service

### Available Functions

#### 1. Send Welcome Email
```javascript
import emailService from './services/email.service.js';

await emailService.sendWelcomeEmail({
  toEmail: 'user@example.com',
  userName: 'John Doe',
  accountName: 'Acme Corp',
  userType: 'direct_client',
  credentials: {  // Optional
    username: 'john@example.com',
    password: 'temp123'
  }
});
```

#### 2. Send Notification Email
```javascript
await emailService.sendNotificationEmail({
  toEmail: 'user@example.com',
  subject: 'Important Update',
  message: '<p>Your account has been updated.</p>',
  userName: 'John Doe'  // Optional
});
```

#### 3. Send Subscription Email
```javascript
await emailService.sendSubscriptionEmail({
  toEmail: 'user@example.com',
  userName: 'John Doe',
  planName: 'Pro Plan',
  price: 79.99
});
```

#### 4. Generic Send Email
```javascript
await emailService.sendEmail({
  to: 'user@example.com',
  subject: 'Custom Email',
  html: '<h1>Hello World</h1>'
});
```

---

## 💬 Slack Service

### Available Functions

#### 1. Send General Notification
```javascript
import slackService from './services/slack.service.js';

await slackService.notifySlack('🎉 Something awesome happened!');
```

#### 2. Send Login Notification
```javascript
await slackService.notifySlackLogin('User logged in from new device');
```

#### 3. Send to Zapier
```javascript
await slackService.notifyZapier({
  event: 'user_registered',
  email: 'user@example.com',
  timestamp: new Date()
});
```

#### 4. Formatted New User Notification
```javascript
await slackService.notifyNewUser({
  userName: 'John Doe',
  email: 'john@example.com',
  accountName: 'Acme Corp',
  userType: 'direct_client',
  accountId: 123
});
```

#### 5. Formatted Login Notification
```javascript
await slackService.notifyUserLogin({
  email: 'john@example.com',
  accountName: 'Acme Corp',
  userType: 'direct_client',
  ipAddress: '192.168.1.1'  // Optional
});
```

#### 6. Subscription Notifications
```javascript
// New subscription
await slackService.notifyNewSubscription({
  email: 'john@example.com',
  planName: 'Pro Plan',
  price: 79.99,
  locationId: 456
});

// Subscription canceled
await slackService.notifySubscriptionCanceled({
  email: 'john@example.com',
  planName: 'Pro Plan',
  locationId: 456
});
```

#### 7. Error Notifications
```javascript
await slackService.notifyError({
  error: 'Database connection failed',
  context: 'User Registration',
  details: {
    userId: 123,
    timestamp: new Date()
  }
});
```

#### 8. Custom Formatted Message
```javascript
await slackService.sendFormattedMessage({
  title: 'System Update',
  fields: {
    'Status': 'Completed',
    'Duration': '5 minutes',
    'Affected Users': '0'
  },
  emoji: '✅'
});
```

---

## 🔗 Integration Points

### 1. User Registration (auth.service.js)

When a new user registers:
- ✅ **Welcome email** sent automatically
- ✅ **Slack notification** sent to main channel

```javascript
// Automatically triggered in auth.service.js
if (!existingAccount) {
  // ... create account and user ...
  
  // Send welcome email
  emailService.sendWelcomeEmail({
    toEmail: email,
    userName: full_name,
    accountName: full_name,
    userType: user_type,
  });

  // Send Slack notification
  slackService.notifyNewUser({
    userName: full_name,
    email: email,
    accountName: full_name,
    userType: user_type,
    accountId: account.id,
  });
}
```

### 2. Subscription Events (stripe.service.js)

When subscription is created:
- ✅ **Subscription confirmation email** sent
- ✅ **Slack notification** sent to main channel

When subscription is canceled:
- ✅ **Slack notification** sent to main channel

```javascript
// Automatically triggered in stripe.service.js
async handleCheckoutCompleted(session) {
  // ... create subscription ...
  
  // Send subscription email
  emailService.sendSubscriptionEmail({
    toEmail: location.client.account.email,
    userName: location.client.account.name,
    planName: plan.display_name,
    price: parseFloat(plan.price_per_month),
  });

  // Send Slack notification
  slackService.notifyNewSubscription({
    email: location.client?.account?.email,
    planName: plan.display_name,
    price: parseFloat(plan.price_per_month),
    locationId: locationIdInt,
  });
}
```

---

## 💡 Usage Examples

### Example 1: Send Custom Notification

```javascript
// In any controller or service
import emailService from '../services/email.service.js';
import slackService from '../services/slack.service.js';

// Send email notification
await emailService.sendNotificationEmail({
  toEmail: 'user@example.com',
  subject: 'Your report is ready',
  message: `
    <p>Hi John,</p>
    <p>Your monthly report has been generated and is ready for download.</p>
    <a href="https://example.com/reports/123">Download Report</a>
  `,
  userName: 'John Doe'
});

// Send Slack notification
await slackService.notifySlack('📊 Monthly report generated for John Doe');
```

### Example 2: Error Handling with Notifications

```javascript
try {
  // Some operation
  await performCriticalOperation();
} catch (error) {
  // Log error
  console.error('Critical operation failed:', error);
  
  // Notify via Slack
  await slackService.notifyError({
    error: error.message,
    context: 'Critical Operation',
    details: {
      operation: 'performCriticalOperation',
      timestamp: new Date(),
      stack: error.stack
    }
  });
  
  // Optionally notify user via email
  await emailService.sendNotificationEmail({
    toEmail: 'admin@example.com',
    subject: 'System Error Alert',
    message: `<p>An error occurred: ${error.message}</p>`
  });
}
```

### Example 3: Location Creation Notification

```javascript
// In location.service.js
async createLocation(payload) {
  const location = await prisma.location.create({
    data: { ...payload },
    include: {
      client: {
        include: { account: true }
      }
    }
  });

  // Send notification
  await slackService.sendFormattedMessage({
    title: 'New Location Created',
    fields: {
      'Location': location.name,
      'Client': location.client.name,
      'Email': location.client.account.email,
      'Location ID': location.id
    },
    emoji: '📍'
  });

  return location;
}
```

---

## 🎨 Email Templates

All emails use responsive HTML templates with:
- Company branding
- Professional styling
- Mobile-friendly design
- Call-to-action buttons
- Footer with company info

### Customizing Templates

Edit the HTML in `email.service.js` functions to customize:
- Colors (currently using Indigo: `#4F46E5`)
- Layout
- Content structure
- Branding elements

---

## 🔒 Security Best Practices

1. **Never commit `.env` file** - Keep credentials secure
2. **Use app passwords** for Gmail (not your main password)
3. **Rotate webhook URLs** periodically
4. **Monitor Slack channels** for suspicious activity
5. **Rate limit notifications** to avoid spam
6. **Validate email addresses** before sending
7. **Handle errors gracefully** - don't expose sensitive info

---

## 🐛 Troubleshooting

### Email Not Sending

1. **Check SMTP credentials** in `.env`
2. **Verify Gmail app password** is correct
3. **Check firewall/network** settings
4. **Review console logs** for errors
5. **Test with a simple email** first

```javascript
// Test email
await emailService.sendEmail({
  to: 'your-email@example.com',
  subject: 'Test Email',
  html: '<p>This is a test</p>'
});
```

### Slack Notifications Not Working

1. **Verify webhook URL** is correct
2. **Check webhook is active** in Slack settings
3. **Test with curl**:
```bash
curl -X POST https://hooks.slack.com/services/YOUR/WEBHOOK/URL \
  -H 'Content-Type: application/json' \
  -d '{"text":"Test message"}'
```
4. **Review console logs** for errors

### Gmail "Less Secure Apps" Error

Gmail no longer supports "less secure apps". You **must** use:
- 2-Factor Authentication
- App-specific password

---

## 📊 Monitoring

### Email Delivery

Monitor email delivery in console logs:
```
✅ Welcome email sent to user@example.com
✅ Subscription email sent to user@example.com
❌ Failed to send email: Connection timeout
```

### Slack Notifications

Monitor Slack notifications in console logs:
```
✅ Slack notification sent
✅ Slack login notification sent
❌ Failed to send notification to Slack: Invalid webhook URL
```

---

## 🚀 Future Enhancements

Potential improvements:
- [ ] Email queue system (Bull/Redis)
- [ ] Email templates from database
- [ ] Unsubscribe functionality
- [ ] Email analytics/tracking
- [ ] Multiple Slack channels
- [ ] SMS notifications (Twilio)
- [ ] Push notifications
- [ ] Email scheduling
- [ ] A/B testing for emails

---

## 📚 File Structure

```
src/
├── services/
│   ├── email.service.js      # Email functionality
│   ├── slack.service.js      # Slack notifications
│   ├── auth.service.js       # Integrated with email/Slack
│   └── stripe.service.js     # Integrated with email/Slack
```

---

## ✅ Testing Checklist

Before going to production:

- [ ] Test welcome email with real email address
- [ ] Test subscription email
- [ ] Test notification email
- [ ] Test all Slack webhooks
- [ ] Verify email templates render correctly
- [ ] Test error handling (invalid email, wrong webhook)
- [ ] Monitor Slack channels for test messages
- [ ] Test with different email providers (Gmail, Outlook, etc.)
- [ ] Verify emails don't go to spam
- [ ] Test unsubscribe links (if implemented)

---

## 📞 Support

For issues or questions:
- Check console logs first
- Review `.env` configuration
- Test individual functions in isolation
- Check Slack webhook status in Slack dashboard
- Verify Gmail app password is active
