AI-powered payment recovery infrastructure that turns failed transactions into intelligent, explainable, and safely executable recovery opportunities.
RecoverAI is an enterprise-grade AI revenue recovery operating system designed for modern online merchants. When digital payments fail, merchants face a critical dilemma: ignoring failed payments forfeits massive revenue, but blindly retrying transactions annoys customers, drives up gateway fees, triggers bank rate-limits, and risks operational chaos.
RecoverAI replaces blind retries with predictive intelligence, mathematical prioritization, multi-tier safety guardrails, and deterministic sandbox recovery workflows.
FAILED PAYMENT
│
▼
ML SCORING (9 Pre-Recovery Features)
│
▼
EXPECTED RECOVERY VALUE (Amount × Probability)
│
▼
POLICY EVALUATION (Merchant Controls)
│
▼
9-FACTOR SAFETY CHECK (Platform Guardrails)
│
▼
CAMPAIGN / EXPERIMENT ORCHESTRATION (Deterministic Allocation)
│
▼
SANDBOX EXECUTION (Razorpay Test Mode / HMAC-SHA256)
│
▼
IMMUTABLE AUDIT TRAIL (Cryptographic Event Log)
│
▼
EXECUTIVE ANALYTICS (Boardroom ROI & Attribution)
- 1. Canonical PostgreSQL Dataset: 10,000 realistic payments across 1,988 customers with ₹25.19 Cr revenue at risk and ₹7.78 Cr ground truth recoverable capital.
- 2. Leak-Free ML Recovery Predictor: Calibrated Scikit-Learn pipeline (9 pre-recovery features, zero future leakage, ROC-AUC 0.7617, dynamic thresholding).
- 3. Recovery Operations Center: High-density payment ledger and 3-column operational decision workspace.
-
4. Razorpay Test Mode Execution: Idempotency-locked recovery order dispatch with strict
rzp_test_safety and demo fallback. -
5. Recovery Intelligence: Root-cause diagnostic attribution (
BANK_TIMEOUT), customer segmentation, and automated next-best actions. - 6. Smart Recovery Campaigns: Automated cohort-based batch recovery engine with server-side previews, approvals, and live execution.
- 7. Executive Analytics & ROI: Boardroom financial metrics, expected vs. actual variance analysis, and channel attribution.
-
8. Merchant Recovery Policy Controls: Configurable merchant thresholds (
$\ge 0.50$ ), amount caps ($\le ₹2,00,000$ ), failure filters, and policy simulator. - 9. Recovery Experimentation & A/B Testing: Cryptographic SHA-256 deterministic arm allocation for testing competing recovery policies.
-
10. Merchant Command Center & Product Polish: Responsive design (320px to 1920px+), Command Palette (
Ctrl+K), and live Activity feed drawer. - 11. Final Hardening & Master Certification: Comprehensive security audit, regression verification across all 11 suites, and production build readiness. =======
| Category | Invariant / Verified Metric | Verification Detail |
|---|---|---|
| Canonical Transactions | 10,000 |
Full realistic population dataset |
| Unique Customer Accounts | 1,988 |
Multi-tier customer cohort history |
| Total Revenue at Risk | ₹25,18,75,831 |
Cumulative transaction failure volume |
| Canonical Recoverable Revenue | ₹7,78,21,773 |
Ground truth recoverable capital pool |
| Ground Truth Positive Labels | 3,315 |
Successful historical recoveries (33.15% prevalence) |
| Held-Out Test Set Volume | 2,000 |
Isolated ML evaluation dataset |
| ML Model Architecture | Logistic Regression | Calibrated pipeline with 9 pre-recovery features |
| ML Model ROC-AUC | 0.7617 |
Discrimination capability on held-out test data |
| Platform Safety Floor | Threshold ≥ 0.50 |
Hard invariant preventing sub-50% retries |
| Platform Max Attempt Ceiling | 1 Attempt |
Eliminates infinite retry loops and customer fatigue |
| Platform Single Recovery Cap | ₹2,00,000 |
Bounded capital exposure per transaction |
| Terminal Deficit Safety | INSUFFICIENT_FUNDS Blocked |
Permanently blocked from automated retries |
| Automated Verification Checks | 412 / 412 PASSED |
100% pass rate across all test suites |
| Domain Certification Suites | 11 / 11 CERTIFIED |
Full platform domain verification |
| Production Build Routes | 45 Routes (0 Errors) |
Next.js 16.3.2 App Router with Turbopack |
| Live Money Settlement | Strictly Disabled |
Razorpay Test Mode (rzp_test_) + Offline Simulation |
RecoverAI directly addresses the core operational, financial, and safety challenges of e-commerce payment failures:
- Predict High-Probability Recoveries: Identify transient failures (such as temporary bank downtime or network timeouts) that have genuine recovery viability using leak-free machine learning.
-
Maximize Capital Efficiency via Expected Value: Prioritize recovery operations using Expected Recovery Value (
$\text{Amount} \times P$ ), ensuring high-value, high-probability payments receive immediate focus. -
Eliminate Pointless & Destructive Retries: Block non-recoverable terminal failures (e.g.,
INSUFFICIENT_FUNDS) to protect customer goodwill and reduce gateway noise. - Empower Merchants with Transparent Controls: Enable merchants to customize recovery thresholds, amount limits, and channel rules while enforcing non-negotiable platform safety floors.
- Automate Recovery Campaigns Safely: Provide a two-phase approval mechanism for batch cohort recovery with server-side previews, pause/resume controls, and idempotent execution.
- Enable Cryptographic Policy A/B Testing: Compare competing recovery strategies using deterministic SHA-256 arm allocation without random allocation bias.
-
Deliver Boardroom Executive Telemetry: Distinguish clearly between total revenue at risk, machine learning projections, and verified sandbox recoveries with zero
NaNmetrics. - Guarantee Complete Forensic Auditability: Record an immutable, sanitized lifecycle event ledger for every recovery decision.
- Provide Safe Razorpay Sandbox Integration: Support real-time order generation and cryptographic HMAC-SHA256 signature verification in test mode with zero live-money exposure.
RecoverAI is not a simple dashboard or a basic webhook viewer. It is an active recovery operating system with a dedicated safety architecture and machine-learning decision engine.
| Dimension | Traditional Retry Logic | RecoverAI Operating System |
|---|---|---|
| Decision Engine | Blind retry of all failed payments | Leak-free ML classifier scoring recovery probability |
| Financial Prioritization | Chronological FIFO or probability only | Expected Recovery Value ( |
| Decision Authority | Client-driven or easily bypassed scripts | Strict server-side revalidation before any execution |
| Safety Invariants | Hardcoded or unbounded retry loops | Platform Safety Floor ( |
| Terminal Failure Handling | Retries insufficient funds blindly | INSUFFICIENT_FUNDS permanently blocked by safety engine |
| Campaign Execution | Uncontrolled mass scripts | Two-phase commit: Server Preview |
| A/B Experimentation | Biased Math.random() allocation |
Deterministic SHA-256 cryptographic arm allocation |
| Auditability | Ephemeral application logs | Sanitized, immutable AuditEvent ledger for all lifecycle steps |
| Payment Gateway Integration | Unbounded or risky live credentials | Strict rzp_test_ sandbox enforcement with rzp_live_ rejection |
| Executive Reporting | Basic aggregated counts | Multi-dimensional ROI analytics, variance tracking, and root-cause insights |
RecoverAI processes every failed payment through an 8-step deterministic recovery workflow:
[1. Failure Detected] ──► [2. Context Retrieved] ──► [3. ML Inference (P)] ──► [4. Expected Value]
│
[8. Audit & Analytics] ◄── [7. Sandbox Execution] ◄── [6. 9-Factor Safety] ◄── [5. Policy Check]
-
Failure Detected: A transaction failure event is ingested with error telemetry (
BANK_TIMEOUT,NETWORK_ERROR, etc.). - Context Retrieved: Historical context is retrieved from PostgreSQL (customer lifetime spend, historical attempt counts, prior success rate, payment method).
-
ML Model Calculates Recovery Probability: The leak-free Logistic Regression predictor evaluates 9 pre-recovery features and outputs a calibrated recovery probability
$P \in [0.0, 1.0]$ . -
Expected Recovery Value Computed: The system calculates
$\text{Amount} \times P$ to rank and prioritize the opportunity financially. - Merchant Policy Evaluated: The active workspace policy validates whether the transaction meets the merchant's configured threshold, amount cap, and payment method criteria.
-
9-Factor Safety Guardrails Evaluated: Server-side safety checks confirm payment status, ensure attempts
$\le 1$ , verify amount$\le ₹2,00,000$ , and block terminalINSUFFICIENT_FUNDSfailures. -
Sandbox Recovery Executed: If all checks pass, the
RecoveryAgentdispatches an idempotent order request viaRazorpayTestProvideror offlineDemoSimulationProvider. - Database, Audit Ledger & Analytics Updated: In a single atomic transaction, the payment status updates, an immutable audit event is recorded, and executive analytics reflect the recovery.
RecoverAI is built around a non-negotiable principle: lower configuration layers cannot weaken higher-level safety constraints.
PLATFORM SAFETY FLOOR
(Threshold >= 0.50 | Amount <= ₹2,00,000 | Attempts <= 1)
│
▼
MERCHANT ACTIVE POLICY
(Threshold in [0.50, 0.90] | Custom Amount Cap <= ₹2,00,000)
│
▼
EXPERIMENT VARIANT
(Must be >= Active Policy Threshold to prevent weakening)
│
▼
CAMPAIGN TARGETING
(Must satisfy Active Policy and Platform Safety Floors)
│
▼
RECOVERY EXECUTION
-
Minimum Threshold Floor (
$\ge 0.50$ ): No merchant, campaign, or experiment can trigger recovery on transactions with$< 50%$ ML recovery probability. -
Maximum Attempt Hard Ceiling (
$1$ ): Every transaction is strictly bounded to a single recovery attempt to protect customer experience. -
Single Transaction Recovery Cap (
$\le ₹2,00,000$ ): Single recoveries exceeding ₹2,00,000 are blocked by platform safety invariants. -
Terminal Failure Mode Block: Transactions failing due to
INSUFFICIENT_FUNDSare permanently blocked from automated retries. -
Strict Sandbox Enforcement: All payment credentials must begin with
rzp_test_. Anyrzp_live_*keys are strictly rejected at provider instantiation. - Strict Server Authority: Client inputs cannot override probabilities or bypass safety rules; all policies are revalidated server-side before execution.
-
Cryptographic Idempotency: Every recovery action requires an SHA-256 composite key (
workspaceId:paymentId:attempt). Duplicate requests safely return existing records without re-dispatching to the gateway. - Sanitized Audit Trail: All audit records scrub passwords, API keys, database URLs, and customer tokens.
RecoverAI uses a calibrated Scikit-Learn Logistic Regression pipeline trained with strict prevention of data leakage.
amount— Transaction amount in INRpaymentMethod— Payment method (UPI, CARD, NETBANKING, WALLET)failureReason— Initial gateway error codecurrency— Transaction currency (INR)attemptNumber— Sequential attempt countmerchantCategory— Merchant category classificationcustomerLifetimeSpend— Cumulative historical spend prior to failurecustomerSuccessRate— Historical transaction success rate prior to failurecustomerTotalAttempts— Total prior transactions attempted by customer
Illustrative Example:
- Held-Out Test Population: 2,000 isolated records
- ROC-AUC:
0.7617(Area Under the Receiver Operating Characteristic Curve) - Recommended Threshold:
0.50(Selected via internal cross-validation for optimal F1 and capital capture) - High-Speed Inference: Sub-millisecond fallback scoring (
scorePaymentFast) ensures zero UI latency.
The Recovery Intelligence engine automatically transforms raw transaction logs into structured root-cause diagnostics, customer segmentation, and explainable next-best actions:
- Root-Cause Attribution: Categorizes failures into actionable transient errors (
BANK_TIMEOUT,NETWORK_ERROR) vs. terminal errors (INSUFFICIENT_FUNDS). - Highest Opportunity Identification: Automatically flags
BANK_TIMEOUTas the highest recoverable failure category (accounting for ₹2.32 Cr of expected recovery capital). - Customer Segmentation: Analyzes recovery performance across 5 merchant segments: High-Value Enterprise, Loyal Repeat Buyers, Mid-Market Accounts, Standard Retail, and New Accounts.
- Explainable Next-Best Actions: Generates dynamic recommendation cards with explainable rationale and one-click navigation into pre-filtered operational queues.
Smart Recovery Campaigns provide automated, cohort-based batch recovery workflows with strict safety controls:
[Targeting Query Builder] ──► [Server-Side Preview] ──► [Merchant Review & Approval] ──► [Bounded Execution]
- Targeting Matrix: Multi-factor filtering across transaction amount ranges, ML probability floors, failure reasons, and payment methods.
- Two-Phase Approval Gate: Campaigns cannot execute until a merchant reviews the server-side target preview and explicitly approves the run.
- Execution Orchestration: Real-time batch processing with interactive Pause, Resume, and Cancel & Skip Remaining controls.
- Target Immutability: Composite database unique constraint on
(campaignId, paymentId)prevents duplicate target assignments.
RecoverAI enables merchants to scientifically validate competing recovery policies through controlled A/B experimentation:
-
Deterministic SHA-256 Allocation: Transactions are assigned to arms using:
$$\text{SHA-256}(\text{experimentId} + \text{":"} + \text{paymentId})$$ This guarantees 100% deterministic, stateless, uniform 50/50 allocation without usingMath.random(). - Policy Invariant Guard: Experiment variants cannot weaken the active merchant policy (e.g. if active policy is 0.65, a variant of 0.50 is rejected).
- Side-by-Side Telemetry: Real-time comparison of Control vs. Variant conversion rate, capital recovered, and win-rate attribution.
The Executive Analytics suite provides boardroom-ready financial reporting while maintaining strict mathematical distinctions:
- Executive KPI Cards: Real-time aggregation of total volume, revenue at risk (₹25.19 Cr), inherent recoverable opportunity (₹7.78 Cr), sandbox recovered capital, and success rates.
- Expected vs. Actual Variance: Evaluates sandbox recovery realization against ML expected basis with non-NaN formulas.
- Attribution Breakdowns: Slices recovery metrics by Failure Reason, Customer Segment, and Payment Method.
- Period Filtering: Instant multi-period analysis across
TODAY,7D,30D,90D,ALL, andCUSTOMdate ranges.
The Merchant Policy Center provides fine-grained control over automated recovery behaviors:
-
Tunable Parameters: ML probability threshold slider (
$0.50 \dots 0.90$ ), transaction amount safety caps ($\le ₹2,00,000$ ), allowed payment methods, and failure mode filters. -
Pre-Activation Policy Simulator: Tests proposed policy modifications against canonical database records, computing immediate impacts on eligible volume (
$\Delta$ ) and expected recovery value ($\Delta$ ) before activation. -
Immutable Version History: Every policy change is permanently archived with mandatory change reason justifications (
$\ge 5$ characters) and audit logging.
RecoverAI integrates cleanly with Razorpay in Test Mode Sandbox:
[Backend Order Creation] ──► [Razorpay Web Checkout Modal] ──► [Backend HMAC-SHA256 Verification]
- Strict Test Mode Gating: Verifies that all initialized keys begin with
rzp_test_. Any attempt to passrzp_live_*keys triggers an immediate exception and disables execution. - Server-Side Secret Protection:
RAZORPAY_KEY_SECRETis strictly accessible only to Node.js server runtimes and is never exposed to browser bundles. - Cryptographic Signature Verification: Standard web checkout payments require HMAC-SHA256 signature verification (
razorpay_order_id + "|" + razorpay_payment_idsigned byRAZORPAY_KEY_SECRET). - Simulation Fallback:
DemoSimulationProviderprovides a deterministic offline fallback for local environments without active gateway credentials.
flowchart TD
A[Failed Payment Telemetry] --> B[ML Recovery Predictor]
B --> C[Expected Recovery Value Engine]
C --> D[Merchant Policy Engine]
D --> E[9-Factor Safety Guardrails]
E --> F1[Recovery Operations Center]
E --> F2[Smart Recovery Campaigns]
E --> F3[Recovery A/B Experiments]
F1 --> G[Recovery Agent Orchestrator]
F2 --> G
F3 --> G
G --> H1[Razorpay Test Mode Provider]
G --> H2[Demo Simulation Provider]
H1 --> I[Atomic Database State Update]
H2 --> I
I --> J[Sanitized Immutable Audit Ledger]
I --> K[Executive Analytics Engine]
| Layer | Technology | Description |
|---|---|---|
| Frontend Framework | Next.js 16.3.2 (App Router) | Server & Client Components, Turbopack, Fast Refresh |
| Language | TypeScript 5.0+ | Strict end-to-end type safety |
| Styling & Design | Vanilla CSS Design System | Custom tokens, dark mode (#09090b), WCAG AA contrast |
| Machine Learning | Python 3.11 + Scikit-Learn | Calibrated Logistic Regression, leak-free pipeline |
| Database & ORM | PostgreSQL 16 + Prisma ORM | Relational data model with compound indexes and constraints |
| Payment Gateway | Razorpay Node SDK | Test Mode (rzp_test_) with HMAC-SHA256 signature validation |
| Runtime & Tooling | Node.js 20+ / tsx | Native ESM TypeScript execution for scripts and migrations |
RecoverAI includes 11 specialized automated verification test suites covering 412 total validation checks:
# 1. Run Machine Learning Pipeline & Leakage Audit (13 checks)
python ml/test_pipeline.py
# 2. Run Phase 3 Recovery Operations & Safety Suite (24 checks)
npx tsx scripts/test_phase3.ts
# 3. Run End-to-End App Integration Suite (34 checks)
npx tsx scripts/verify_app_integration.ts
# 4. Run Razorpay Test Mode & Web Checkout Suite (21 checks)
npx tsx scripts/verify_razorpay_checkout.ts
# 5. Run Recovery Intelligence Engine Suite (64 checks)
npx tsx scripts/verify_recovery_intelligence.ts
# 6. Run Smart Recovery Campaigns Automation Suite (39 checks)
npx tsx scripts/verify_recovery_campaigns.ts
# 7. Run Executive Analytics & ROI Engine Suite (60 checks)
npx tsx scripts/verify_analytics.ts
# 8. Run Merchant Policy Controls & Simulator Suite (32 checks)
npx tsx scripts/verify_recovery_policy.ts
# 9. Run Recovery Experiments & A/B Testing Suite (48 checks)
npx tsx scripts/verify_recovery_experiments.ts
# 10. Run Product Quality, UX & Responsive Design Suite (66 checks)
npx tsx scripts/verify_day10_product_quality.ts
# 11. Run Master Final Certification (All 11 Domains Orchestrated)
npx tsx scripts/verify_final_certification.tsnpm run buildResult: Compiled successfully across 45 routes with 0 errors and 0 warnings.
- Node.js 20+
- PostgreSQL 15+ running locally or via Docker
- Python 3.11+ with
scikit-learn,pandas,numpy
git clone https://github.com/AtharvOps/RecoverAI.git
cd RecoverAI
npm install
pip install -r ml/requirements.txtCreate a local .env file based on .env.example:
DATABASE_URL="postgresql://postgres:password@localhost:5432/recoverai?schema=public"
NEXTAUTH_SECRET="your-development-session-secret-min-32-chars"
NEXTAUTH_URL="http://localhost:3000"
# Razorpay Test Mode Credentials (Optional for local offline simulation)
RAZORPAY_KEY_ID="rzp_test_your_test_key_id"
RAZORPAY_KEY_SECRET="your_test_key_secret"(Note: If Razorpay credentials are not provided, RecoverAI automatically uses the built-in DemoSimulationProvider fallback).
npx prisma generate
npx prisma db push
npm run seednpm run devOpen http://localhost:3000 in your browser.
For quick evaluation of the platform, use the pre-seeded demo merchant account:
- Demo Portal:
http://localhost:3000/login(or Live Demo) - Email:
demo@recoverai.io - Password:
demo123 - Active Workspace:
RecoverAI Demo Store - Mode:
Sandbox Test Mode (Razorpay Test)
For detailed architectural specifications, audit logs, and demonstration scripts, refer to the docs/ directory:
- 📐 System Architecture Document (
docs/FINAL_ARCHITECTURE.md) - 🔒 Security Audit & Hardening Report (
docs/SECURITY_AUDIT.md) - 🎬 Official Demo Presentation Guide (
docs/DEMO_GUIDE.md) - 🏆 Master Final Certification Record (
docs/FINAL_CERTIFICATION.md)
RecoverAI is open-source software licensed under the Apache-2.0 License.