Skip to content

Mark - SalesTrackingAgent

A comprehensive business coaching chatbot system that helps young entrepreneurs in rural Kenya track daily profits, manage customer credit, and receive personalized micro-actions to grow their businesses. The workflow combines intent analysis with conversational AI to provide structured guidance through WhatsApp, SMS, and call center channels.

Purpose

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

This workflow serves as the main conversational engine for Sifa, a business coaching platform supporting out-of-school youth entrepreneurs aged 18-30 in Makueni County, Kenya. The system addresses the core challenge of profit visibility and credit management that leads to business failure among young entrepreneurs who extend informal credit to friends and family without proper tracking systems.

The workflow enables youth to: - Track daily sales, costs, and profits through simple SMS/WhatsApp interactions - Receive personalized coaching based on their business performance trends - Learn credit recovery strategies through guided micro-actions - Access escalation support through Community Education Advisors (CEAs) when needed

How It Works

  1. Message Reception: The workflow receives incoming messages from youth via WhatsApp, SMS, or call center channels
  2. User Context Loading: Retrieves user profile, business records, and chat history from the database
  3. Intent Analysis: An AI agent analyzes the conversation state, determines the current stage of interaction, and identifies what data needs to be collected
  4. Conversation Routing: Based on the user's onboarding status and conversation stage, routes to appropriate response flows (onboarding, daily tracking, credit management, or advice)
  5. AI Response Generation: The main AI agent generates contextually appropriate responses using message templates and business logic
  6. Data Storage: Saves business records, updates user status, and logs conversation history
  7. Response Delivery: Sends the final message back to the user through their preferred channel

The system supports multiple conversation flows including initial onboarding, daily profit tracking, 3-day trend analysis, credit module activation, and ongoing business coaching.

Mermaid Diagram

graph TD
    A[Execute Workflow Trigger] --> B[Get User Record]
    B --> C[Get Profit Data]
    C --> D[Get Chat History]
    D --> E[Limit Chat History]
    E --> F[Aggregate Chat History]
    C --> G[Aggregate Business Records]
    F --> H[Merge Data]
    G --> H
    H --> I[Aggregate All Data]
    I --> J[Intent Analysis Tool]
    J --> K[JSON Object Parser]
    K --> L[Intent Analysis Object]
    L --> M{Conversation Concluded?}
    M -->|No| N[AI Agent]
    M -->|Yes| O[No Operation]
    N --> P[Message Parser]
    P --> Q[Insert Chat Log]
    Q --> R[Set Output Field]

    N -.-> S[Daily Sales Data Collection]
    N -.-> T[Update User Data Tool]
    N -.-> U[Update User Status Tool]
    N -.-> V[Message Templates]

    J -.-> W[OpenRouter Chat Model]
    J -.-> X[Postgres Chat Memory]
    J -.-> Y[Think Tool]

    N -.-> Z[OpenRouter Chat Model 2]
    N -.-> AA[Postgres Chat Memory 2]
    N -.-> BB[Message Templates Tool]

Trigger

Execute Workflow Trigger - This workflow is triggered by another workflow and expects three input parameters: - phoneNumber: The user's phone number identifier - query: The user's message content - channel: Communication channel (WhatsApp, SMS, or call center)

Nodes Used

Node Type Purpose
Execute Workflow Trigger Receives input parameters from calling workflow
Postgres (getUserRecord) Retrieves user profile and configuration data
Postgres (getProfitData) Fetches recent business performance records
Postgres (getChatHistory) Loads conversation history for context
Aggregate Combines and structures data for AI processing
Merge Joins different data streams
Limit Restricts chat history to recent messages
AI Agent (Intent Analysis) Analyzes conversation state and determines next actions
AI Agent (Main) Generates contextual responses and manages conversation flow
Code (JSON Parser) Processes and validates AI output
Set Formats data for downstream processing
IF Routes based on conversation completion status
Postgres (Insert Chat Log) Saves conversation turns to database
Tool Workflow (Daily Sales) Records business performance data
Tool Workflow (Update User) Modifies user profile information
Tool Workflow (Update Status) Changes user onboarding status
Tool Workflow (Message Templates) Retrieves appropriate response templates
OpenRouter Chat Model Provides LLM capabilities for AI agents
Postgres Chat Memory Maintains conversation context
Think Tool Provides internal reasoning framework for AI

