Skip to content

WhatsApp Trigger Workflow

This workflow serves as the main entry point for processing incoming WhatsApp messages, routing them to appropriate conversation handlers based on user context and message timing, while providing comprehensive error handling and logging capabilities.

Purpose

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

This workflow appears to be part of a youth entrepreneurship program system that handles WhatsApp communications. It processes incoming messages, manages user sessions, routes conversations to specialized handlers (including weekly reports and sales tracking), and ensures messages sent during off-hours are properly queued for later processing.

How It Works

  1. Message Reception: Receives incoming WhatsApp messages via webhook
  2. Configuration Setup: Establishes base URLs and authentication tokens for downstream services
  3. User Lookup: Queries the database to find the user record based on phone number
  4. User Validation: Checks if the user exists in the system
  5. Activity Tracking: Updates the user's last inbound message timestamp
  6. Time-Based Filtering: Determines if the message was sent during business hours (4 AM - 7 PM Nairobi time)
  7. Daytime Message Handling: Stores messages sent outside business hours for later processing
  8. Message Processing: Prepares user data and message content for agent processing
  9. Turn Timestamping: Records when the conversation turn began
  10. Conversation Routing: Routes to either Weekly Report handler or general Sales Tracking agent based on user's current stage
  11. Response Validation: Checks if the agent produced a valid response
  12. Success Path: Sends successful responses back to the user via HTTP dispatch
  13. Error Handling: Logs errors and sends fallback messages when agents fail
  14. Chat Logging: Records all conversations for audit and analysis purposes

Workflow Diagram

graph TD
    A[DevelopmentWebhook] --> B[Set Constants]
    B --> C[getUserRecord]
    C --> D[ifUserNotFound]
    D -->|User Not Found| E[setUserPhoneNumnberAndQuery]
    D -->|User Found| F[updateLastInboundAt]
    F --> G[isDaytimeMessage]
    G -->|Daytime| H[storeDaytimeMessage]
    G -->|Evening/Night| E
    H --> E
    E --> I[Set Turn Timestamp]
    I --> J[isWeeklyReport]
    J -->|Weekly Report Stage| K[Set WR Input]
    J -->|Other Stages| L[Call Francis SalesTrackingAgent]
    K --> M[Call Weekly Report Handler]
    M --> N[hasAgentOutput]
    L --> N
    L -->|Error| O[logError]
    N -->|Has Output| P[HTTP Request1]
    N -->|No Output| O
    O --> Q[setFallbackMessage]
    Q --> R[logChatFallback]
    Q --> S[HTTP Request2]

Trigger

Webhook Trigger: The workflow is triggered by incoming HTTP POST requests to the webhook endpoint 98ed6d7d-5af1-4500-878f-56b7f22cad75. This webhook receives WhatsApp message data including the sender's phone number (WaId) and message content (Body).

Nodes Used

Node Type Node Name Purpose
Webhook DevelopmentWebhook Receives incoming WhatsApp messages
Set Set Constants Configures base URLs and authentication tokens
Postgres getUserRecord Retrieves user information from database
If ifUserNotFound Checks if user exists in system
Postgres updateLastInboundAt Updates user's last message timestamp
If isDaytimeMessage Filters messages by time of day
Postgres storeDaytimeMessage Stores off-hours messages for later processing
Set setUserPhoneNumnberAndQuery Prepares user data for processing
Set Set Turn Timestamp Records conversation turn timing
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 Francis SalesTrackingAgent Handles general sales tracking conversations
If hasAgentOutput Validates agent responses
HTTP Request HTTP Request1 Sends successful responses to user
Postgres logError Records errors for debugging
Set setFallbackMessage Creates fallback response for failures
Postgres logChatFallback Logs fallback conversations
HTTP Request HTTP Request2 Sends fallback messages to user

External Services & Credentials Required

Database Connections

  • Postgres account 2 (7qvANxg1uH6hles5): Access to user records, message storage, error logging, and chat history

HTTP Authentication

  • FastAPI dispatcher (HcWCeoa3MLd3HcAJ): Authentication for sending messages back to users via the dispatch service

External Workflows

  • Weekly Report Handler (UmXTl93UZT4C9o9q): Specialized handler for weekly report conversations
  • Francis - SalesTrackingAgent (MBUCWxZ2NnrrKMzz): General sales tracking and conversation agent

Environment Variables

The workflow dynamically configures these values: - baseUrl: Extracted from incoming webhook data or defaults to https://sifa.alpha-test.kriftx.app - webHookToken: Set to DCoW5pU2PxCLTOqJtW7K0I-evhg4ZFJ4mv83TGkQG5c

Data Flow

Input

  • Phone Number: WhatsApp sender ID (WaId)
  • Message Content: User's message text (Body)
  • Sender Info: Full WhatsApp sender identifier (From)
  • Dispatch URL: Optional callback URL for responses (DispatchBackTo)

Output

  • User Responses: Processed messages sent back via HTTP dispatch
  • Database Records: User activity updates, message logs, error logs
  • Stored Messages: Daytime messages queued for evening processing

Error Handling

The workflow includes comprehensive error handling:

  1. Database Query Errors: The getUserRecord node continues on error to handle new users
  2. Agent Failures: Both conversation handlers have error outputs that route to the error logging system
  3. Fallback Responses: When agents fail, users receive a polite Swahili message: "Samahani, kuna tatizo kidogo. Tafadhali jaribu tena baadaye. 🙏"
  4. Error Logging: All errors are recorded with phone number, workflow name, error message, and raw input
  5. Graceful Degradation: The system continues to function even when individual components fail

Known Limitations

Based on the workflow structure, potential limitations include:

  • Time Zone Dependency: Business hours are hardcoded to Nairobi time (Africa/Nairobi)
  • Single Language Fallback: Error messages are only provided in Swahili
  • Webhook Token: Uses a hardcoded webhook token that may need rotation
  • Database Dependencies: Heavy reliance on PostgreSQL availability for core functionality
  • [Weekly Report] Conversation Handler - Optimized (UmXTl93UZT4C9o9q): Handles weekly report collection conversations
  • Francis - SalesTrackingAgent - optimized (MBUCWxZ2NnrrKMzz): Manages general sales tracking and user interactions

Setup Instructions

  1. Import Workflow: Import the workflow JSON into your n8n instance

  2. Configure Database Connection:

    • Set up PostgreSQL credentials named "Postgres account 2"
    • Ensure access to tables: youthEntrepreneursReal, pendingDaytimeMessages, errorLog, chatLog
  3. Configure HTTP Authentication:

    • Create HTTP Header Auth credential named "FastAPI dispatcher"
    • Configure with appropriate authentication headers for your dispatch service
  4. Set Up Webhook:

    • Note the webhook URL: [your-n8n-url]/webhook/98ed6d7d-5af1-4500-878f-56b7f22cad75
    • Configure your WhatsApp service to send messages to this endpoint
  5. Configure Related Workflows:

    • Ensure the Weekly Report Handler workflow is imported and active
    • Ensure the Francis SalesTrackingAgent workflow is imported and active
  6. Update Environment Variables:

    • Modify the Set Constants node if you need different base URLs or webhook tokens
    • Adjust time zone settings in isDaytimeMessage if not using Nairobi time
  7. Test the Setup:

    • Send a test WhatsApp message to verify the webhook receives data
    • Check database tables to confirm logging is working
    • Verify responses are sent back to users correctly
  8. Activate Workflow: Enable the workflow to start processing incoming messages