Skip to content

V4 - CreditOutcomeHandler_V2 - Warenga

A multi-turn conversational state machine that guides young entrepreneurs through credit recovery outcomes, providing personalized coaching scripts and follow-up scheduling based on debtor relationships and payment results.

Purpose

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

This workflow serves as the core credit outcome processing engine for the Sifa V4 platform. When entrepreneurs report the results of their credit collection efforts (promise, partial payment, full recovery, refusal, etc.), this workflow provides contextual coaching, generates relationship-appropriate scripts, and schedules intelligent follow-ups. It handles 7 different outcome types (C1-C7) with multi-turn conversations that capture debtor relationships, payment amounts, and commitment dates while maintaining safety guardrails for emotional distress.

How It Works

  1. Trigger Reception: Receives credit outcome data from morning check-ins or daily tracking sessions
  2. Context Loading: Retrieves entrepreneur profile, current credit tracking data, and active followup sessions
  3. Safety Check: Scans for safety-related keywords and immediately pauses with crisis support if detected
  4. Outcome Processing: Routes to appropriate conversation flow based on outcome type (C1-C7):
    • C1 (Promise): Celebrates commitment → captures relationship → records date → schedules reminder
    • C2 (Partial Payment): Celebrates progress → captures amount → handles relationship → schedules balance followup
    • C3 (Full Recovery): Celebrates success → provides appreciation script → explores next targets
    • C4 (Refusal): Provides empathy → captures relationship → delivers soft reframe script → schedules retry
    • C5 (Forgot): Validates normalcy → provides script → offers reminder scheduling
    • C6 (Fear): Acknowledges difficulty → diagnoses fear type → delivers confidence coaching
    • C7 (No Time): Respects busy schedule → provides 30-second script → offers quick reminders
  5. AI Enhancement: Calls CoachingAgent for personalized script generation when needed
  6. State Management: Updates conversation state, micro-actions, and credit tracking records
  7. Points & Followups: Awards points for successful outcomes and schedules automated followups
  8. Response Formatting: Returns structured output with conversation text and interaction options

Mermaid Diagram

graph TD
    A[When Executed by Another Workflow] --> B[Get Credit Context]
    B --> C[Process Step]
    C --> D[Write State]
    C --> E{Needs AI?}
    E -->|Yes| F[Call CoachingAgent]
    E -->|No| G{Session Done?}
    F --> H[Merge AI]
    H --> G
    G -->|Yes| I[Save Micro Inline]
    G -->|No| L[Format Output]
    I --> J[Award Points Inline]
    J --> K[Schedule Followup]
    K --> L

Trigger

Execute Workflow Trigger - Called by other workflows with these inputs: - phoneNumber: Entrepreneur's phone number - query: User's response text - channel: Communication channel (whatsapp, sms) - outcomeStep: Credit outcome type (C1-C7, optional)

Nodes Used

Node Type Node Name Purpose
Execute Workflow Trigger When Executed by Another Workflow Receives inputs from calling workflows
Postgres Get Credit Context Loads entrepreneur profile and credit tracking data
Code Process Step Main business logic for outcome processing and conversation flow
Postgres Write State Updates conversation state and credit tracking records
If Needs AI? Determines if AI coaching is required
Execute Workflow Call CoachingAgent Calls AI workflow for personalized script generation
Code Merge AI Combines AI output with standard responses
If Session Done? Checks if conversation is complete
Postgres Save Micro Inline Updates micro-action history
Postgres Award Points Inline Awards points for successful outcomes
Postgres Schedule Followup Creates automated followup reminders
Code Format Output Structures final response for caller

External Services & Credentials Required

  • PostgreSQL Database: sifaV4Dev credential for all database operations
  • CoachingAgent Workflow: Internal n8n workflow (ID: Bz0GPL2vYbDw8ygf) for AI-generated coaching scripts

Environment Variables

No explicit environment variables are used. All configuration is handled through database connections and workflow references.

Data Flow

Input:

1
2
3
4
5
6
{
  "phoneNumber": "string",
  "query": "string", 
  "channel": "string",
  "outcomeStep": "string (C1-C7, optional)"
}

Output:

1
2
3
4
5
{
  "output": "string (conversation response)",
  "outputType": "string (plain|interactive)",
  "outputOptions": "array (for interactive responses)"
}

Internal Data: - Entrepreneur profile (firstName, businessOwned, sifa_level) - Credit tracking (totalCreditLocked, debtorName, debtorAmount) - Followup state (currentCreditFollowupStep, debtorRelationship, debtorBalance) - Outcome metadata (points awarded, micro-actions, followup schedules)

Error Handling

  • Safety Override: Detects crisis keywords and immediately pauses with mental health resources
  • Missing Context: Gracefully handles missing credit sessions with informative messages
  • AI Fallback: Uses hardcoded scripts if AI coaching fails
  • Database Resilience: Uses conditional SQL execution to prevent errors on missing data

Known Limitations

Based on the workflow structure: - Relies on accurate keyword detection for safety concerns - Swahili date parsing may not handle all regional variations - Interactive options are limited to predefined lists - No explicit validation of payment amounts or dates

  • MorningCheckInHandler: Calls this workflow with outcome steps
  • DailyTrackingRouter: Routes credit sessions to this workflow
  • CoachingAgent (Bz0GPL2vYbDw8ygf): Provides AI-generated coaching scripts

Setup Instructions

  1. Import Workflow: Import the JSON into your n8n instance
  2. Configure Database: Set up PostgreSQL credential named sifaV4Dev with access to:
    • v4_youthEntrepreneurs table
    • v4_creditTracking table
    • v4_creditpathFollowup table
    • v4_microaction_history table
    • v4_pointsledger table
    • v4_ceaalerts table
    • v4_emotionalevents table
  3. Link CoachingAgent: Ensure CoachingAgent workflow (ID: Bz0GPL2vYbDw8ygf) is available
  4. Test Integration: Verify calling workflows can execute this workflow with proper inputs
  5. Activate: Enable the workflow for production use

The workflow is designed to be called by other workflows rather than triggered directly by external events.