Skip to content

V4 - WhatsAppTrigger - Web

This workflow serves as the main entry point for processing incoming WhatsApp messages in the Sifa V4 system. It handles user authentication, message routing, agent processing, and response delivery through a comprehensive pipeline that includes error handling, logging, and integration with external messaging services.

Purpose

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

How It Works

  1. Message Reception: The workflow starts when a WhatsApp message is received via webhook
  2. User Lookup: Queries the database to find the user's record based on their phone number
  3. User Routing: If the user is not found, routes them to an organic handler for new user onboarding
  4. Activity Tracking: Updates the user's last inbound message timestamp
  5. Message Processing: Prepares user data and sends the message to the Francis SalesTrackingAgent
  6. Response Validation: Checks if the agent returned a valid response
  7. Message Formatting: Processes the agent's response through a MessageInterceptor for proper formatting
  8. Interactive Content Check: Determines if the response contains interactive elements (buttons, forms)
  9. Variable Processing: Handles special formatting for certain content types
  10. Response Delivery: Forwards the formatted response back to the FastAPI service for delivery
  11. Error Handling: Logs errors and provides fallback messages when processing fails
  12. Chat Logging: Records all interactions for monitoring and analysis

Workflow Diagram

graph TD
    A[DevelopmentWebhook] --> B[getUserRecord]
    B --> C[ifUserNotFound]
    C -->|User Not Found| D[callOrganicHandler]
    C -->|User Found| E[updateLastInboundAt]
    E --> F[setUserPhoneNumnberAndQuery]
    F --> G["Call 'Francis - SalesTrackingAgent'"]
    G -->|Success| H[hasAgentOutput]
    G -->|Error| I[logError]
    H -->|Valid Output| J["Call 'V4 - MessageInterceptor'"]
    H -->|No Output| I
    I --> K[setFallbackMessage]
    J --> L[isInteractive?]
    L -->|Has Interactive Content| M[Variables]
    L -->|No Interactive Content| N[Forward reply to FastAPI]
    M --> N
    K --> O[logChatFallback]
    K --> N

    %% Daytime message handling (currently disabled)
    P[isDaytimeMessage] --> Q[storeDaytimeMessage]
    Q --> R[isWeeklyReport]
    R --> S[Set WR Input]
    S --> T[Call Weekly Report Handler]

Trigger

Webhook: POST request to endpoint 95e6d98e-7599-49ff-abbf-6d744ca0c7b9 - Receives WhatsApp message data from external messaging service - Expects JSON payload with user phone number, message content, and metadata

Nodes Used

Node Type Node Name Purpose
Webhook DevelopmentWebhook Receives incoming WhatsApp messages
PostgreSQL getUserRecord Retrieves user information from database
If ifUserNotFound Routes new vs existing users
PostgreSQL updateLastInboundAt Updates user's last activity timestamp
Set setUserPhoneNumnberAndQuery Prepares data for agent processing
Execute Workflow Call 'Francis - SalesTrackingAgent' Processes message through AI agent
If hasAgentOutput Validates agent response
Execute Workflow Call 'V4 - MessageInterceptor' Formats agent response
If isInteractive? Checks for interactive content
Set Variables Processes content variables
HTTP Request Forward reply to FastAPI Sends response back to messaging service
PostgreSQL logError Records processing errors
Set setFallbackMessage Creates fallback response for errors
PostgreSQL logChatFallback Logs fallback interactions
Execute Workflow callOrganicHandler Handles new user onboarding

External Services & Credentials Required

Database Connections

  • PostgreSQL: sifaV4Dev - Main application database for user records, chat logs, and error tracking

HTTP Authentication

  • FastAPI dispatcher: Header-based authentication for forwarding responses
  • Waringa twilio auth: Basic authentication for Twilio integration

External APIs

  • FastAPI Service: Receives processed responses via callback URL
  • Twilio WhatsApp: Messaging service integration

Environment Variables

No explicit environment variables are configured in this workflow. Configuration is handled through n8n credentials and node parameters.

Data Flow

Input

  • Phone Number: User's WhatsApp number (WaId)
  • Message Content: Text message or interactive data
  • Metadata: Profile name, callback URL, correlation ID
  • Twilio Data: From/To numbers, message type

Output

  • Formatted Response: Processed message ready for delivery
  • Content Variables: Dynamic content for interactive messages
  • Delivery Instructions: Content SID and formatting parameters
  • Correlation ID: For tracking message flow

Database Records

  • User Activity: Updated last inbound timestamp
  • Chat Logs: Complete conversation history
  • Error Logs: Processing failures and debugging information

Error Handling

The workflow includes comprehensive error handling:

  1. Agent Processing Errors: Caught and logged with fallback message in Swahili
  2. Database Connection Issues: Continues execution with error logging
  3. Missing User Records: Routes to organic handler for new user processing
  4. Invalid Agent Responses: Provides generic error message to user
  5. HTTP Request Failures: Logged but workflow continues
  6. Retry Logic: Sales tracking agent has retry-on-fail enabled

Fallback Message: "Samahani, kuna tatizo kidogo. Tafadhali jaribu tena baadaye. 🙏" (Sorry, there's a small problem. Please try again later.)

Known Limitations

Based on the workflow notes: - Daytime message logic is currently disabled (Sifa V4 is active throughout) - Weekly report handler is disabled - Call center integration is not implemented - Error notifications to Slack are not yet implemented

  • Francis - SalesTrackingAgent (nyk5AWlf0hTWye5D): AI agent for processing user messages
  • V4 - MessageInterceptor (s5k7iyzMK6cYVzAa): Formats and prepares responses
  • V4 - OrganicKeepWarmHandler (TfryOt52CrUqYwgc): Handles new user onboarding
  • Weekly Report Handler (liCqzaZwxr01Y1gx): Currently disabled

Setup Instructions

  1. Import Workflow: Import the JSON into your n8n instance
  2. Configure Database Credentials:
    • Set up PostgreSQL connection named sifaV4Dev
    • Ensure access to tables: v4_youthEntrepreneurs, v4_chatLog, errorLog
  3. Configure HTTP Credentials:
    • Set up FastAPI dispatcher header authentication
    • Configure Waringa twilio auth basic authentication
  4. Update Webhook URL: Note the webhook endpoint for external service configuration
  5. Verify Sub-workflows: Ensure all referenced workflows are imported and active
  6. Test Database Schema: Confirm all required database tables and columns exist
  7. Configure External Services: Set up FastAPI callback endpoint and Twilio integration
  8. Activate Workflow: Enable the workflow to start processing messages

Database Tables Required: - v4_youthEntrepreneurs: User records and status tracking - v4_chatLog: Conversation history - errorLog: Error tracking and debugging - v4_pendingDaytimeMessages: Message queuing (if daytime logic is re-enabled)