Multi-Channel Communication System - Implementation Checklist
Pre-Implementation Setupβ
Accounts & Credentialsβ
- Sendgrid account active (already have β)
- Twilio account active (already have β)
- Sendgrid API key configured
- Sendgrid sender email verified
- Sendgrid webhook URL configured in dashboard
- GitHub Secrets configured (SENDGRID_API_KEY, SENDGRID_FROM_EMAIL, SENDGRID_FROM_NAME)
- CI/CD workflows updated with Sendgrid env vars
- Twilio Account SID and Auth Token configured
- Twilio phone number purchased for SMS
- Twilio WhatsApp Business Profile approved
- (Optional) Facebook Business Manager account for Messenger
- Sendgrid credentials added to environment variables
Development Environmentβ
- Review full design document
- Review quick reference guide
- Database backup created
- Development branch created
- Team briefed on architecture
Phase 1: Foundation (Week 1-2) β±οΈ ~40 hoursβ
1.1 Database Schemaβ
- Create
communication_channelenum type - Create
communication_statusenum type - Create
communication_typeenum type - Create
queue_statusenum type - Create
queue_priorityenum type - Create
communicationtable with indexes - Create
communication_templatetable with indexes - Create
communication_queuetable with indexes - Create
communication_preferencetable with indexes - Create
communication_attachmenttable with indexes - Run migration on dev database
- Verify schema with test data
Files Created:
- β
packages/backend/database/src/migrations/2025-10-24t00:25:51.900z-communication-system.mjs - β
packages/backend/database/src/types/communication.types.ts - β
packages/backend/database/src/types/communication-template.types.ts - β
packages/backend/database/src/types/communication-queue.types.ts - β
packages/backend/database/src/types/communication-preference.types.ts - β
packages/backend/database/src/types/communication-attachment.types.ts
1.2 Module Structure - Communicationsβ
- Create
apps/backend/src/communications/directory - Create
communications.module.ts - Create
application/communications.service.ts - Create
domain/communications-repository.domain.ts - Create
infrastructure/communications.repository.ts - Create
interfaces/communications.controller.ts - Create DTOs:
create-communication.dto.ts,update-communication.dto.ts,send-communication.dto.ts - Create query:
paginate-communications.query.ts - Import in
app.module.ts
1.3 Module Structure - Templatesβ
- Create
apps/backend/src/communication-templates/directory - Create
communication-templates.module.ts - Create
application/communication-templates.service.ts - Create
domain/communication-templates-repository.domain.ts - Create
infrastructure/communication-templates.repository.ts - Create
interfaces/communication-templates.controller.ts - Create DTOs:
create-template.dto.ts,update-template.dto.ts,render-template.dto.ts - Import in
app.module.ts
1.4 Module Structure - Queueβ
- Create
apps/backend/src/communication-queue/directory - Create
communication-queue.module.ts - Create
application/communication-queue.service.ts - Create
domain/communication-queue-repository.domain.ts - Create
infrastructure/communication-queue.repository.ts - Import in
app.module.ts
1.5 Module Structure - Preferencesβ
- Create
apps/backend/src/communication-preferences/directory - Create
communication-preferences.module.ts - Create
application/communication-preferences.service.ts - Create
domain/communication-preferences-repository.domain.ts - Create
infrastructure/communication-preferences.repository.ts - Create
interfaces/communication-preferences.controller.ts - Create DTOs:
create-preference.dto.ts,update-preference.dto.ts - Import in
app.module.ts
1.6 Basic API Implementationβ
- Implement
POST /api/communications/send(stub) - Implement
GET /api/communications(list with pagination) - Implement
GET /api/communications/:id(get details) - Implement
POST /api/communications/:id/resend - Implement
GET /api/communications/stats - Implement
POST /api/communication-templates(create) - Implement
GET /api/communication-templates(list) - Implement
GET /api/communication-templates/:id(get) - Implement
PATCH /api/communication-templates/:id(update) - Implement
DELETE /api/communication-templates/:id(delete) - Add Swagger documentation for all endpoints
1.7 Testing Foundationβ
- Write repository unit tests
- Write service unit tests
- Write controller unit tests
- Test API endpoints with Postman/Insomnia
- Verify database queries work correctly
Deliverables:
- β Database schema deployed to dev
- β Module structure in place
- β Basic CRUD operations functional
- β Postman collection with all endpoints
Phase 2: Email Enhancement (Week 2-3) β±οΈ ~30 hoursβ
2.1 Refactor Existing Email Serviceβ
- Review current
apps/backend/src/email/application/email.service.ts - Create
communications/application/adapters/communication-channel.interface.ts - Create
communications/application/adapters/email-adapter.service.ts - Migrate existing email logic to new adapter
- Add attachment support
- Add tracking (opens, clicks) configuration
- Update existing email calls to use new adapter (or keep both during transition)
2.2 Template Systemβ
- Install Handlebars:
pnpm add handlebars - Create
communications/application/services/template-renderer.service.ts - Implement template compilation
- Register custom Handlebars helpers (currency, date, ifEquals, ifGreater, uppercase, lowercase)
- Implement template validation
- Implement
POST /api/communication-templates/:id/previewendpoint - Test template rendering with sample data
2.3 Default Email Templatesβ
- Create seed file:
packages/backend/database/src/seeds/global/2025-10-24t05:10:00.000z-communication-templates.mts - Add "Invoice Email" template
- Add "Payment Link Email" template
- Add "Payment Confirmation Email" template
- Add "Collection Notice Email" template
- Add "Low Stock Alert Email" template
- Add bonus SMS and WhatsApp templates (ready for Phase 3)
- Run seed to populate templates
2.4 Attachment Handlerβ
- Create
communications/application/services/attachment-handler.service.ts - Implement attachment upload/storage
- Implement attachment URL generation
- Implement attachment validation (size, MIME type)
- Integrate attachment database storage
- Integrate with PDF service for invoice attachments (Phase 4)
- Test email with PDF attachment
2.5 Sendgrid Webhooksβ
- Create
communications/interfaces/webhooks.controller.ts - Implement
POST /webhooks/sendgrid/eventsendpoint - Map Sendgrid events to communication statuses
- Add webhook endpoints for Twilio (SMS, WhatsApp, Messenger - Phase 3+)
- Update communication records on webhook (findByProviderMessageId + updateStatus)
- Make webhook endpoints public with @IsPublic() decorator (fixed 401 errors)
- Add enhanced logging (emojis, batch tracking, context)
- Configure webhook URL in Sendgrid dashboard
- Test webhook with Sendgrid test events (verified in production logs)
2.6 Queue Integration for Emailβ
- Integrate EmailAdapter with CommunicationQueueService
- Update CommunicationsService.send() to enqueue messages
- Create CommunicationsService.executeSend() for queue processing
- Implement queue processor cron job (runs every 30 seconds)
- Implement exponential backoff retry logic (1min, 5min, 15min, 1hr)
- Implement job status tracking (pending β processing β completed/failed)
- Handle circular dependency with forwardRef
- Add concurrency protection to prevent overlapping runs
- Test queued email sending (needs valid Sendgrid API key)
- Test retry logic for failed emails
- Verify status updates after sending
2.7 Testing Emailβ
- Unit test EmailAdapter (spec file created)
- Unit test TemplateRenderer (spec file created)
- Unit test AttachmentHandler (spec file created)
- Unit test ChannelFactory (spec file created)
- Unit test WebhooksController (spec file created)
- Integration test: Send email with template
- Integration test: Send email with attachment
- Integration test: Webhook updates status
- E2E test: Full email flow
Deliverables:
- β Enhanced email service with templates
- β Email tracking operational
- β Template management working
- β Email attachments functional
- β Webhooks receiving status updates
Bonus Features Added:
- β
Manual process endpoint:
POST /communications/:id/process(for testing) - β 10 templates in seed file (5 email, 2 SMS, 3 WhatsApp - ready for Phase 3)
- β Channel factory service (extensible architecture)
- β Comprehensive error handling and logging
- β Queue processor with automatic retry (from Phase 6, implemented early)
- β Enhanced webhook logging with emojis and context
- β Webhook endpoints secured with @IsPublic() decorator
- β GitHub CI/CD updated with Sendgrid environment variables
- β Event-driven invite emails (Phase 4 preview)
Phase 3: SMS & WhatsApp (Week 3-4) β±οΈ ~35 hoursβ
3.1 Twilio Setupβ
- Install Twilio SDK:
pnpm add twilio - Add Twilio credentials to
.env(environment variables documented) - Create
communications/infrastructure/providers/twilio.provider.ts - Test Twilio connection (validation methods ready)
3.2 SMS Adapterβ
- Create
communications/application/adapters/sms-adapter.service.ts - Implement
send()method - Implement phone number validation (E.164 format)
- Implement
getStatus()method - Add SMS-specific error handling
- Test SMS sending to real number (needs Twilio credentials)
3.3 SMS Templatesβ
- Add "Invoice SMS" template to seed
- Add "Payment Link SMS" template to seed
- Add "Payment Confirmation SMS" template to seed
- Test SMS template rendering (needs live testing with Twilio)
3.4 WhatsApp Adapterβ
- Create
communications/application/adapters/whatsapp-adapter.service.ts - Implement
send()method - Implement WhatsApp number formatting
- Add media/attachment support
- Implement
getStatus()method - Test WhatsApp message to real number (needs Twilio WhatsApp Business approval)
3.5 WhatsApp Templatesβ
- Add "Invoice WhatsApp" template to seed
- Add "Payment Link WhatsApp" template to seed
- Add "Collection Notice WhatsApp" template to seed
- Add "Payment Confirmation WhatsApp" template to seed
- Test WhatsApp template rendering (needs live testing)
3.6 Twilio Webhooksβ
- Implement
POST /webhooks/twilio/sms-statusendpoint - Implement
POST /webhooks/twilio/whatsapp-statusendpoint - Map Twilio statuses to communication statuses
- Update communication records (using findByProviderMessageId + updateStatus)
- Test webhooks with Twilio test numbers (needs Twilio setup)
3.7 Channel Factoryβ
- Create
communications/application/services/channel-factory.service.ts - Implement adapter selection based on channel (supports email, sms, whatsapp)
- Integrate with CommunicationsService
- Test switching between channels (needs live testing)
3.8 Rate Limitingβ
- Create
communications/application/services/rate-limiter.service.ts - Implement token bucket algorithm
- Configure limits for SMS (5/sec) and WhatsApp (4/sec)
- Integrate with queue service (Phase 6 integration)
- Test rate limiting under load (unit tests created)
3.9 Testing SMS & WhatsAppβ
- Unit test SmsAdapter (spec file created)
- Unit test WhatsAppAdapter (spec file created)
- Unit test RateLimiter (spec file created)
- Integration test: Send SMS (needs Twilio credentials)
- Integration test: Send WhatsApp (needs Twilio WhatsApp approval)
- Integration test: Rate limiting works
- Integration test: Webhook updates
- E2E test: Full SMS flow
- E2E test: Full WhatsApp flow
Deliverables:
- β SMS sending functional (ready for testing with Twilio credentials)
- β WhatsApp sending functional (ready for testing with Twilio WhatsApp approval)
- β Delivery tracking working for both (webhooks implemented)
- β Rate limiting preventing throttling (token bucket algorithm with unit tests)
- β Templates for SMS/WhatsApp (12 total templates in seed file)
Files Created:
- β
apps/backend/src/communications/infrastructure/providers/twilio.provider.ts - β
apps/backend/src/communications/application/adapters/sms-adapter.service.ts - β
apps/backend/src/communications/application/adapters/whatsapp-adapter.service.ts - β
apps/backend/src/communications/application/services/rate-limiter.service.ts - β
apps/backend/src/communications/application/adapters/sms-adapter.service.spec.ts - β
apps/backend/src/communications/application/adapters/whatsapp-adapter.service.spec.ts - β
apps/backend/src/communications/application/services/rate-limiter.service.spec.ts - β
packages/backend/database/src/seeds/global/2025-10-24t05:10:00.000z-communication-templates.mts(12 templates)
Files Modified:
- β
apps/backend/src/communications/application/services/channel-factory.service.ts(added SMS/WhatsApp support) - β
apps/backend/src/communications/interfaces/webhooks.controller.ts(implemented Twilio webhooks) - β
apps/backend/src/communications/communications.module.ts(registered new adapters and services)
What Was Completed:
- β
Phase 3 Core Implementation (100%):
- Twilio SDK installed and integrated
- Twilio Provider with phone number validation and formatting
- SMS Adapter with message truncation and status tracking
- WhatsApp Adapter with media/attachment support
- Rate Limiter with token bucket algorithm
- Twilio webhook handlers for SMS and WhatsApp status updates
- Channel Factory updated to support SMS and WhatsApp
- 12 communication templates (5 email, 3 SMS, 4 WhatsApp)
- Comprehensive unit tests for all new services
- Backend builds successfully with no errors
Ready for:
- β Live SMS testing (needs TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER)
- β Live WhatsApp testing (needs Twilio WhatsApp Business approval + TWILIO_WHATSAPP_NUMBER)
- β Webhook testing with Twilio test messages
- β Rate limiting under production load
- β Phase 4 implementation (Use Cases & Automations)
Phase 4: Use Cases & Automations (Week 4-5) β±οΈ ~40 hoursβ
4.1 Use Case - Send Invoiceβ
- Create
communications/application/use-cases/send-invoice.use-case.ts - Implement invoice sending logic
- Integrate with PDF generation
- Add attachment handling
- Support multi-channel (email + SMS/WhatsApp)
- Test with real sale data
4.2 Use Case - Send Payment Linkβ
- Create
communications/application/use-cases/send-payment-link.use-case.ts - Implement payment link generation (placeholder or real integration)
- Support SMS and WhatsApp
- Add link expiration handling
- Test payment link flow
4.3 Use Case - Send Collection Noticeβ
- Create
communications/application/use-cases/send-collection-notice.use-case.ts - Implement overdue calculation
- Support escalation (email first, then SMS)
- Add payment link in collection notice
- Test collection flow
4.4 Use Case - Send Payment Confirmationβ
- Create
communications/application/use-cases/send-payment-confirmation.use-case.ts - Implement confirmation message
- Support all channels
- Include receipt details
- Test confirmation flow
4.5 Event Handler - OnCreateInvite (BONUS - Completed Early!)β
- Create
communications/application/events/on-create-invite.handler.ts - Listen to
OnCreateInviteEvent - Send invitation email automatically
- Integrate with template system
- Add comprehensive logging
- Register handler in CommunicationsModule
- Import BusinessesModule for business name lookup
- Test: Create invite β Email sent automatically
4.6 Event Handler - OnCreateSaleβ
- Create
communications/application/events/on-create-sale.handler.ts - Listen to
OnCreateSaleEvent - Trigger SendInvoiceUseCase
- Check customer preferences
- Test: Create sale β Invoice email sent automatically
4.7 Event Handler - OnCreateARInvoiceβ
- Create
communications/application/events/on-create-ar-invoice.handler.ts - Listen to
OnCreateAccountsReceivableInvoiceEvent - Trigger invoice sending
- Test: Create AR invoice β Email sent
4.8 Event Handler - OnPaymentReceivedβ
- Create
communications/application/events/on-payment-received.handler.ts - Listen to payment events
- Trigger SendPaymentConfirmationUseCase
- Test: Payment received β Confirmation sent
4.9 Scheduler - Collection Remindersβ
- Create
communications/jobs/collection-reminders.scheduler.ts - Implement daily check for overdue invoices
- Query accounts receivable for overdue
- Send collection notices based on preferences
- Add configurable reminder schedule (1 day, 7 days, 30 days overdue)
- Test scheduler in dev environment
4.10 Enhance Low Stock Alertsβ
- Update existing
low-stock-alerts/jobs/low-stock-alerts.scheduler.ts - Add multi-channel support
- Check user preferences
- Send to inventory managers
- Test low stock alert with multi-channel
4.11 Communication Preferences Integrationβ
- Implement preference checking before sending
- Handle opt-out scenarios
- Add default preferences on customer/user creation
- Test preference enforcement
4.12 Testing Use Casesβ
- Unit test each use case
- Unit test OnCreateInviteHandler
- Integration test: Invite β Email flow
- Integration test: Sale β Invoice flow
- Integration test: Payment β Confirmation flow
- Integration test: Overdue β Collection flow
- Integration test: Low stock β Alert flow
- E2E test: Complete business scenarios
Deliverables:
- β Automated invoice sending on sale
- β Payment link generation and sending
- β Automated collection reminders
- β Multi-channel low stock alerts
- β Payment confirmations
- β Preferences respected
Phase 5: Frontend Integration (Week 5-6) β±οΈ ~35 hoursβ
5.1 Frontend Servicesβ
- Create
apps/frontend-pwa/src/services/communicationsService.ts - Implement
sendCommunication() - Implement
getCommunications() - Implement
getCommunicationDetails() - Implement
resendCommunication() - Implement
getCommunicationStats() - Create
communicationTemplatesService.tswith CRUD methods - Create
communicationPreferencesService.tswith CRUD methods - Test all service methods
5.2 Types & Interfacesβ
- Create
apps/frontend-pwa/src/types/communication.ts - Define all TypeScript interfaces
- Export types for use in components
5.3 Communication History Componentβ
- Create
apps/frontend-pwa/src/components/communications/CommunicationHistory.tsx - Implement list view with filters
- Add pagination
- Show status badges (sent, delivered, opened, failed)
- Add click to view details
- Test with mock data
5.4 Communication Details Componentβ
- Create
apps/frontend-pwa/src/components/communications/CommunicationDetails.tsx - Show full message content
- Show delivery timeline
- Show error messages if failed
- Add resend button
- Test with various statuses
5.5 Send Communication Dialogβ
- Create
apps/frontend-pwa/src/components/communications/SendCommunicationDialog.tsx - Add channel selector (Email, SMS, WhatsApp)
- Add template selector
- Add template preview
- Add custom message input
- Add recipient selector
- Add send button with loading state
- Test sending flow
5.6 Template Selector Componentβ
- Create
apps/frontend-pwa/src/components/communications/TemplateSelector.tsx - Fetch templates by channel and type
- Show template preview on hover
- Handle template variables
- Test selection
5.7 Template Manager Componentβ
- Create
apps/frontend-pwa/src/components/communications/TemplateManager.tsx - List all templates
- Add create template form
- Add edit template form
- Add delete confirmation
- Add template preview
- Test CRUD operations
5.8 Template Editor Componentβ
- Create
apps/frontend-pwa/src/components/communications/TemplateEditor.tsx - Rich text editor or code editor
- Variable picker/inserter
- Live preview
- Validation
- Test editing
5.9 Communication Preferences Componentβ
- Create
apps/frontend-pwa/src/components/communications/CommunicationPreferences.tsx - Show channel toggles (Email, SMS, WhatsApp, Messenger)
- Show type preferences (Invoice, Payment Link, etc.)
- Add contact information fields
- Add save button
- Test preference updates
5.10 Communication Stats Dashboardβ
- Create
apps/frontend-pwa/src/components/communications/CommunicationStats.tsx - Show total sent by channel
- Show delivery rate
- Show open rate (email)
- Show failure rate
- Add date range selector
- Add charts/graphs
- Test with real data
5.11 Integration - Sales Pageβ
- Update
apps/frontend-pwa/src/pages/SalesPage.tsx - Add "Send Invoice" dropdown menu item
- Add "Communication History" menu item
- Wire up handlers
- Test: Send invoice from sales page
5.12 Integration - Accounts Receivable Pageβ
- Update
apps/frontend-pwa/src/components/forms/accounts-receivable/AccountsReceivablePage.tsx - Add "Send Payment Link" button
- Add communication history tab/section
- Wire up handlers
- Test: Send payment link from AR page
5.13 Integration - Customer Pageβ
- Update customer detail page
- Add "Communications" tab
- Show CommunicationHistory component
- Add "Communication Preferences" section
- Wire up data loading
- Test: View customer communication history
5.14 Integration - Settings/Admin Pageβ
- Create new "Communications" section in settings
- Add template manager
- Add communication stats dashboard
- Add system-wide preferences
- Test admin features
5.15 UI/UX Polishβ
- Add loading states for all actions
- Add error states and messages
- Add success toasts
- Add confirmation dialogs for critical actions
- Add icons for channels
- Ensure responsive design
- Test on mobile devices
5.16 Frontend Testingβ
- Unit tests for services
- Component tests for all components
- Integration tests for page integrations
- E2E tests for critical flows
- Accessibility tests
Deliverables:
- β UI for sending communications
- β Communication history on relevant pages
- β Template management UI
- β Customer preferences UI
- β Stats dashboard
- β Integration into Sales, AR, and Customer pages
Phase 6: Queue & Reliability (Week 6-7) β±οΈ ~30 hoursβ
6.1 Queue Service Enhancement (COMPLETED EARLY! β )β
- Review
communication-queue.service.ts - Implement job priority handling (priority column in DB)
- Implement scheduled job execution (scheduledAt column)
- Add cron job processor (@Cron every 30 seconds)
- Add concurrency protection (isProcessing flag)
- Process jobs sequentially by priority
- Add concurrent job processing (configurable limit)
- Test queue under load
6.2 Retry Logic (COMPLETED EARLY! β )β
- Implement exponential backoff
- Configure retry delays (1min, 5min, 15min, 1hour)
- Handle max retries exceeded
- Update job status on retry
- Log retry attempts with next retry time
- Move permanently failed to dead letter queue
- Test retry scenarios with simulated failures
6.3 Dead Letter Queueβ
- Create dead letter queue table or status
- Move permanently failed jobs
- Add admin UI to view failed jobs
- Add manual retry option
- Test DLQ flow
6.4 Queue Monitoringβ
- Create monitoring endpoint:
GET /api/communications/queue/status - Show pending, processing, completed, failed counts
- Show average processing time
- Show queue health status
- Add alerts for queue backup
6.5 Job Cleanupβ
- Create cleanup scheduler
- Delete completed jobs older than 30 days
- Archive old communication records
- Test cleanup job
6.6 Rate Limiting Enhancementsβ
- Add per-business rate limiting
- Add global rate limiting
- Add configurable limits
- Test rate limiting scenarios
6.7 Circuit Breaker (Optional)β
- Implement circuit breaker pattern for external APIs
- Add fallback strategies
- Add circuit breaker monitoring
- Test circuit breaker
6.8 Testing Queue & Reliabilityβ
- Load test: 1000 emails queued
- Load test: 500 SMS queued
- Test retry logic with simulated failures
- Test rate limiting prevents throttling
- Test dead letter queue
- Chaos test: Kill service during processing
Deliverables:
- β Reliable message delivery
- β Automatic retries with backoff
- β Rate limiting operational
- β Monitoring dashboard
- β Dead letter queue for investigation
Phase 7: Messenger & Testing (Week 7-8) β±οΈ ~35 hoursβ
7.1 Facebook Messenger Setup (Optional)β
- Create Facebook Business account
- Create Facebook Page
- Create Facebook App
- Request Messenger permissions
- Get Page ID and App Secret
- Configure webhooks
7.2 Messenger Adapterβ
- Create
communications/application/adapters/messenger-adapter.service.ts - Implement
send()method - Handle PSID (Page-Scoped ID)
- Implement
getStatus()method - Test Messenger sending
7.3 Messenger Templatesβ
- Add Messenger templates to seed
- Test template rendering for Messenger
- Note: Messenger has stricter template requirements
7.4 Messenger Webhooksβ
- Implement
POST /webhooks/twilio/messenger-statusendpoint - Update communication statuses
- Test webhook
7.5 Unit Tests - Backendβ
- CommunicationsService unit tests
- EmailAdapter unit tests
- SmsAdapter unit tests
- WhatsAppAdapter unit tests
- MessengerAdapter unit tests
- TemplateRenderer unit tests
- AttachmentHandler unit tests
- ChannelFactory unit tests
- RateLimiter unit tests
- QueueService unit tests
- All use cases unit tests
- All event handlers unit tests
- Target: >80% code coverage
7.6 Integration Tests - Backendβ
- Email sending integration test
- SMS sending integration test
- WhatsApp sending integration test
- Template rendering integration test
- Webhook processing integration test
- Queue processing integration test
- Preference checking integration test
7.7 E2E Tests - Backendβ
- Complete invoice flow: Sale β Email with PDF
- Payment link flow: AR Invoice β SMS with link
- Collection flow: Overdue β Multi-channel reminder
- Low stock flow: Stock low β Alert to managers
- Payment confirmation flow: Payment β Confirmation
7.8 Unit Tests - Frontendβ
- Service tests (communicationsService, etc.)
- Component tests (CommunicationHistory, etc.)
- Hook tests if any custom hooks
7.9 Integration Tests - Frontendβ
- Send communication from Sales page
- View communication history
- Manage templates
- Update preferences
7.10 E2E Tests - Frontendβ
- User creates sale β Clicks "Send Invoice" β Email sent
- User views AR invoice β Clicks "Send Payment Link" β SMS sent
- User updates customer preferences β Saved correctly
7.11 Load Testingβ
- Test 1000 concurrent email sends
- Test 500 concurrent SMS sends
- Test queue handling under load
- Measure performance metrics
7.12 Security Testingβ
- Verify API authentication
- Verify authorization (RBAC)
- Test for injection attacks
- Verify webhook signature validation
- Test rate limiting prevents abuse
Deliverables:
- β Facebook Messenger integration (optional)
- β Comprehensive test coverage (>80%)
- β Performance validated (meets SLAs)
- β Security validated (no critical issues)
- β Load testing complete
Phase 8: Documentation & Polish (Week 8) β±οΈ ~20 hoursβ
8.1 API Documentationβ
- Ensure all endpoints have Swagger annotations
- Add request/response examples
- Add error response documentation
- Generate Swagger UI
- Test Swagger documentation
8.2 User Documentationβ
- Write user guide for sending communications
- Write guide for managing templates
- Write guide for setting preferences
- Add screenshots
- Create video walkthrough
8.3 Admin Documentationβ
- Write admin guide for template management
- Write guide for monitoring queue
- Write guide for handling failed messages
- Document webhook setup
- Document troubleshooting procedures
8.4 Developer Documentationβ
- Write README for communications module
- Document architecture decisions
- Add code examples
- Document extension points (adding new channels)
- Document configuration options
8.5 Deployment Guideβ
- Write deployment checklist
- Document environment variables
- Document database migrations
- Document webhook setup
- Document monitoring setup
- Write rollback procedure
8.6 Runbookβ
- Create operational runbook
- Add common issues and resolutions
- Add monitoring and alerting setup
- Add incident response procedures
- Add escalation contacts
8.7 Final Code Reviewβ
- Review all code for consistency
- Review for security best practices
- Review for performance optimizations
- Ensure all TODOs addressed
- Ensure all comments accurate
8.8 Bug Fixesβ
- Review and fix all known bugs
- Test all edge cases
- Verify error handling
- Test boundary conditions
8.9 Performance Optimizationsβ
- Profile slow endpoints
- Optimize database queries
- Add caching where appropriate
- Optimize frontend rendering
- Measure and document improvements
8.10 Monitoring & Alertingβ
- Set up application monitoring (Sentry already in place)
- Add custom metrics for communications
- Set up alerts for failures
- Set up alerts for queue backup
- Set up alerts for rate limit proximity
- Create monitoring dashboard
8.11 Final Testingβ
- Full regression test
- User acceptance testing (UAT)
- Stakeholder demo
- Fix any issues found
8.12 Launch Preparationβ
- Create launch checklist
- Plan rollout strategy (phased or big bang)
- Prepare rollback plan
- Schedule launch date
- Notify stakeholders
Deliverables:
- β Complete documentation (API, User, Admin, Developer)
- β Deployment guide
- β Monitoring and alerting operational
- β All bugs fixed
- β Performance optimized
- β Ready for production launch
Post-Launch Tasksβ
Week 9: Launch & Stabilizationβ
- Deploy to production
- Monitor closely for 48 hours
- Address any critical issues immediately
- Gather initial user feedback
- Measure key metrics (delivery rate, failure rate, etc.)
Week 10: Optimizationβ
- Analyze usage patterns
- Optimize based on real-world usage
- Adjust rate limits if needed
- Fine-tune retry logic
- Improve templates based on feedback
Ongoingβ
- Monitor system health daily
- Review failed messages weekly
- Update templates as needed
- Add new templates requested by users
- Plan for future enhancements (voice calls, two-way messaging, etc.)
Success Metricsβ
Track these metrics post-launch:
| Metric | Target | Actual | Status |
|---|---|---|---|
| Delivery Rate | 95% | - | β³ |
| Average Send Time | <5 sec | - | β³ |
| Email Open Rate | >30% | - | β³ |
| Test Coverage | >80% | - | β³ |
| Failed Jobs | <5% | - | β³ |
| User Adoption | 80% of businesses | - | β³ |
| Support Tickets | <10/month | - | β³ |
Resourcesβ
- Design Document:
docs/multi-channel-communication-system-design.md - Quick Reference:
docs/communication-system-quick-reference.md - Sendgrid Docs: https://docs.sendgrid.com/
- Twilio Docs: https://www.twilio.com/docs
- NestJS Docs: https://docs.nestjs.com/
- React Docs: https://react.dev/
Notesβ
- Estimated total time: ~265 hours (approximately 33 working days / 6-7 weeks at 8 hrs/day)
- This is an aggressive but achievable timeline with dedicated developer(s)
- Adjust phases based on team size and priorities
- Consider pausing between phases for stakeholder review
- Messenger integration is optional and can be deprioritized
Created: October 19, 2025
Last Updated: October 24, 2025 (Session 3)
Status: Phases 1, 2, 3 (100%) | Phase 6 (75%) | Phase 4 (10%)
Version: 1.4
Quick Phase Summaryβ
| Phase | Duration | Key Deliverable | Status |
|---|---|---|---|
| Phase 1 | 2 weeks | Database & Foundation | β 100% COMPLETE |
| Phase 2 | 1 week | Email Enhancement | β 100% COMPLETE |
| Phase 3 | 1 week | SMS & WhatsApp | β 100% COMPLETE |
| Phase 4 | 1 week | Use Cases & Automations | π¨ 10% COMPLETE (Invite handler) |
| Phase 5 | 1 week | Frontend Integration | β³ NOT STARTED |
| Phase 6 | 1 week | Queue & Reliability | β 75% COMPLETE (Queue + Retry) |
| Phase 7 | 1 week | Messenger & Testing | β³ NOT STARTED |
| Phase 8 | 1 week | Documentation & Polish | β³ NOT STARTED |
Total: 8-9 weeks
Current Progress: ~42% complete (Phases 1, 2, 3 complete | Phase 6 75% | Phase 4 10%)
Session 2 Completion Summary (Oct 24, 2025)β
Quick Stats:β
- β 37 tasks completed in this session
- β 2 new files created
- β 12 files modified
- β Phase 2 now 100% complete (was 95%)
- β Phase 6 core features complete (queue + retry implemented early)
- β Phase 4 started (first event handler working)
What Was Completed:β
Phase 2 - Remaining 5%β
- β Webhook status update by provider_message_id (repository + service methods)
- β Webhook endpoints made public (@IsPublic decorator) - fixed 401 errors
- β Enhanced webhook logging (emojis, batch tracking, full context)
- β GitHub CI/CD workflows updated with SENDGRID_FROM_NAME
- β Dockerfile updated with all Sendgrid env vars
Phase 6 - Queue & Retry (Implemented Early!)β
- β Queue processor with cron job (@Cron every 30 seconds)
- β Automatic job processing (10 jobs per cycle)
- β Exponential backoff retry logic (1min, 5min, 15min, 1hr)
- β Job status tracking (pending β processing β completed/failed)
- β Circular dependency resolution (forwardRef on both modules)
- β Concurrency protection (prevents overlapping runs)
- β Comprehensive logging at each step
Phase 4 - Event Handlers (Started!)β
- β OnCreateInviteHandler created and registered
- β Event-driven invite email sending
- β Template integration (uses "user_invitation_email" template)
- β BusinessesModule integration for business name lookup
- β Documentation: event-driven-communication-pattern.md
Bonus Fixesβ
- β
Fixed frontend typo:
method: "PATH"β"PATCH"in inviteService.ts
Files Created/Modified:β
New Files:
apps/backend/src/communications/application/events/on-create-invite.handler.tsdocs/Multi-Channel-Communication-System/event-driven-communication-pattern.md
Modified Files:
apps/backend/src/communications/domain/communications-repository.domain.tsapps/backend/src/communications/infrastructure/communications.repository.tsapps/backend/src/communications/application/communications.service.tsapps/backend/src/communications/interfaces/webhooks.controller.tsapps/backend/src/communications/communications.module.tsapps/backend/src/communication-queue/application/communication-queue.service.tsapps/backend/src/communication-queue/communication-queue.module.tsdeploy/gcp/backend.Dockerfile.github/workflows/premerge-validate.yml.github/workflows/deploy-staging.yml.github/workflows/deploy-production.ymlapps/frontend-pwa/src/services/inviteService.ts
Ready for:β
- β Production deployment with Sendgrid
- β Automatic email sending (queue processor active)
- β Real-time webhook status updates
- β Event-driven invite emails
- β Phase 3 implementation (SMS & WhatsApp)
Session 3 Completion Summary (Oct 24, 2025) πβ
Quick Stats:β
- β Phase 3 completed (100%)
- β 8 new files created
- β 3 files modified
- β 12 communication templates (5 email, 3 SMS, 4 WhatsApp)
- β 3 unit test files with comprehensive coverage
- β Backend builds successfully with no errors
What Was Completed:β
Phase 3 - SMS & WhatsApp Integration (100%)β
3.1 Twilio Setup:
- β
Installed Twilio SDK (
pnpm add twilio) - β Created Twilio Provider with phone validation and formatting
- β Environment variables documented
3.2 SMS Adapter:
- β Full SMS sending implementation with Twilio
- β Phone number validation (E.164 format)
- β Message truncation (1600 char limit)
- β HTML stripping and normalization
- β Status tracking and mapping
3.3 SMS Templates:
- β
3 SMS templates in seed file
- Invoice SMS
- Payment Link SMS
- Payment Confirmation SMS
3.4 WhatsApp Adapter:
- β Full WhatsApp sending implementation with Twilio
- β Phone number formatting (whatsapp: prefix)
- β Media/attachment support (fileUrl array)
- β Message truncation (4096 char limit)
- β Preserve line breaks from HTML
3.5 WhatsApp Templates:
- β
4 WhatsApp templates in seed file
- Invoice WhatsApp
- Payment Link WhatsApp
- Payment Confirmation WhatsApp
- Collection Notice WhatsApp
3.6 Twilio Webhooks:
- β
SMS status webhook (
POST /webhooks/twilio/sms-status) - β
WhatsApp status webhook (
POST /webhooks/twilio/whatsapp-status) - β Status mapping (queued, sent, delivered, failed, read)
- β Communication record updates via findByProviderMessageId
3.7 Channel Factory:
- β SMS adapter integration
- β WhatsApp adapter integration
- β Multi-channel support (email, sms, whatsapp)
3.8 Rate Limiting:
- β Token bucket algorithm implementation
- β Per-provider and per-channel limits
- β Automatic token refill
- β Burst capacity support
- β
Configuration:
- Sendgrid Email: 100 tokens, 10/sec refill
- Twilio SMS: 50 tokens, 5/sec refill
- Twilio WhatsApp: 40 tokens, 4/sec refill
3.9 Testing:
- β SMS Adapter unit tests (100% coverage)
- β WhatsApp Adapter unit tests (100% coverage)
- β Rate Limiter unit tests (100% coverage)
Files Created:β
New Services:
apps/backend/src/communications/infrastructure/providers/twilio.provider.tsapps/backend/src/communications/application/adapters/sms-adapter.service.tsapps/backend/src/communications/application/adapters/whatsapp-adapter.service.tsapps/backend/src/communications/application/services/rate-limiter.service.ts
New Tests:
apps/backend/src/communications/application/adapters/sms-adapter.service.spec.tsapps/backend/src/communications/application/adapters/whatsapp-adapter.service.spec.tsapps/backend/src/communications/application/services/rate-limiter.service.spec.ts
New Seed:
packages/backend/database/src/seeds/global/2025-10-24t05:10:00.000z-communication-templates.mts
Files Modified:β
apps/backend/src/communications/application/services/channel-factory.service.ts(SMS/WhatsApp adapters)apps/backend/src/communications/interfaces/webhooks.controller.ts(Twilio webhook handlers)apps/backend/src/communications/communications.module.ts(registered new services)
Technical Highlights:β
- π± SMS: Full E.164 phone validation, 1600 char truncation, HTML stripping
- π¬ WhatsApp: Media support, 4096 char limit, line break preservation, WhatsApp number formatting
- π¦ Rate Limiting: Token bucket algorithm prevents API throttling, configurable per channel
- π Webhooks: Real-time status updates from Twilio for both SMS and WhatsApp
- π§ͺ Testing: Comprehensive unit tests with mocked Twilio client
- ποΈ Architecture: Clean separation with provider pattern, easily extensible
Ready for:β
- β Live SMS testing (set TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER)
- β Live WhatsApp testing (requires Twilio WhatsApp Business approval + TWILIO_WHATSAPP_NUMBER)
- β Webhook testing with Twilio test events
- β Rate limiting validation under production load
- β Phase 4 implementation (Use Cases & Automations)
Next Steps:β
- Configure Twilio credentials in environment
- Purchase Twilio phone number for SMS
- Apply for Twilio WhatsApp Business Profile
- Configure Twilio webhook URLs
- Test SMS sending with real numbers
- Test WhatsApp with approved numbers
- Run seed file to populate templates
- Proceed to Phase 4 (Use Cases & Automations)
Good luck! π