Skip to content

Repository files navigation

RecoverX: Autonomous Checkout Revenue Recovery Agent Platform

RecoverX is an event-driven, autonomous revenue-recovery system designed for merchant checkout workflows. It intercepts transactional friction points (payment declines, cart abandonment, and transient gateway timeouts), reasons over optimal recovery strategies using tool-calling agent logic, executes deterministic recovery actions within strict mathematical bounds, and logs an immutable chronological audit trail in PostgreSQL via Redis Streams.


Live Deployments


Project Objectives

  1. Autonomous Revenue Recovery: Intercept payment drop-offs and transient bank/gateway declines in real-time, executing deterministic retry and payment-method switching strategies without requiring human merchant intervention for standard order amounts.
  2. Hard Mathematical Safety Guardrails: Enforce uncompromised numeric bounds (maximum automatic order value <= 5,000 INR, maximum auto-discount <= 15%, max 2 retries) ensuring the agent never incurs unauthorized merchant liabilities or enters infinite transaction loops.
  3. Human-in-the-Loop Gating: Automatically escalate high-value checkouts (> 5,000 INR) and excessive discount requests to a structured merchant approval queue with distinct ticketing identifiers (gate_<timestamp>_<id>).
  4. End-to-End Auditability and Observability: Immutably capture every domain event, LLM tool call, payload mutation, and timestamp across Redis Streams and PostgreSQL to give merchants forensic visibility over all autonomous actions.
  5. Production-Ready Resilience: Deliver a decoupled, event-driven microservices architecture featuring distributed caching, idempotency keys, and graceful fallback execution under network degradation.

What Does It Solve?

The Problem in Modern E-Commerce

Traditional checkout funnels suffer from severe drop-offs caused by brittle payment pipelines:

  • High Decline Rates: Between 20% to 35% of legitimate e-commerce transactions fail due to transient issuer timeouts, 3D-Secure authentication delays, temporary network routing glitches, or insufficient funds on a specific card.
  • Dead-End Checkout UX: Standard payment gateways return static, unhelpful error screens ("Transaction Failed. Please try again."). Facing friction, the vast majority of prospective buyers abandon their carts entirely rather than re-entering card details.
  • Ineffective Post-Hoc Retargeting: Existing recovery tools rely on asynchronous recovery emails or SMS notifications dispatched hours later, by which point buyer purchase intent has dropped significantly.
  • Unbounded Risk in AI Automation: Deploying standard generative AI agents directly into payment flows introduces risks of hallucinated discounts, unapproved price reductions, or unauthorized charges.

How RecoverX Solves It

  • Real-Time Conversational Intervention: Rather than displaying a failure screen, RecoverX maintains active checkout context, explains the exact failure reason in clean natural language, and offers immediate corrective actions.
  • Intelligent Channel Switching: If a card payment fails due to bank 3D-Secure timeouts (TRANSIENT_NETWORK_TIMEOUT), RecoverX autonomously switches the transaction route to UPI or Netbanking, executing a bounded retry to complete settlement on the spot.
  • Bounded Negotiation: For price-sensitive hesitation, RecoverX can offer bounded, merchant-approved discounts (<= 15%) directly in chat, computing dynamic cart subtotals and applying real-time price reductions.
  • Deterministic Safety Ceilings: High-risk actions automatically halt, record pending approval states, and alert the merchant, ensuring zero risk of unauthorized high-ticket executions.
  • Single-Source-of-Truth Ledger: Merchants receive a live Recovery Dashboard showing exact recovered revenue (INR) alongside a transparent audit trail detailing every automated intervention step by step.

Architectural Overview

RecoverX operates as a decoupled microservices architecture with a unified gateway entrypoint. Each domain service handles a bounded context:

                               +-----------------------------+
                               |     React 18 / Vite SPA     |
                               |  (Render Static Site Host)  |
                               +--------------+--------------+
                                              |
                                              | HTTPS / REST
                                              v
                               +-----------------------------+
                               |  RecoverX API Gateway Host  |
                               | (Express / Reverse Proxy)   |
                               +--------------+--------------+
                                              |
         +--------------------+---------------+--------------------+
         |                    |                                    |
         v                    v                                    v
+------------------+ +------------------+                +------------------+
| Catalog Service  | |  Agent Service   |                | Payment Service  |
|  (Port 4001)     | |   (Port 4002)    |                |   (Port 4003)    |
| - Stock Truth    | | - Reasoning Core |                | - Razorpay APIs  |
| - Redis Caching  | | - Bounded Tools  |                | - Idempotency    |
+--------+---------+ +--------+---------+                +--------+---------+
         |                    |                                   |
         +--------------------+-----------------------------------+
                              |
                              | Domain Events (Pub/Sub & Streams)
                              v
                     +------------------+
                     |  Audit Service   |
                     |   (Port 4004)    |
                     | - Stream Listener|
                     | - Metrics Engine |
                     +--------+---------+
                              |
         +--------------------+--------------------+
         |                                         |
         v                                         v
+-------------------------+               +-------------------------+
|  Neon Cloud PostgreSQL  |               |    Upstash Cloud Redis  |
| - Products (Inventory)  |               | - Stream Event Bus (TLS)|
| - Immutable Audit Log   |               | - LRU Catalog Cache     |
+-------------------------+               +-------------------------+

Core Capabilities

1. Conversational Commerce and Real-Time Inventory

  • Natural language query parser with fallback reasoning engine.
  • Instant stock validation and price checks against PostgreSQL with Redis read-through caching.
  • Dynamic cart state management and real-time order creation.

2. Live Payment Integration and Decline Simulation

  • Direct integration with Razorpay Orders API (POST /v1/orders) for authentic payment token generation.
  • Deterministic simulation of transient payment failures (e.g., 3D-Secure timeouts, issuer network errors) to validate recovery pipelines.
  • Distributed idempotency key management (idemp_<timestamp>_<hash>) preventing duplicate debit attempts.

3. Autonomous Decline Recovery

  • Event-driven decline ingestion: payment.failed events published to Redis Stream (recoverx:stream).
  • Strategy determination: Automatic fallback from declining card channels to UPI/Netbanking with bounded retry execution (maximum 2 attempts).
  • Real-time notification dispatched to client session state.

4. Safety Guardrails and Merchant Gating

RecoverX enforces hardcoded business rules that cannot be bypassed by LLM inference:

  • Maximum Automated Order Ceiling: <= 5,000 INR. Any order > 5,000 INR is paused with status REQUIRES_GATE and assigned a merchant approval ticket (gate_<timestamp>_<id>).
  • Maximum Automated Discount Ceiling: <= 15%. Discount requests exceeding 15% require manual authorization.
  • Maximum Retry Ceiling: 2 attempts per transaction identifier.

5. Merchant Dashboard and Audit Trail

  • Real-time KPI aggregation: Recovery Rate (%), Recovered Revenue (INR), Total Declines, and Successful Interventions.
  • Session-specific chronological audit explorer tracking events (payment.failed, agent.decision, payment.recovered, approval.required).

Service Breakdown

Service Responsibility Key Dependencies Primary Endpoints
catalog-service Product catalog CRUD, inventory checks, category search pg, ioredis, express GET /api/catalog/products
GET /api/catalog/products/:id
POST /api/catalog/stock/check
agent-service Intent classification, bounded tool execution, LLM integration express, ioredis, crypto POST /api/agent/chat
POST /api/agent/recovery/payment-decline
GET /api/agent/approvals/pending
payment-service Razorpay gateway communications, decline simulation, retry router express, ioredis, crypto POST /api/payment/orders
POST /api/payment/payments/process
POST /api/payment/payments/retry
audit-service Event bus consumer, immutable ledger persistence, KPI calculations pg, ioredis, express GET /api/audit/audit/:sessionId
GET /api/audit/metrics/recovery
POST /api/audit/events
frontend SPA Interface for shopping, checkout, merchant KPIs, and audit timeline react, vite, lucide-react Client Routes: /, /dashboard, /audit

Technology Stack

  • Runtime: Node.js (v20+ LTS)
  • Web Framework: Express 4.x
  • Frontend Framework: React 18, Vite
  • Styling & Typography: Vanilla CSS Custom Properties, Space Grotesk, IBM Plex Mono
  • Relational Database: PostgreSQL (Neon Serverless, SSL Mode require)
  • Cache & Messaging: Redis (Upstash Serverless, TLS TCP rediss://)
  • Payment Processor: Razorpay REST API
  • Containerization: Docker, Docker Compose

Local Development Setup

Prerequisites

  • Node.js >= 20.0.0
  • Docker and Docker Compose
  • Git

1. Clone Repository

git clone https://github.com/syedaftab-dev/RecoverX.git
cd RecoverX

2. Environment Configuration

Create a .env file in the project root based on .env.example:

# Database & Cache
DATABASE_URL=postgres://recoverx:recoverx@localhost:5432/recoverx
REDIS_URL=redis://localhost:6379

# Gateway & Security
PORT=8080
ALLOWED_ORIGIN=*
NODE_ENV=development

# Razorpay Test Credentials
RAZORPAY_KEY_ID=rzp_test_YourKeyId
RAZORPAY_KEY_SECRET=YourKeySecret

# Optional LLM Integration
OPENAI_API_KEY=sk-YourOpenAIKey
OPENAI_MODEL=gpt-4o-mini

3. Start Infrastructure via Docker Compose

docker compose up --build -d

4. Verify Local Health

node scripts/healthcheck.js

Local endpoints:

  • Gateway & Client: http://localhost:8080
  • Direct Catalog API: http://localhost:4001/health
  • Direct Agent API: http://localhost:4002/health
  • Direct Payment API: http://localhost:4003/health
  • Direct Audit API: http://localhost:4004/health

Automated Test Suite

The platform includes unit, integration, and end-to-end QA suites verifying boundary limits, idempotency, mathematical consistency, and failure scenarios.

Run the test suite:

npm test

Verified Test Suites

  1. tests/unit/tools.test.js: Validates tool schemas, discount bounds, order ceilings, and gate triggers.
  2. tests/integration/catalog.test.js: Verifies PostgreSQL retrieval and Redis caching behavior.
  3. tests/integration/agent.test.js: Tests conversational turns, product lookup, and safety limits.
  4. tests/integration/recovery.test.js: Executes decline-to-recovery workflows and channel transitions.
  5. tests/integration/audit.test.js: Validates stream ingestion, event ordering, and metric calculation.
  6. tests/integration/frontend_journey.test.js: Validates conversational checkout, cart mutations, and order placement.
  7. tests/integration/dashboard_routing.test.js: Tests client route accessibility and KPI rendering integrity.
  8. tests/qa_bug_hunt.js: Tests edge inputs, boundary values (0%, 100%, negative), XSS payloads, SQL injection resistance, and event deduplication.

Production Deployment Architecture

RecoverX is deployed on Render using a dual-service architecture:

1. Backend Web Service (recoverx-backend)

  • Root Directory: backend
  • Build Command: npm install --production
  • Start Command: npm start (Executes backend/server.js)
  • Attached Infrastructure: Neon PostgreSQL (SSL required) and Upstash Redis (TLS TCP)

2. Frontend Static Site (recoverx-frontend)

  • Root Directory: frontend
  • Build Command: npm install && npm run build
  • Publish Directory: dist
  • Environment Variables: VITE_API_BASE_URL=https://recoverx-t9cg.onrender.com
  • Rewrites: /* -> /index.html (HTTP 200 Rewrite for client-side routing)

License

This project is licensed under the ISC License.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages