# Email + CRM + Campaigns Integration Specification ## AI-Powered Cross-App Features (Optional) ## Architecture Principle ``` Email (Standalone) ↓ (optional integration) ├─→ CRM (if enabled) └─→ Campaigns (if enabled) ``` **Rules:** - Email works independently - CRM features appear ONLY if CRM is enabled - Campaign features appear ONLY if Campaigns is enabled - All integrations are AI-powered ## 🔗 Email → CRM Integration (When CRM Enabled) ### 1. Auto-Create Lead from Email **What:** AI detects potential leads in emails and suggests creating CRM lead **Implementation:** ```html
This looks like a sales inquiry. Create a lead?
``` ### 2. Link Email to Existing Contact/Deal **What:** Show CRM context when viewing emails from known contacts **Implementation:** ```html ``` ### 3. Track Email in Deal Timeline **What:** Automatically log emails to deal activity timeline **Implementation:** ```javascript async function logEmailToCrm() { const email = getCurrentEmail(); await fetch('/api/crm/activity/log', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'email', contact_email: email.from, subject: email.subject, body: email.body, timestamp: email.date }) }); showNotification('Email logged to CRM'); } // Auto-log if setting enabled if (window.crmEnabled && window.crmAutoLog) { logEmailToCrm(); } ``` ## 📧 Email → Campaigns Integration (When Campaigns Enabled) ### 4. Add Email Sender to Campaign List **What:** Quick-add email sender to marketing list **Implementation:** ```html
``` ### 5. Track Campaign Email Opens **What:** Show if email is from a campaign and track engagement **Implementation:** ```html
From Campaign: "Welcome Series" View Campaign →
Opened: Yes Clicked: 2 links Converted: No
``` ## 🤖 AI-Powered Cross-App Features ### 6. Smart Reply Suggestions (AI + CRM Context) **What:** AI generates replies using CRM deal context **Implementation:** ```javascript async function generateSmartReply() { const email = getCurrentEmail(); let context = { email }; // Add CRM context if available if (window.crmEnabled) { const crmData = await fetch(`/api/crm/contact/by-email?email=${email.from}`); context.crm = await crmData.json(); } // Generate reply with full context const response = await fetch('/api/ai/generate-reply', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(context) }); const { suggestions } = await response.json(); showReplySuggestions(suggestions); } ``` ### 7. Lead Scoring from Email Behavior **What:** AI scores leads based on email engagement **Implementation:** ```javascript async function updateLeadScore(emailId) { if (!window.crmEnabled) return; const email = getCurrentEmail(); // Calculate engagement score const score = { opened: email.opened ? 10 : 0, replied: email.replied ? 20 : 0, clicked_links: email.clicks * 5, response_time: calculateResponseScore(email.response_time) }; const totalScore = Object.values(score).reduce((a, b) => a + b, 0); // Update in CRM await fetch('/api/crm/lead/score', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: email.from, score: totalScore, source: 'email_engagement' }) }); } ``` ### 8. Campaign Performance in Email **What:** Show campaign metrics when viewing campaign emails **Implementation:** ```html ``` ### 9. Unified Contact View **What:** See all interactions (emails + CRM + campaigns) in one place **Implementation:** ```html

John Doe

john@company.com CEO at Acme Corp
📞
Call completed

Discussed pricing

Yesterday
📨
Campaign email opened

Welcome Series - Email 2

3 days ago
``` ### 10. AI Email Categorization **What:** AI automatically categorizes emails (sales, support, marketing) **Implementation:** ```javascript async function categorizeEmail(emailId) { const email = getCurrentEmail(); const response = await fetch('/api/ai/categorize-email', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ from: email.from, subject: email.subject, body: email.body }) }); const { category, confidence } = await response.json(); // Route based on category if (category === 'sales' && window.crmEnabled) { suggestCreateLead(); } else if (category === 'marketing' && window.campaignsEnabled) { suggestAddToList(); } // Add category badge addCategoryBadge(category); } ``` ## 🔧 Backend API Requirements ``` # Feature Detection GET /api/features/enabled - Check which features are enabled # Email → CRM POST /api/ai/extract-lead - Extract lead info from email GET /api/crm/contact/by-email - Get contact by email POST /api/crm/activity/log - Log email to CRM # Email → Campaigns GET /api/crm/lists - Get campaign lists POST /api/crm/lists/:id/contacts - Add contact to list GET /api/crm/campaigns/check-email - Check if email is from campaign # AI Features POST /api/ai/generate-reply - Generate smart reply POST /api/ai/categorize-email - Categorize email POST /api/crm/lead/score - Update lead score # Unified View GET /api/contact/timeline - Get all interactions ``` ## 📊 Database Schema ```sql -- Feature flags CREATE TABLE feature_flags ( id UUID PRIMARY KEY, org_id UUID NOT NULL, feature VARCHAR(50), -- 'crm', 'campaigns' enabled BOOLEAN DEFAULT FALSE ); -- Email-CRM links CREATE TABLE email_crm_links ( id UUID PRIMARY KEY, email_id UUID, contact_id UUID REFERENCES crm_contacts(id), deal_id UUID REFERENCES crm_opportunities(id), logged_at TIMESTAMP ); -- Email-Campaign links CREATE TABLE email_campaign_links ( id UUID PRIMARY KEY, email_id UUID, campaign_id UUID REFERENCES campaigns(id), list_id UUID REFERENCES contact_lists(id), sent_at TIMESTAMP ); -- AI categorization ALTER TABLE emails ADD COLUMN ai_category VARCHAR(50); ALTER TABLE emails ADD COLUMN ai_confidence FLOAT; ``` ## ✅ Implementation Priority ### Phase 1: Feature Detection (Week 1) 1. Check if CRM/Campaigns enabled 2. Show/hide integration features 3. Feature flag system ### Phase 2: CRM Integration (Week 2) 4. Auto-create lead from email 5. Link email to contact/deal 6. Track email in deal timeline ### Phase 3: Campaigns Integration (Week 3) 7. Add sender to campaign list 8. Track campaign email opens 9. Show campaign performance ### Phase 4: AI Features (Week 4) 10. Smart reply with CRM context 11. Lead scoring from email 12. Unified contact view 13. AI email categorization ## 🧪 Testing Checklist **Email Standalone:** - [ ] Email works without CRM - [ ] Email works without Campaigns - [ ] All email features functional **With CRM Enabled:** - [ ] CRM panel appears in email - [ ] Create lead from email - [ ] Link email to contact - [ ] Log email to deal timeline **With Campaigns Enabled:** - [ ] Add sender to list - [ ] Track campaign opens - [ ] Show campaign metrics **AI Features:** - [ ] Smart reply uses CRM context - [ ] Lead score updates from engagement - [ ] Unified timeline shows all interactions - [ ] AI categorizes emails correctly