Skip to content

WhatsApp Trigger Workflow

This workflow serves as the main entry point for WhatsApp messages in a youth entrepreneurship coaching program. It intelligently routes messages based on user status and time of day, handling both regular coaching conversations and weekly report submissions while implementing daytime message queuing and comprehensive error handling.

Purpose

No business context provided yet — add a context.md to enrich this documentation.

Based on the workflow structure, this appears to be part of a youth entrepreneurship program that provides coaching through WhatsApp. The system manages different conversation types (regular coaching vs. weekly reports) and implements time-based message handling to ensure appropriate response timing.

How It Works

  1. Message Reception: Receives WhatsApp messages via webhook and extracts configuration constants
  2. User Lookup: Queries the database to find the user record based on phone number
  3. User Validation: Checks if the user exists in the system - new users are processed immediately
  4. Activity Tracking: Updates the user's last inbound message timestamp for existing users
  5. Time-Based Routing: For existing users, checks if it's daytime (4 AM - 7 PM Nairobi time) and if evening session hasn't started
  6. Message Queuing: Daytime messages are stored in a pending queue for later processing
  7. Conversation Routing: Evening messages are routed based on user's current stage:
    • Weekly report stages go to the Weekly Report Handler
    • Other stages go to the Sales Tracking Agent
  8. Response Processing: Validates agent responses and handles successful replies
  9. Error Handling: Logs errors and sends fallback messages when agents fail
  10. Message Dispatch: Sends responses back through the external dispatch system

Workflow Diagram

graph TD
    A[DevelopmentWebhook] --> B[Set Constants]
    B --> C[getUserRecord]
    C --> D[ifUserNotFound]
    D -->|New User| E[setUserPhoneNumnberAndQuery]
    D -->|Existing User| F[updateLastInboundAt]
    F --> G[isDaytimeMessage]
    G -->|Daytime| H[storeDaytimeMessage]
    G -->|Evening| E
    H --> E
    E --> I[Set Turn Timestamp]
    I --> J[isWeeklyReport]
    J -->|Weekly Report| K[Set WR Input]
    J -->|Regular Chat| L[Call Sales Tracking Agent]
    K --> M[Call Weekly Report Handler]
    M --> N[hasAgentOutput]
    L --> N
    N -->|Success| O[HTTP Request1]
    N -->|Failure| P[logError]
    P --> Q[setFallbackMessage]
    Q --> R[logChatFallback]
    Q --> S[HTTP Request2]

Trigger

Webhook Trigger: Listens for POST requests at path 98ed6d7d-5af1-4500-878f-56b7f22cad75. This webhook receives WhatsApp message data including: - WaId: User's WhatsApp ID (phone number) - Body: Message content - From: Sender information - DispatchBackTo: Optional callback URL

Nodes Used

Node Type Node Name Purpose
Webhook DevelopmentWebhook Receives incoming WhatsApp messages
Set Set Constants Configures base URL and webhook token
Postgres getUserRecord Retrieves user information from database
If ifUserNotFound Routes new vs existing users
Postgres updateLastInboundAt Updates user's last activity timestamp
If isDaytimeMessage Checks if message is during daytime hours
Postgres storeDaytimeMessage Queues daytime messages for later processing
Set setUserPhoneNumnberAndQuery Prepares user data for processing
Set Set Turn Timestamp Records conversation turn timestamp
If isWeeklyReport Routes based on user's current stage
Set Set WR Input Prepares data for weekly report handler
Execute Workflow Call Weekly Report Handler Processes weekly report conversations
Execute Workflow Call Sales Tracking Agent Handles regular coaching conversations
If hasAgentOutput Validates agent response
HTTP Request HTTP Request1 Dispatches successful responses
Postgres logError Records errors for debugging
Set setFallbackMessage Creates fallback response
Postgres logChatFallback Logs fallback conversations
HTTP Request HTTP Request2 Dispatches fallback responses

External Services & Credentials Required

Database Connections

  • Postgres account 2 (7qvANxg1uH6hles5): Main database connection for user records, message queuing, error logging, and chat logging

HTTP Authentication

  • FastAPI dispatcher (HcWCeoa3MLd3HcAJ): HTTP header authentication for message dispatch API

External APIs

  • Message Dispatch API: Sends responses back to users via configurable base URL
  • Weekly Report Handler Workflow: Processes weekly report conversations
  • Sales Tracking Agent Workflow: Handles regular coaching interactions

Environment Variables

The workflow uses dynamic configuration through the webhook payload: - DispatchBackTo: Optional callback URL (defaults to https://sifa.alpha-test.kriftx.app/webhooks/n8n/dispatch) - Webhook token: DCoW5pU2PxCLTOqJtW7K0I-evhg4ZFJ4mv83TGkQG5c

Data Flow

Input

  • WhatsApp webhook payload containing user phone number, message content, and sender information

Processing

  • User lookup and validation
  • Time-based message routing
  • Conversation type detection
  • Agent response generation
  • Error handling and fallback responses

Output

  • Agent responses dispatched to users
  • Message logs stored in database
  • Error logs for debugging
  • Queued daytime messages for later processing

Error Handling

The workflow implements comprehensive error handling:

  1. Database Errors: User lookup continues on error to handle new users
  2. Agent Failures: Both sub-workflows have error handling that continues execution
  3. Error Logging: Failed agent calls are logged to errorLog table with details
  4. Fallback Messages: Users receive a polite Swahili fallback message when agents fail
  5. Graceful Degradation: System continues operating even when individual components fail

Known Limitations

  • Daytime message queuing requires manual processing or separate workflow to handle queued messages
  • Hard-coded webhook token may need rotation
  • Time zone handling is fixed to Africa/Nairobi
  • No retry mechanism for failed HTTP dispatches
  • Weekly Report Handler (UmXTl93UZT4C9o9q): Processes weekly report conversations
  • Francis - SalesTrackingAgent (MBUCWxZ2NnrrKMzz): Handles regular coaching interactions

Setup Instructions

  1. Import Workflow: Import the JSON into your n8n instance
  2. Configure Database: Set up PostgreSQL connection with these tables:
    • youthEntrepreneursReal: User records with phone numbers and status
    • pendingDaytimeMessages: Queue for daytime messages
    • errorLog: Error tracking
    • chatLog: Conversation history
  3. Set Up Credentials:
    • Create PostgreSQL credential named "Postgres account 2"
    • Create HTTP header auth credential named "FastAPI dispatcher"
  4. Configure Sub-workflows: Ensure the Weekly Report Handler and Sales Tracking Agent workflows are available
  5. Test Webhook: Send test POST requests to the webhook URL to verify message processing
  6. Monitor Logs: Check error logs and chat logs to ensure proper operation

The workflow will automatically activate and begin processing WhatsApp messages according to the configured routing logic.