# Phase 9: Advanced Features Implementation Plan

**Total Scope:** 6 major features  
**Estimated Time:** 2-3 days (40-50 hours)  
**Complexity:** High  
**Starting:** June 5, 2026  

---

## 🎯 Overview

Implementing 6 advanced features to transform Haznox from a single-platform tool into an enterprise-grade multi-channel management platform with security, analytics, and automation.

---

## 📋 Feature Breakdown by Phase

### **Phase A: Facebook Integration** (8-10 hours) ⭐ PRIORITY 1
**Goal:** Enable posting to Facebook Pages alongside Instagram

**Components:**
1. Database schema updates
   - Extend social_accounts to store Facebook Page ID, Page Name, Page Token
   - Add facebook_post_id to posts table
   - Support multiple accounts per user

2. Backend API endpoints
   - POST `/api/facebook/auth-url` — Get Facebook OAuth redirect
   - POST `/api/facebook/callback` — Handle OAuth callback
   - POST `/api/facebook/connect` — Manual token connection
   - GET `/api/facebook/status` — Check connection status
   - POST `/api/facebook/disconnect` — Remove Facebook connection

3. Facebook publishing service
   - `publishToFacebook()` — Post image + caption to Facebook Page
   - Handle Facebook API rate limiting
   - Error handling for page access issues

4. Multi-platform post publishing
   - Update post creation to support platform selection
   - Atomic transactions for multi-platform publishing
   - Fallback if one platform fails

5. UI Components
   - Settings page: Facebook connection section
   - Create post: Platform selector (Instagram / Facebook / Both)
   - Dashboard: Platform-specific status indicators

**API Keys Needed:**
```
META_APP_ID          (reuse from Instagram setup)
META_APP_SECRET      (reuse from Instagram setup)
META_REDIRECT_URI    (update for callback)
```

---

### **Phase B: Two-Factor Authentication (2FA)** (6-8 hours) ⭐ PRIORITY 2
**Goal:** Add 2FA via TOTP (Time-based One-Time Password) using Google Authenticator

**Components:**
1. Database updates
   - Add 2fa_enabled, 2fa_secret columns to users table
   - Add 2fa_backup_codes for emergency access
   - Add 2fa_verified_at timestamp

2. Backend services
   - TOTP generation (speakeasy library)
   - QR code generation for authenticator apps
   - Backup code generation (10 codes)
   - TOTP verification
   - 2FA enforcement on login

3. API endpoints
   - POST `/api/auth/2fa/setup` — Generate QR code
   - POST `/api/auth/2fa/verify` — Verify and enable 2FA
   - POST `/api/auth/2fa/disable` — Disable 2FA
   - POST `/api/auth/2fa/backup-codes` — Get new backup codes
   - POST `/api/auth/login-2fa` — Login with TOTP verification

4. UI Components
   - Settings page: 2FA management section
   - Login page: 2FA verification form
   - Backup code display and management

**New Dependencies:**
- speakeasy (TOTP generation)
- qrcode (QR code generation)

---

### **Phase C: Webhook Integrations** (8-10 hours) ⭐ PRIORITY 3
**Goal:** Receive real-time notifications from Instagram & Facebook

**Components:**
1. Database updates
   - webhooks table (id, user_id, platform, url, events, active)
   - webhook_logs table (id, webhook_id, status_code, payload, response)

2. Backend services
   - Webhook verification (signature validation)
   - Webhook parsing and routing
   - Automatic event handling

3. API endpoints
   - POST `/api/webhooks/register` — Register webhook URL
   - GET `/api/webhooks/list` — List user webhooks
   - DELETE `/api/webhooks/{id}` — Remove webhook
   - POST `/api/webhooks/instagram` — Receive Instagram events
   - POST `/api/webhooks/facebook` — Receive Facebook events

4. Webhook events supported
   - Instagram: post published, post engagement (likes, comments)
   - Facebook: post engagement, page activity
   - Auto-update post status from webhook events
   - Logging all webhook calls for debugging

5. UI Components
   - Settings page: Webhook management section
   - Webhook logs/history viewer
   - Test webhook functionality

---

### **Phase D: Advanced Analytics & Reporting** (10-12 hours) ⭐ PRIORITY 4
**Goal:** Provide insights into post performance and engagement

**Components:**
1. Database updates
   - post_analytics table (post_id, platform, likes, comments, shares, impressions, engagement_rate, updated_at)
   - campaign_analytics table (campaign_id, posts_published, total_reach, total_engagement, avg_engagement_rate)

2. Backend services
   - Fetch insights from Instagram Graph API
   - Fetch insights from Facebook Graph API
   - Analytics aggregation and calculation
   - Trend analysis (7-day, 30-day, 90-day)

3. API endpoints
   - GET `/api/analytics/posts` — Get analytics for user's posts
   - GET `/api/analytics/campaigns/{id}` — Campaign analytics
   - GET `/api/analytics/summary` — Dashboard summary stats
   - GET `/api/analytics/trends` — Trend data (7d, 30d, 90d)
   - GET `/api/analytics/export` — Export as CSV/PDF

4. Analytics metrics
   - Per-post: likes, comments, shares, impressions, reach
   - Per-campaign: total posts, reach, engagement
   - Time-based: daily/weekly trends
   - Platform comparison: IG vs Facebook performance

5. UI Components
   - Analytics dashboard page
   - Post-level analytics modal
   - Campaign analytics charts
   - Export functionality

---

### **Phase E: Email Notifications** (6-8 hours) ⭐ PRIORITY 5
**Goal:** Alert users about important events via email

**Components:**
1. Database updates
   - notification_preferences table (user_id, event_type, enabled, email)
   - email_logs table (id, user_id, event, recipient, sent_at, status)

2. Backend services
   - Email service (nodemailer or SendGrid)
   - Email template renderer (handlebars)
   - Queue system for async email sending (bull/redis)

3. Email types
   - Post published successfully
   - Post failed to publish
   - Campaign completed
   - High engagement notification
   - Weekly summary report
   - Security alerts (new login, 2FA enabled)

4. API endpoints
   - GET/POST `/api/notifications/preferences` — Manage preferences
   - GET `/api/notifications/history` — View sent emails

5. UI Components
   - Settings page: Email preferences section
   - Notification center in dashboard
   - Email log viewer

**New Dependencies:**
- nodemailer or sendgrid
- bull (job queue)
- handlebars (email templates)

---

### **Phase F: API Key Management** (4-6 hours) ⭐ PRIORITY 6
**Goal:** Allow developers to create API keys for programmatic access

**Components:**
1. Database updates
   - api_keys table (id, user_id, name, key_hash, key_preview, permissions, last_used_at, created_at, expires_at)
   - api_logs table (id, api_key_id, endpoint, status_code, timestamp)

2. Backend services
   - Generate secure API keys (64-char random tokens)
   - Hash keys for storage (bcrypt)
   - Key rotation and expiration

3. API endpoints (using API key auth)
   - GET/POST/DELETE `/api/admin/api-keys` — Manage keys
   - POST `/api/posts` — Create post via API (requires key)
   - GET `/api/posts` — List posts via API
   - GET `/api/campaigns` — List campaigns via API
   - All major endpoints support API key authentication

4. API Documentation
   - Generate OpenAPI/Swagger docs
   - API key authentication examples
   - Rate limiting per key
   - Usage metrics per key

5. UI Components
   - Settings page: API keys section
   - Generate new key modal
   - Key copy/visibility toggle
   - Usage and logs viewer

---

## 🗂️ Implementation Sequence

```
Week 1:
├─ Phase A: Facebook Integration (Days 1-2)
├─ Phase B: Two-Factor Authentication (Days 2-3)
└─ Phase C: Webhook Integrations (Days 3-4)

Week 2:
├─ Phase D: Advanced Analytics (Days 5-6)
├─ Phase E: Email Notifications (Days 6-7)
└─ Phase F: API Key Management (Days 7-8)

Testing & Refinement:
├─ Integration testing (Day 8-9)
├─ Bug fixes and polish (Day 9)
└─ Documentation (Day 10)
```

---

## 📊 Resource Requirements

### Backend Dependencies to Add
```json
{
  "speakeasy": "^2.0.0",
  "qrcode": "^1.5.3",
  "bull": "^4.11.0",
  "nodemailer": "^6.9.0",
  "sendgrid": "^7.7.0",
  "handlebars": "^4.7.7",
  "bcryptjs": "^2.4.3"
}
```

### Recommended Services
- **Email:** SendGrid (free tier: 100/day) or Gmail SMTP
- **Queuing:** Redis (if using Bull)
- **External APIs:** Instagram & Facebook Graph APIs (already set up)

### Database Migrations Needed
- Migration 004: Add Facebook support
- Migration 005: Add 2FA support
- Migration 006: Add webhooks and analytics
- Migration 007: Add email notifications
- Migration 008: Add API keys

---

## 🔐 Security Considerations

### For Facebook Integration
- Store tokens encrypted in database
- Use secure token exchange
- Implement token refresh logic
- Validate Webhook signatures

### For 2FA
- Use TOTP (not SMS—harder to spoof)
- Generate backup codes for account recovery
- Log 2FA events
- Rate-limit verification attempts

### For API Keys
- Hash keys before storage
- Implement key rotation
- Track API key usage
- Rate limiting per key
- Scope/permission system

### For Email
- Rate limit email sending
- Validate email addresses
- Unsubscribe link on all emails
- GDPR compliance (data deletion on request)

---

## 🧪 Testing Strategy

### Unit Tests
- Facebook API client functions
- TOTP generation and verification
- Analytics calculations
- Email template rendering
- API key generation and validation

### Integration Tests
- End-to-end Facebook OAuth flow
- Multi-platform post publishing
- Webhook signature verification
- Email sending via queue
- API key authentication

### User Testing
- Facebook connection flow (E2E with Playwright)
- 2FA setup and login (E2E)
- Webhook delivery (mock webhook server)
- Analytics data accuracy
- Email delivery

---

## 📱 UI/UX Updates Needed

### Settings Page Updates
- New tabs/sections for each feature
- Facebook account connection
- 2FA setup wizard
- Webhook management
- Email preferences
- API keys management

### Dashboard Updates
- Multi-platform indicators
- Analytics cards
- 2FA status badge
- Notification center

### Create Post Updates
- Platform selector (Instagram / Facebook / Both)
- Platform-specific preview
- Post status by platform

---

## ⚠️ Potential Challenges

1. **Facebook API Complexity**
   - Different rate limits per endpoint
   - OAuth token expiration handling
   - Page access validation
   - Solution: Comprehensive error handling + retry logic

2. **2FA Implementation**
   - User lockout if backup codes lost
   - Device sync issues with TOTP
   - Solution: Backup codes, support email recovery

3. **Analytics Data Freshness**
   - Instagram API doesn't return real-time insights
   - Caching strategy needed
   - Solution: Scheduled job to fetch analytics hourly

4. **Email Deliverability**
   - Spam filter issues
   - Unsubscribe management
   - Solution: Use SendGrid/reputable service

5. **Webhook Reliability**
   - Meta/Facebook webhooks can fail
   - Retry logic needed
   - Solution: Webhook retry queue + manual sync

---

## 📈 Success Metrics

- ✅ Users can connect Facebook Pages
- ✅ Posts can publish to both platforms simultaneously
- ✅ 2FA can be enabled and verified
- ✅ Webhooks receive events and auto-update post status
- ✅ Analytics dashboard shows engagement data
- ✅ Emails send for key events
- ✅ API keys work for CRUD operations

---

## 📞 Support & Rollback

### If Issues Occur
1. Disable feature flag for that feature
2. Rollback latest migration
3. Fix in development
4. Redeploy

### Database Rollback
```sql
-- Rollback Facebook integration
DROP TABLE IF EXISTS social_accounts_facebook;
ALTER TABLE posts DROP COLUMN facebook_post_id;

-- Rollback 2FA
ALTER TABLE users DROP COLUMN 2fa_enabled;
ALTER TABLE users DROP COLUMN 2fa_secret;
```

---

## 🚀 Go-Live Plan

1. **Week 1-2:** Implement all features
2. **Week 2:** Internal testing + bug fixes
3. **Week 3:** Beta testing with select users
4. **Week 3-4:** Gather feedback + refinements
5. **Week 4:** Public release with documentation
6. **Ongoing:** Monitor and support

---

## 📚 Documentation Deliverables

- User guides for each feature
- API documentation (OpenAPI/Swagger)
- Setup guides for Facebook/webhooks
- Administrator manual for managing users
- Developer guide for webhook integration
- Email template documentation

---

## ✅ Ready to Start?

**Next Steps:**
1. Create database migrations (Phase A)
2. Implement Facebook OAuth flow
3. Build Facebook publishing service
4. Update UI for platform selection
5. Test end-to-end

Shall we begin with **Phase A: Facebook Integration**? 🚀

