Skip to content

V4 - EveningWrapHandler - Warenga

This workflow processes daily business data submissions from young entrepreneurs, calculating profits, tracking credit, awarding points, and providing personalized coaching feedback. It serves as the core evening routine for business performance tracking and mentorship.

Purpose

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

Based on the workflow implementation, this appears to be part of a business coaching platform that helps young entrepreneurs track their daily business performance. The workflow processes sales, expenses, and credit data to calculate profits, identify trends, and provide actionable micro-coaching suggestions. It includes gamification elements with points and levels (Kifaru, Chui, Ndovu, Simba) to encourage consistent data tracking.

How It Works

  1. Data Collection: The workflow receives a phone number, query text, and communication channel from another workflow
  2. Context Retrieval: Fetches user profile, credit status, today's existing records, and yesterday's performance from the database
  3. Input Analysis: Parses the query to extract numerical data (sales, expenses, credit given/recovered) and detects emotional distress keywords
  4. State Routing: Determines the appropriate response path:
    • If data already submitted today → confirmation message
    • If emotional distress detected → routes to emotional support
    • If insufficient data → requests proper format
    • If complete data → processes the business metrics
  5. Business Calculations: Computes profit, trend analysis, outlier detection, and generates micro-actions for improvement
  6. Database Updates: Records daily profit tracking, updates credit balances, marks data collection as complete
  7. Gamification: Awards 20 points, updates streaks, saves micro-actions, and checks for level progression
  8. Response Generation: Returns a formatted message with business insights and coaching advice

Workflow Diagram

graph TD
    A[When Executed by Another Workflow] --> B[Get All Data]
    B --> C[Parse & Route]
    C --> D[Route State]
    D --> E[Already Done]
    D --> F[Call EmotionalSupportHandler]
    D --> G[Ask For Data]
    D --> H[Process Data]
    F --> I[Format Emotional Output]
    H --> J[Write to DB]
    J --> K[Award Points Inline]
    K --> L[Update Streak Inline]
    L --> M[Save Micro Inline]
    M --> N[Format Output]

Trigger

Type: Execute Workflow Trigger
Inputs Required: - phoneNumber - User's phone number identifier - query - Text message containing business data or questions - channel - Communication channel (WhatsApp, SMS, etc.)

This workflow is designed to be called by other workflows in the system, not triggered directly by external events.

Nodes Used

Node Type Node Name Purpose
Execute Workflow Trigger When Executed by Another Workflow Receives input parameters from calling workflow
PostgreSQL Get All Data Retrieves user context, credit data, and historical records
Code Parse & Route Analyzes input text and determines processing state
Switch Route State Routes execution based on determined state
Code Already Done Generates response when data already submitted
Code Ask For Data Requests properly formatted business data
Execute Workflow Call EmotionalSupportHandler Handles emotional distress situations
Code Format Emotional Output Formats emotional support responses
Code Process Data Calculates business metrics and generates insights
PostgreSQL Write to DB Records daily profit tracking data
PostgreSQL Award Points Inline Updates user points and ledger
PostgreSQL Update Streak Inline Maintains weekly tracking streaks
PostgreSQL Save Micro Inline Records micro-action recommendations
Code Format Output Prepares final response message

External Services & Credentials Required

PostgreSQL Database: sifaV4Dev - Used for all data storage and retrieval operations - Requires read/write access to multiple tables: - v4_youthEntrepreneurs (user profiles) - v4_creditTracking (credit management) - v4_dailyProfitTracking (business performance) - v4_pointsledger (gamification points) - v4_streaks (tracking consistency) - v4_microaction_history (coaching recommendations)

Related Workflow: EmotionalSupportHandler (ID: RbLs1LNSKF4BY9fi) - Called when emotional distress is detected in user messages

Environment Variables

No explicit environment variables are used. The workflow relies on: - Database timezone set to 'Africa/Nairobi' - Credential configuration for PostgreSQL connection

Data Flow

Input:

1
2
3
4
5
{
  "phoneNumber": "string",
  "query": "string", 
  "channel": "string"
}

Output:

1
2
3
4
5
{
  "output": "string (formatted message)",
  "outputType": "plain",
  "outputOptions": []
}

Internal Data Processing: - Extracts numerical values from query text using regex - Calculates profit = sales - (expenses + daily fixed costs) - Determines trend compared to previous day - Identifies business outliers (zero sales, high expenses, excessive credit) - Generates contextual micro-actions for improvement

Error Handling

The workflow includes several error handling mechanisms:

  1. JSON Parsing: Try-catch blocks when parsing database JSON responses
  2. Missing Data: Defaults provided for missing user context fields
  3. Emotional Support: Automatic routing to specialized handler for distress situations
  4. Fallback Messages: Deterministic responses when dynamic generation fails
  5. Database Constraints: Handles existing records and prevents duplicates

Known Limitations

Based on the implementation: - Requires exactly 3 numbers for basic users, 4 numbers for credit-enabled users - Text parsing relies on regex pattern matching which may miss complex formats - Credit module activation is permanent once triggered - Timezone hardcoded to Africa/Nairobi - No validation of business logic (e.g., negative sales, impossible ratios)

  • EmotionalSupportHandler (RbLs1LNSKF4BY9fi): Handles emotional distress situations
  • CoachingAgent (mentioned in documentation): Provides LLM-based coaching responses

Setup Instructions

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

  2. Configure Database Credential:

    • Create PostgreSQL credential named sifaV4Dev
    • Configure connection to database with required tables
    • Ensure timezone is set to Africa/Nairobi
  3. Verify Related Workflows:

    • Ensure EmotionalSupportHandler workflow exists with ID RbLs1LNSKF4BY9fi
    • Update the workflow ID reference if different in your environment
  4. Database Schema Requirements:

    • Ensure all referenced tables exist with proper structure
    • Verify the get_session_context_v4() function is available
    • Set up proper indexes for performance on phone number lookups
  5. Test Integration:

    • Test with sample data: phoneNumber, query with numbers, channel
    • Verify database writes and point calculations
    • Test emotional keyword detection and routing
  6. Activate Workflow: Enable the workflow to accept calls from other workflows in your system