External Services & Credentials Required

Required Credentials

  • PostgresOnSupabase: Database connection for user data, business records, and chat history
  • OpenRouter API: LLM service for AI agents (requires two different API keys)

External Services

  • Supabase PostgreSQL: Primary database for all user and business data
  • OpenRouter: AI/LLM service provider for conversation processing
  • WhatsApp Business API: Message delivery (handled by calling workflow)
  • SMS Gateway: Text message delivery (handled by calling workflow)

Environment Variables

No explicit environment variables are defined in this workflow. Configuration is managed through: - Database connection strings (stored in credentials) - API keys (stored in credentials) - Workflow-specific settings (hardcoded in nodes)

Data Flow

Input

  • phoneNumber: User identifier (string)
  • query: User message content (string)
  • channel: Communication method (WhatsApp/SMS/call center)

Processing

  1. User context retrieval (profile, business records, chat history)
  2. Intent analysis (conversation state, data collection needs, routing decisions)
  3. Response generation (message templates, business logic, tool calls)
  4. Data persistence (chat logs, business records, user updates)

Output

  • output: Final response message to user (string)
  • Database updates (chat history, business records, user status)
  • Tool execution results (profit calculations, status changes)

Error Handling

The workflow includes several error handling mechanisms:

  1. JSON Parsing Errors: Code node includes try-catch blocks for malformed AI responses with fallback to safe defaults
  2. Database Connection Issues: Postgres nodes are configured with error handling for connection failures
  3. AI Response Validation: Structured output parsers ensure AI responses match expected schemas
  4. Conversation State Recovery: Intent analysis provides fallback states when conversation context is lost
  5. Tool Execution Failures: Workflow tools include error responses for failed operations

The system defaults to asking users to re-send messages when critical errors occur, ensuring conversation continuity.

Known Limitations

Based on the workflow structure and documentation:

  1. Language Processing: Primarily designed for Swahili/English mix (Sheng) - may not handle other languages effectively
  2. SMS Character Limits: 160-character limit for SMS responses may truncate complex messages
  3. Concurrent Sessions: Single conversation thread per user - no support for parallel interactions
  4. Offline Capability: Requires active internet connection for all AI processing
  5. Voice Messages: Cannot process voice notes - text-only interaction
  6. Complex Business Logic: Limited to profit tracking and credit management - not suitable for advanced accounting needs

Based on the tool workflow references: - dailySalesDataCollection (fBc6cSMp9Wz1brlZ): Handles business record storage - updateUserDataTool (xVkMVJOCq5ptCOHj): Manages user profile updates
- updateUserStatusTool (nfVcA8ei8x9dE06Z): Controls onboarding progression - messageTemplates (IIuvQx5MoV7CkTAJ): Provides response templates - create_business_summary_for_youth (Z9ekLMmXz9mHDKut): Generates business summaries

Setup Instructions

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

  2. Configure Database Connection:

    • Set up PostgreSQL database (Supabase recommended)
    • Create credential "PostgresOnSupabase" with connection details
    • Ensure required tables exist: youthEntrepreneursReal, dailyProfitTracking, chatLog, n8n_chat_histories
  3. Set Up AI Services:

    • Create OpenRouter account and obtain API keys
    • Configure credentials: "Prompt Testing for Design team" and "OpenRouter account"
    • Ensure access to GPT-5.2 model or adjust model settings
  4. Configure Tool Workflows:

    • Import and configure the five related workflows listed above
    • Verify workflow IDs match the references in tool nodes
    • Test each tool workflow independently
  5. Set Up Message Channels:

    • Configure WhatsApp Business API integration
    • Set up SMS gateway connection
    • Implement call center routing system
  6. Test the System:

    • Create test user records in database
    • Execute workflow with sample inputs
    • Verify conversation flows and data persistence
    • Test error scenarios and recovery mechanisms
  7. Production Deployment:

    • Set up monitoring for database connections
    • Configure logging for AI responses and errors
    • Implement backup procedures for conversation data
    • Set up alerting for system failures