Skip to content

πŸ’¬ WhatsApp Conversation Flows

⚠️ POST-MVP FEATURE: This feature is planned for Month 3-6 after MVP launch. MVP will use email notifications for critical alerts.

Scope: Post-MVP Enhancement Status: Planned for Month 3-6 API: Twilio WhatsApp Business API

Overview

WhatsApp integration provides a conversational interface for compliance tasks, enabling quick responses and updates without logging into the web platform.

Use Cases

1. Quick Status Check

User: "What's our Essential Eight status?"
Bot: "Essential Eight Maturity:
β€’ Application Control: ML2 βœ“
β€’ Patching: ML2 βœ“
β€’ MFA: ML1 ⚠️ (Action needed)
β€’ Overall: 71%

Need details on MFA? Reply 'MFA'"

2. Task Notifications

Bot: "πŸ”΄ Critical Task Alert

Update Application Control Policy
Due: Tomorrow (24 Jan)
Impact: Essential Eight compliance at risk

Reply:
β€’ 'DETAILS' for more info
β€’ 'ASSIGN' to delegate
β€’ 'DONE' when complete"

User: "ASSIGN @john"
Bot: "Assigned to John Smith. He'll receive a notification."

3. Evidence Collection

Bot: "Please provide evidence for MFA implementation.
You can:
β€’ Send a photo of the policy
β€’ Forward the PDF document
β€’ Reply 'LATER' to defer"

User: [Sends PDF]
Bot: "Received 'MFA-Policy-2024.pdf'
Uploaded to Evidence Library βœ“
MFA compliance updated to ML2."

4. Board Report Request

User: "Generate board report"
Bot: "Generating Q1 2024 Board Security Report...

βœ“ Report ready!
πŸ“Š Compliance: 78% (β–²5% from last quarter)
πŸ”΄ Critical items: 2
βœ… Completed this quarter: 8

Send to your email? Reply 'YES' or 'NO'"

Technical Implementation

Message Flow Architecture

WhatsApp β†’ Twilio β†’ Webhook β†’ GetCimple API
   ↑                                    ↓
   ←──────────── Response β†β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Webhook Handler

import { validateTwilioWebhook } from './security'
import { MessageParser } from './parser'
import { ComplianceAgent } from './agent'

export async function handleWhatsAppWebhook(req: Request) {
  // Validate webhook signature
  if (!validateTwilioWebhook(req)) {
    return new Response('Unauthorized', { status: 401 })
  }

  const { From, Body, MediaUrl0 } = await req.formData()

  // Parse message intent
  const intent = MessageParser.parse(Body)

  // Handle based on intent
  const response = await ComplianceAgent.handle({
    intent,
    userId: From,
    message: Body,
    media: MediaUrl0,
  })

  // Format WhatsApp response
  return formatTwilioResponse(response)
}

Message Parser

class MessageParser {
  static intents = {
    STATUS_CHECK: /^(status|E8|essential eight|compliance)/i,
    TASK_ACTION: /^(DETAILS|ASSIGN|DONE|DEFER)/i,
    EVIDENCE_UPLOAD: /^(evidence|upload|document)/i,
    REPORT_REQUEST: /^(report|board report|generate)/i,
    HELP: /^(help|commands|what can you do)/i,
  }

  static parse(message: string): Intent {
    for (const [intent, regex] of Object.entries(this.intents)) {
      if (regex.test(message)) {
        return { type: intent, raw: message }
      }
    }
    return { type: 'UNKNOWN', raw: message }
  }
}

Session Management

interface WhatsAppSession {
  userId: string
  phoneNumber: string
  context: {
    lastIntent: string
    lastTaskId?: string
    awaitingResponse?: string
    conversationHistory: Message[]
  }
  tenantId: string
}

// Redis-backed session store
class SessionManager {
  async getSession(phoneNumber: string): Promise<WhatsAppSession> {
    const cached = await redis.get(`wa:session:${phoneNumber}`)
    if (cached) return JSON.parse(cached)

    // Create new session
    const user = await getUserByPhone(phoneNumber)
    const session = {
      userId: user.id,
      phoneNumber,
      context: { conversationHistory: [] },
      tenantId: user.tenantId,
    }

    await redis.setex(
      `wa:session:${phoneNumber}`,
      3600,
      JSON.stringify(session)
    )
    return session
  }
}

Message Templates

Compliance Status Template

name: compliance_status
variables:
  - framework_name
  - overall_score
  - critical_items
  - improvements
template: |
  πŸ“Š {{framework_name}} Status

  Overall: {{overall_score}}%
  Critical items: {{critical_items}}

  Recent improvements:
  {{improvements}}

  Reply 'DETAILS' for full breakdown

Task Notification Template

name: task_notification
variables:
  - priority_emoji
  - task_title
  - due_date
  - impact
template: |
  {{priority_emoji}} Task Alert

  {{task_title}}
  Due: {{due_date}}
  Impact: {{impact}}

  Actions:
  β€’ 'DETAILS' - View full details
  β€’ 'ASSIGN @name' - Delegate task
  β€’ 'DONE' - Mark complete

Security Considerations

Authentication Flow

1. User registers phone in web app
2. Verification code sent via WhatsApp
3. User confirms code in web app
4. Phone number linked to account
5. All messages authenticated via phone

Data Protection

  • No sensitive data in messages
  • Documents encrypted in transit
  • 24-hour message retention
  • Audit trail for all actions

Rate Limiting

const RATE_LIMITS = {
  messages_per_hour: 20,
  reports_per_day: 5,
  evidence_uploads_per_day: 10,
}

User Commands

Core Commands

STATUS - View compliance status
TASKS - List pending tasks
REPORT - Generate board report
HELP - Show available commands

Task Commands

DETAILS [task_id] - View task details
ASSIGN @username [task_id] - Delegate task
DONE [task_id] - Mark task complete
DEFER [task_id] [date] - Postpone task

Evidence Commands

UPLOAD - Start evidence upload flow
LIST EVIDENCE - Show recent uploads
LINK [doc_id] TO [task_id] - Link evidence

Integration with Core Platform

Event Triggers

// Send WhatsApp notification on critical task
on('task.created', async (task) => {
  if (task.priority === 'critical') {
    const users = await getTaskRecipients(task)
    for (const user of users) {
      if (user.whatsappEnabled) {
        await sendWhatsAppNotification(user.phone, {
          template: 'task_notification',
          variables: {
            priority_emoji: 'πŸ”΄',
            task_title: task.title,
            due_date: task.dueDate,
            impact: task.impact,
          },
        })
      }
    }
  }
})

Data Sync

// Sync WhatsApp actions to main database
async function syncWhatsAppAction(action: WhatsAppAction) {
  switch (action.type) {
    case 'TASK_COMPLETE':
      await taskService.markComplete(action.taskId, action.userId)
      break
    case 'EVIDENCE_UPLOAD':
      await evidenceService.store(action.file, action.metadata)
      break
    case 'TASK_ASSIGN':
      await taskService.reassign(action.taskId, action.assigneeId)
      break
  }

  // Log action for audit
  await auditLog.record({
    action: action.type,
    user: action.userId,
    channel: 'WhatsApp',
    timestamp: new Date(),
  })
}

Analytics & Monitoring

Key Metrics

-- WhatsApp engagement metrics
SELECT
  COUNT(DISTINCT user_id) as daily_active_users,
  COUNT(*) as total_messages,
  AVG(response_time) as avg_response_time,
  COUNT(CASE WHEN intent = 'TASK_COMPLETE' THEN 1 END) as tasks_completed
FROM WhatsApp_interactions
WHERE date = CURRENT_DATE;

Success Metrics

  • Message response time < 2 seconds
  • Task completion via WhatsApp > 30%
  • User engagement rate > 60%
  • Error rate < 1%

Implementation Checklist

  • Set up Twilio WhatsApp Business account
  • Configure webhook endpoints
  • Implement message parser
  • Build session management
  • Create message templates
  • Add authentication flow
  • Implement rate limiting
  • Build command handlers
  • Add file upload support
  • Create analytics dashboard
  • Write user documentation
  • Test conversation flows

Related Documents: