Skip to content
Afnan-0206Public

About

AI-powered revenue recovery agent that intelligently diagnoses failed payments, optimizes recovery actions, and enforces compliant retry, escalation, and audit workflows.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

Repository files navigation

Recoup

AI-powered payment recovery that brings failed revenue back.

Node.js Version React Vite Framer Motion Anthropic Claude SQLite Track

Recoup uses an autonomous AI agent to diagnose why payments fail, determine the optimal retry window, generate personalized customer recovery messages, and maximize reclaimed revenue.


1. The Problem

When online payments fail, standard payment gateways and billing systems typically make one of two mistakes:

  1. Blind fixed-interval retries: Retrying all failures at a static interval (e.g. 24 hours later) regardless of whether the failure was due to an expired card, network drop, or insufficient balance.
  2. Silent surrender: Discarding the failed transaction entirely and expecting the customer to manually re-attempt.

This leads to:

  • Issuer penalties & fraud flags: Retrying invalid/expired cards multiple times damages merchant reputation with card networks (Visa/Mastercard).
  • Missed recovery windows: Technical gateway drops and network timeouts should be retried in minutes, not days.
  • Unnecessary customer churn: Customers facing temporary balance holds abandon purchases without timely, empathetic outreach.

2. The Solution

Recoup replaces static retry loops with an Autonomous AI Revenue Recovery Engine:

Payment Fails at Gateway
         │
         ▼
 ┌──────────────┐
 │ Understand   │  AI Agent classifies root cause (Temporary, Network, or Hard Decline)
 └───────┬──────┘
         ▼
 ┌──────────────┐
 │ Strategy     │  Selects adaptive strategy & optimal processing window (2m, 24h, Payday)
 └───────┬──────┘
         ▼
 ┌──────────────┐
 │ Outreach     │  Auto-generates contextual, empathetic Email / SMS recovery communications
 └───────┬──────┘
         ▼
 ┌──────────────┐
 │ Retry        │  Simulates adaptive payment retry at the high-probability window
 └───────┬──────┘
         ▼
 ┌──────────────┐
 │ Reclaim      │  Settles revenue into treasury & live analytics update automatically
 └──────────────┘

3. Why Recoup is Different

Dimension Traditional Fixed Retry Recoup AI Recovery Agent
Diagnosis None — treats all errors as identical Semantic triage into Soft Decline, Technical Error, or Hard Decline
Retry Timing Fixed 24h interval Dynamic windows: Immediate (2 min), 24h reset, or Salary Day (72h)
Customer Touch Generic automated receipt or none Context-aware, tone-calibrated Email and SMS outreach
Card Network Safety Retries invalid cards, risking issuer blocks Automatically suppresses retries for expired or deactivated cards
Recovery Rate ~20% – 25% baseline ~58% – 70% adaptive recovery efficiency

4. Key Features

  • Autonomous Failure Classification: Evaluates raw gateway error strings, previous retry history, and transaction context using Anthropic Claude with strict structured tool schemas (tool_choice).
  • Adaptive Retry Scheduling: Calculates tailored execution clocks (immediate_retry, 24h_retry, salary_day_retry, do_not_retry).
  • Human-First Language: Transforms confusing gateway error codes into clear, intuitive explanations for merchants and finance teams.
  • Contextual Customer Outreach Engine: Generates polite, high-converting Email and SMS recovery messages with 1-click clipboard actions.
  • Kinetic Revenue Control Center: Real-time animated counters, interactive money-flow pipelines, and visual AI vs Baseline lift telemetry.
  • Live Failure Simulation: Ingest real simulated failure webhooks on demand to test and benchmark the system in real time.
  • 100% Offline Rule Fallback: Seamless deterministic heuristics fallback if the external AI API is unreachable or rate-limited.

5. System Architecture

                                  ┌─────────────────────────────┐
                                  │      React 18 + Vite UI     │
                                  │ (Framer Motion, Syne, Mono) │
                                  └──────────────┬──────────────┘
                                                 │ HTTP / JSON
                                                 ▼
                                  ┌─────────────────────────────┐
                                  │     Node.js + Express API   │
                                  │      (Port 3001 Server)     │
                                  └──────────────┬──────────────┘
                                                 │
                   ┌─────────────────────────────┼─────────────────────────────┐
                   │                             │                             │
                   ▼                             ▼                             ▼
       ┌──────────────────────┐      ┌──────────────────────┐      ┌──────────────────────┐
       │ Transactions Manager │      │  Claude AI Agent     │      │ Analytics Engine     │
       │ (CRUD, Simulators)   │      │  (Classify & Message)│      │ (Aggregation & Lift) │
       └──────────┬───────────┘      └──────────┬───────────┘      └──────────┬───────────┘
                  │                             │                             │
                  ▼                             ▼                             ▼
       ┌──────────────────────────────────────────────────────────────────────────────────┐
       │                       Embedded SQLite Database (Node 22+)                        │
       │         Tables: `transactions`, `retry_attempts`, `recovery_messages`            │
       └──────────────────────────────────────────────────────────────────────────────────┘

6. AI Agent Details

Classification Schema

When a transaction fails, the agent receives:

  • failure_reason_raw (e.g. insufficient_funds, bank_timeout, card_declined)
  • amount & currency
  • retry_count & previous attempt history
  • customer_name & product_description

Structured Tool Output

The model outputs a typed JSON object containing:

  • failure_category: soft_decline | hard_decline | technical_error
  • recommended_retry_strategy: immediate_retry | 24h_retry | salary_day_retry | do_not_retry
  • recommended_retry_window_hours: Float / Integer (e.g. 0.03, 24, 72, null)
  • confidence: Float between 0.0 and 1.0
  • reasoning: Plain-language explanation of why this action was selected.

7. Recovery Strategy Matrix

Why It Failed Problem Type AI Recommended Strategy Best Time to Retry Rationale
bank_timeout Technical Error immediate_retry Within 2 minutes Temporary gateway glitch; customer is still at checkout
network_error Technical Error immediate_retry Within 2 minutes Packet drop during handshake; re-attempt immediately
insufficient_funds Temporary Issue salary_day_retry 48–72h (End of Month) Align with monthly salary credit window
card_declined Temporary Issue 24h_retry 24 hours Allow daily velocity limit or bank security hold to reset
card_expired Card Issue do_not_retry Do not retry Card permanently expired; request alternative payment method
invalid_card Card Issue do_not_retry Do not retry Invalid card details; avoid merchant issuer penalties

8. AI vs Baseline Benchmark

Recoup AI Adaptive Strategy :  62.4% Recovery Rate
Fixed-Interval 24h Baseline :  24.0% Recovery Rate
────────────────────────────────────────────────────
Measurable Revenue Lift     : +38.4% Percentage Points

Note on Methodology: Benchmark comparisons are generated using Recoup's deterministic probability model (backend/utils/retrySimulator.js), simulating empirical recovery rates across 10,000+ synthetic payment error states.


9. Compliance & Governance Layer (Track 3 Bar)

"Don't just identify the problem. Show measured money recovered across a batch, with compliant escalation, stopping rules, and an audit trail." — Razorpay Buildathon Track 3 Bar

Recoup separates the AI recommendation layer from a deterministic Governance enforcement layer. The AI suggests interventions, but the governance engine enforces compliance boundaries, limits, and stopping conditions.

9.1 Track 3 Compliance Mapping

Razorpay Track 3 Requirement Recoup Implementation Codebase Artifact
Detect revenue at risk Failed payment ingestion & gateway telemetry routes/transactions.js
Diagnose revenue loss Autonomous failure category & root cause diagnosis agents/recoveryAgent.js
Choose intervention Adaptive strategy & optimal retry window calculation agents/recoveryAgent.js
Execute workflow Dynamic retry execution & personalized customer outreach utils/retrySimulator.js
Measured batch recovery Measured recovery & +38.4% lift benchmark over static 24h cron routes/analytics.js, Analytics.jsx
Compliant escalation Attempt-based escalation with enforced 24h contact cooldown config/escalationPolicy.js, EscalationPolicyCard.jsx
Stopping rules Deterministic governance engine halting non-viable pursuits utils/stoppingRules.js
Audit trail Immutable, timestamped decision log with 1-click JSON export audit_log table, utils/auditLogger.js, AuditTrail.jsx
Bounded AI & Terminal States Stopped/recovered transactions are terminal and reject future actions permanently_failed terminal state guards in routes/transactions.js
Webhook Idempotency Duplicate payment event protection processed_events table & routes/transactions.js

9.2 Stopping Rules Engine (backend/utils/stoppingRules.js)

A pure deterministic function evaluating recovery viability in a strict, documented sequence:

const MAX_RETRY_ATTEMPTS = 3;             // Cap recovery retries at 3 attempts
const MAX_CONTACT_ATTEMPTS = 3;           // Cap communications at 3 contacts
const HARD_DECLINE_STOP = true;           // Halt immediately on card_expired / invalid_card
const MAX_PURSUIT_DAYS = 14;              // Archive pursuit after 14 days
const REPEATED_FAILURE_STOP_THRESHOLD = 2;// Halt on 2 repeated failures on identical error code
  • Terminal State: When triggered, status = 'permanently_failed' and next_retry_at = null. All subsequent retry or outreach actions are blocked with HTTP 400.

9.3 Compliant Escalation Policy (backend/config/escalationPolicy.js)

const ESCALATION_POLICY = {
  steps: [
    { attempt: 1, tone: 'friendly', channel: 'email', minHoursSinceLastContact: 0  },
    { attempt: 2, tone: 'friendly', channel: 'email', minHoursSinceLastContact: 24 },
    { attempt: 3, tone: 'neutral',  channel: 'sms',   minHoursSinceLastContact: 24 },
  ],
  maxAttempts: 3,
  cooldownHoursBetweenContacts: 24, // Never contact customer more than once every 24 hours
  suppressOnHardDecline: true,       // Suppress "retry" language for expired/invalid cards
  requireCustomerActionLinkOnFinalAttempt: true,
};
  • Live Cooldown Guard: If outreach is attempted within 24 hours of previous contact, the request is blocked (HTTP 403, { blocked: true }), leaving the transaction recoverable while recording a message_blocked audit event.

9.4 Authoritative Audit Trail (audit_log table & backend/utils/auditLogger.js)

Every state transition records an immutable, structured audit entry:

  • Event Types: classified | message_generated | message_blocked | retry_attempted | stopped | recovered

  • Actors: ai_agent | stopping_rules_engine | escalation_policy | system

  • UI: Rendered in AuditTrail.jsx with monospace timestamps, color-coded badges, collapsible JSON metadata, and 1-click Export Audit Log (JSON).

  • Frontend: React 18, Vite, Framer Motion, Recharts, Lucide React, Canvas Confetti

  • Typography: Syne (Display / Hero), Plus Jakarta Sans (UI Chrome), IBM Plex Mono (Tabular Numbers)

  • Backend: Node.js, Express.js

  • Database: SQLite (node:sqlite / DatabaseSync on Node 22+)

  • AI Model: Anthropic Claude (claude-3-5-sonnet-20241022 with structured tool calling)


10. Project Structure

recoup/
├── backend/
│   ├── agents/
│   │   └── recoveryAgent.js       # Claude AI classification & outreach engine
│   ├── db/
│   │   ├── schema.js              # SQLite database schema & migrations
│   │   └── seed.js                # Seed script with realistic demo transactions
│   ├── routes/
│   │   ├── transactions.js        # Transaction CRUD, triage & simulation routes
│   │   └── analytics.js           # Analytics aggregation & AI vs baseline metrics
│   ├── utils/
│   │   └── retrySimulator.js      # Weighted probability recovery simulator
│   ├── package.json
│   └── server.js                  # Express application entry point
├── frontend/
│   ├── src/
│   │   ├── api/
│   │   │   └── client.js          # Centralized API client
│   │   ├── components/
│   │   │   ├── AnimatedNumber.jsx # Kinetic ease-out counter
│   │   │   ├── DemoGuideModal.jsx # 5-minute judge walkthrough modal
│   │   │   ├── JourneyTimeline.jsx# Multi-stage recovery life-cycle timeline
│   │   │   ├── MessagePreview.jsx # High-fidelity Email & SMS preview
│   │   │   ├── RecoveryChart.jsx  # Recharts visualizations
│   │   │   ├── RecoveryFlow.jsx   # Kinetic money flow pipeline
│   │   │   ├── RecoveryHero.jsx   # Hero command center
│   │   │   ├── SimulateFailuresModal.jsx # Interactive failure ingestion modal
│   │   │   ├── StatusBadge.jsx    # Status beacons & strategy chips
│   │   │   └── StrategyMatrix.jsx # AI lift telemetry component
│   │   ├── pages/
│   │   │   ├── Dashboard.jsx      # Overview dashboard
│   │   │   ├── Transactions.jsx   # Payments master ledger (search/filter/sort)
│   │   │   ├── TransactionDetail.jsx # Transaction journey & retry climax
│   │   │   └── Analytics.jsx      # Dedicated analytics & lift benchmark
│   │   ├── utils/
│   │   │   └── formatters.js      # Human-friendly terminology dictionary
│   │   ├── App.jsx                # Responsive shell & navigation
│   │   ├── index.css              # 2026 design system & mobile responsive CSS
│   │   └── main.jsx
│   ├── index.html
│   ├── package.json
│   └── vite.config.js
├── package.json                   # Root orchestrator package.json
└── README.md

11. Getting Started

Prerequisites

  • Node.js: v18.0.0 or higher (Node v20/v22 recommended)
  • Anthropic API Key (optional for AI live calls; built-in heuristic fallback operates without it): Get a key here

1. Clone the Repository

git clone https://github.com/your-repo/recoup.git
cd recoup

2. Install Dependencies

# Root and workspace dependencies
npm install
npm install --prefix backend
npm install --prefix frontend

3. Configure Environment

Create a .env file in the backend/ directory:

# backend/.env
PORT=3001
ANTHROPIC_API_KEY=your_anthropic_api_key_here

(If no API key is provided, Recoup automatically engages its built-in rule-based adaptive engine).

4. Seed the Database

npm run seed

Initializes backend/recoup.db with 20 realistic payment transactions across various failure states.

5. Run the Application

npm run dev
  • Backend starts at http://localhost:3001
  • Frontend starts at http://localhost:5173

Open http://localhost:5173 in your browser.


12. 5-Minute Demo Flow for Judges

  1. Step 1 — Overview (/): View the headline hero showing total revenue recovered, recovery rate, and the live interactive Money at Risk ➔ Recovered pipeline.
  2. Step 2 — Ingest Failures: Click "Simulate Failures" in the top right. Select 5 payments and click Create Failed Payments.
  3. Step 3 — Open Payments (/transactions): Search for a customer (e.g. Arjun) or filter by "Waiting for Retry". Click on any failed payment.
  4. Step 4 — AI Diagnosis: On the payment detail page, click "Analyze payment". Watch the AI diagnose the root cause, output its reasoning trace, and calculate the win probability.
  5. Step 5 — Customer Outreach: Click "Create customer message" to preview a personalized recovery Email and SMS notice.
  6. Step 6 — Retry & Recover: Click "Retry payment". Observe the recovery animation, celebratory burst, status transition, and upward tick of reclaimed revenue.
  7. Step 7 — Dedicated Analytics (/analytics): Open the Analytics tab to view the +38.4% AI lift benchmark and failure recovery breakdowns.

13. API Documentation

POST /api/transactions/simulate-failure

Injects simulated failure records into the database.

// Request
{ "count": 5 }

// Response
{
  "created": 5,
  "transactions": [
    { "id": "uuid-...", "customer_name": "Arjun Sharma", "amount": 4999, "failureReason": "insufficient_funds" }
  ]
}

GET /api/transactions

Retrieves transactions with optional filtering and sorting.

  • Query Parameters: status, failure_category, search, sort (newest, oldest, amount_desc, amount_asc, status), limit, page.

GET /api/transactions/:id

Returns a single transaction with complete retry history and drafted recovery messages.

POST /api/transactions/:id/classify

Invokes the Claude AI agent to classify the payment failure and calculate optimal retry timing.

POST /api/transactions/:id/generate-message

Generates a context-aware Email / SMS recovery communication draft.

POST /api/transactions/:id/simulate-retry

Simulates payment retry based on the recommended strategy and records the outcome in retry_attempts.

GET /api/analytics/summary

Returns aggregate statistics, AI vs baseline comparison, category breakdowns, and strategy win rates.


14. Limitations & Future Roadmap

Current Limitations

  • Payment attempts and retry outcomes are currently simulated via a weighted empirical model.
  • Email and SMS messages are generated and previewed within the UI; live SMTP / SMS gateway delivery is mocked.

Future Roadmap

  • Live Razorpay Webhook Ingestion: Automatically trigger AI classification upon receiving payment.failed webhooks from Razorpay.
  • Automated Retry Daemon: Background cron runner executing retries at next_retry_at using Razorpay's recurring payment API.
  • Multi-Channel Dispatch: Production integrations with SendGrid (Email), Twilio (SMS), and WhatsApp Business API.
  • Card Update Self-Serve Portal: Tokenized customer portal allowing buyers with expired cards to securely update payment methods in one tap.

15. Security & Privacy

  • All API credentials (ANTHROPIC_API_KEY) are kept exclusively on the server side in environment variables and never exposed to the client.
  • No real credit card numbers, CVVs, or sensitive PII are stored or transmitted.
  • Parameterized SQL queries are used across all database operations to eliminate SQL injection risks.

16. License

This project is licensed under the MIT License — see the LICENSE file for details. Built for the Razorpay AI Buildathon 2025.

recoup

About

AI-powered revenue recovery agent that intelligently diagnoses failed payments, optimizes recovery actions, and enforces compliant retry, escalation, and audit workflows.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages