Inspiration

Modern digital agencies, software consultancies, and independent B2B merchants face an operational bottleneck: while their services are high-value, their financial operations are fragmented and fragile. They struggle with delayed invoice payments, dispute friction with client chargebacks, and cumbersome manual escrow negotiations.

When a payment dispute occurs on standard gateways, merchants are forced to manually track down courier waybills, delivery signatures, and proof-of-work receipts across disparate systems. Often, they miss strict dispute response deadlines—forfeiting both their earned revenue and gateway standing.

We asked ourselves: What if an enterprise merchant operating system could autonomously defend merchant disputes using multimodal AI vision, calculate mathematically penny-accurate milestone escrows, and execute live PayPal payments with zero human latency?

That question led to PayPulse: an Autonomous B2B Escrow, Multimodal Vision Invoicing, and Self-Healing Dispute Protection Engine powered by React 19, Hono, AG Grid, PayPal Sandbox REST APIs, and Google Gemini Multimodal AI.


What It Does

PayPulse unites high-velocity billing, deterministic escrow calculations, and autonomous dispute defense within a calm, executive Finity Warm Matte Dark Bento workspace:

  • Executive Bento Overview Canvas: Provides instant visibility into aggregated ledger balances, live PayPal Sandbox wallet funds, multi-timeframe cashflow velocity curves, commercial cards, and a self-serve + Add widget Smart Workspace Assistant equipped with natural language intent recognition.
  • Deterministic 3-Step Milestone Invoicing: Allows merchants to bill clients across staged project tranches (such as \( 30\% / 40\% / 30\% \)). Every split is computed with integer-cent accuracy to ensure zero-penny rounding leaks: $$ \text{TotalCents} = \sum_{i=1}^{n} \text{TrancheCents}i \quad \text{where} \quad \text{Remainder} = \text{TotalCents} - \sum{i=1}^{n-1} \lfloor \text{TotalCents} \times r_i \rfloor $$
  • Smart Document & Waybill Scanner: Multimodal AI Vision powered by Google Gemini extracts vendor details, reference numbers, dates, line items, and totals in cents from uploaded receipts or delivery slips in under \( 3 \) seconds, generating a cryptographic SHA-256 evidence digest directly into SQLite.
  • Interactive Milestone Escrow Release: Staged client payment releases where tranches advance through PENDING_APPROVAL \( \rightarrow \) APPROVED \( \rightarrow \) RELEASED with real-time ledger write-through updates.
  • Autonomous Dispute Protection Agent: Live monitoring of open PayPal buyer claims (e.g., "Item or service not received"). A 5-stage deterministic AI playbook automatically cross-references uploaded courier waybills, validates GPS coordinates and recipient signatures, and submits cryptographic evidence to PayPal's Customer Disputes API within seconds.

How We Built It

We engineered PayPulse with an enterprise-first, production-hardened full-stack architecture:

1. Frontend Architecture

  • Framework: React 19 paired with Vite 6 (react-ts, TypeScript 5).
  • Styling & Design System: Tailwind CSS v4 (@tailwindcss/vite) utilizing our Finity Matte Dark palette (#141418 canvas, #1E1E26 elevated Bento cards with \( 24\text{px} \) border radii, #8B7CFF Periwinkle, #5CE1E6 Aqua Mint, and #FFC439 PayPal Gold).
  • Grid & Analytics: AG Grid Community v33 (ag-grid-react) customized to our dark theme via themeQuartz.withParams, combined with AG Charts v11 (ag-charts-react) for dual-spline cashflow velocity and thick rounded-cap expense donuts.
  • Icons & State: 100% vector SVG icons via Lucide React (zero emojis) and asynchronous server-state synchronization via @tanstack/react-query.

2. Backend & Database Architecture

  • API Server: High-throughput, lightweight Hono framework on Node.js 20 with hono/body-limit configured at \( 15\text{MB} \) to accommodate high-resolution multimodal vision payloads.
  • Database & Persistence: Embedded SQLite (better-sqlite3) operating in high-concurrency Write-Ahead Logging mode (journal_mode = WAL), with write-through synchronization to live PayPal Sandbox records and SHA-256 document proof hashing.

3. PayPal Developer Platform Integration

  • Direct PayPal Sandbox REST API Client:
    • Orders v2 (/v2/checkout/orders): Dynamic order creation and instant payment capture with full paypal-debug-id audit traceability.
    • Invoicing v2 (/v2/invoicing/invoices): Dynamic creation and formatting of itemized milestone invoices with payment due dates.
    • Customer Disputes v1 (/v1/customer/disputes): Programmatic ingestion of active claims and automated submission of courier evidence files.
    • Reporting Balances & Transactions v1: Live balance and ledger history retrieval.
    • OAuth2 Token Cache: Automated bearer token refresh with proactive \( 60\text{s} \) TTL renewal buffers.
  • PayPal JS SDK v6 (@paypal/react-paypal-js): Client-side PayPal Smart Payment Buttons and standard credit/debit card capture directly inside invoice modals.
  • PayPal MCP Server SSE (.mcp.json): Agent-to-Agent tool protocol integration for automated dispute resolution and sandbox state sync.

4. Multimodal AI Vision & Deterministic Playbooks

  • Google Gemini Multimodal Vision (gemini-3.5-flash-lite via @ai-sdk/google & Vercel AI SDK ai): Parses unformatted receipts, invoices, and delivery waybills to produce structured, Zod-validated financial records with a \( 10\text{s} \) circuit-breaker timeout (AbortSignal.timeout) and resilient offline fallback.
  • Deterministic Agent Playbook Engine: Orchestrates an idempotent 5-step dispute defense lifecycle that matches cryptographically verified delivery proofs against disputed PayPal transaction IDs.

5. Enterprise DevSecOps CI/CD Pipeline

  • Jenkins Declarative Pipeline (Jenkinsfile): 12 automated stages encompassing dependency audit, TypeScript compilation, Vitest test execution, SonarQube static analysis, Docker image compilation, and multi-environment promotion.
  • SonarQube Quality Gate: Strict zero-tolerance gate enforcing 0 Bugs, 0 Vulnerabilities, 0 Security Hotspots, and \( < 3\% \) Duplication.
  • Vitest Coverage Suite: 50 automated tests executing in \( < 2\text{s} \), guaranteeing \( 94.03\% \) statement coverage and \( 94.15\% \) line coverage with lcov.info reporting.
  • Multi-Environment Promotion: Multi-stage Docker topology (Dockerfile.frontend + Dockerfile.backend) verified across QA (:4000), UAT (:5000), and Production (:8080) via Docker Compose.

Challenges We Faced

  1. Floating-Point Precision in Escrow Math: Payment gateways reject transactions if line item sums mismatch by even \( \$0.01 \). Standard JavaScript floating-point arithmetic (e.g., \( 0.1 + 0.2 = 0.30000000000000004 \)) was strictly forbidden. We resolved this by building a dedicated integer-cent arithmetic engine (splitAmountIntoCents), ensuring that every fractional cent remainder is deterministically allocated to the final tranche: $$ \text{TotalCents} = \sum_{i=1}^{n} \text{Cents}_i $$
  2. AI Vision Throttling & Network Latency: Heavy vision models frequently suffered from Google API 503 high-demand spikes and exponential SDK retry loops, causing frontend spinners to hang for over \( 40\text{s} \). We benchmarked models and migrated to gemini-3.5-flash-lite, cutting inference times down to \( 2.8\text{s} \). We then wrapped calls in a \( 10\text{s} \) circuit breaker with automatic fallback to local cryptographic sample proofs, guaranteeing the UI never hangs.
  3. Idempotent Autonomous Dispute Defense: In an autonomous agent architecture, concurrent triggers can cause duplicate gateway submissions or race conditions. We designed an idempotent state machine (IDLE \( \rightarrow \) ANALYZING \( \rightarrow \) MATCHING_PROOF \( \rightarrow \) DISPATCHING_PAYPAL \( \rightarrow \) DEFENDED) that verifies SHA-256 evidence hashes and locks case records before dispatching requests to PayPal's Disputes API.

What We Learned

  • Balancing AI Agency with Financial Determinism: Generative AI excels at perception (reading chaotic, unformatted invoices and courier slips) and natural language intent classification. However, financial execution (gateway handshakes, escrow calculations, and ledger balances) must always be governed by strict, deterministic TypeScript contracts and Zod validation schemas.
  • Deep Mastery of the PayPal Sandbox REST Platform: Navigating Disputes v1, Orders v2, and Invoicing v2 simultaneously gave us deep insight into PayPal's event lifecycles, OAuth2 token renewal strategies, and paypal-debug-id correlation logging.
  • Enterprise DevSecOps Rigor: Integrating SonarQube with zero tolerance and achieving over \( 94\% \) automated test coverage ensured that the codebase remains completely free of security vulnerabilities, memory leaks, and technical debt.

What's Next for PayPulse

  • Agentic Purchasing via @paypal/agent-toolkit: Expanding the system so autonomous AI buyer agents can negotiate milestone deliverables and pay via PayPal balances programmatically.
  • Real-Time PayPal Webhook Ingestion: Deploying live webhook listeners for immediate, zero-click dispute defense the exact second a buyer opens a claim.
  • Multi-Currency Auto-Hedging: Integrating real-time foreign exchange conversion for cross-border milestone contracts.

Built With

Share this project:

Updates

Submission history