Normalized for Mintlify from
knowledge-base/aiconnected-apps-and-modules/modules/funnelChat/legacy-funnelChat-prd.mdx.Project Requirements Document (PRD)
funnelChat - AI-Powered Debt Collection Platform
Version: 1.0Date: November 23, 2025
Author: Oxford Pierpont / aiConnected
Status: Ready for Development
Table of Contents
- Executive Summary
- Product Vision & Goals
- User Personas
- Functional Requirements
- Technical Architecture
- Database Schema
- API Specifications
- User Interface Requirements
- AI & Chatbot Specifications
- Payment Processing
- Multi-Channel Communication
- Compliance & Security
- Analytics & Reporting
- Integration Requirements
- Testing Requirements
- Deployment & Infrastructure
- Success Metrics
1. Executive Summary
1.1 Product Overview
funnelChat is a comprehensive AI-powered chatbot platform designed to revolutionize the debt collection and accounts receivable industry. The platform automates debtor communication across multiple channels (SMS, WhatsApp, email, web chat) while maintaining regulatory compliance and providing businesses with powerful collection management tools.1.2 Key Capabilities
For Debtors:- 24/7 conversational AI support in multiple languages
- Self-service payment plan negotiation
- Secure payment processing
- Multi-channel communication options
- Real-time account information access
- Automated debtor outreach and follow-ups
- AI-powered conversation monitoring
- Compliance enforcement (FDCPA, TCPA, CFPB)
- Real-time analytics and reporting
- Payment plan management
- Multi-agent collaboration tools
1.3 Business Model
Subscription Tiers:- Free Tier: 0.03 per message (inbound + outbound)
- Basic Tier: 0.015 per overage message
- Premium Tier: 0.015 per overage message
- Subscription fees
- Usage-based charges (messages)
- Enterprise custom plans
- Professional services (setup, training)
1.4 Target Market
- Debt collection agencies
- Accounts receivable departments
- Medical billing companies
- Utility companies
- Financial institutions
- Property management companies
2. Product Vision & Goals
2.1 Vision Statement
To transform debt collection from an adversarial process into a cooperative, technology-enabled conversation that respects debtors while maximizing recovery rates for businesses.2.2 Product Goals
- Increase Recovery Rates: Improve payment collection by 30-40% through automated, personalized outreach
- Reduce Operational Costs: Lower cost per collection by 50% through AI automation
- Ensure Compliance: 100% FDCPA/TCPA compliant communications with automated monitoring
- Improve Debtor Experience: 90%+ satisfaction rate through empathetic, 24/7 support
- Scale Efficiently: Handle 10,000+ concurrent conversations per business client
2.3 Success Criteria
Phase 1 (MVP - Months 1-3):- Launch with 5 pilot business customers
- Process 10,000 conversations
- Achieve 95% chatbot accuracy
- Zero compliance violations
- Acquire 25 paying customers
- Process 100,000 conversations
- Add WhatsApp and voice channels
- Achieve 85% customer retention
- Reach 100 paying customers
- Process 1M+ conversations monthly
- Expand to international markets
- Achieve profitability
3. User Personas
3.1 Primary Personas
Persona 1: Sarah - The Debtor
Demographics:- Age: 32
- Occupation: Retail manager
- Tech proficiency: Medium
- Financial situation: Temporary hardship due to medical bills
- Understand her debt obligations clearly
- Negotiate a manageable payment plan
- Avoid embarrassing phone calls at work
- Rebuild her credit score
- Aggressive collection calls during work hours
- Confusing debt documentation
- Inability to afford full payment
- Fear of legal action
- 24/7 text-based communication
- Clear debt breakdown and payment options
- Automated payment plan proposals
- Respectful, empathetic AI conversations
Persona 2: Mike - The Collection Agent
Demographics:- Age: 38
- Role: Senior Collection Agent
- Experience: 10 years in collections
- Tech proficiency: Medium
- Maximize monthly recovery rates
- Handle more accounts efficiently
- Maintain compliance with regulations
- Reduce manual data entry work
- Time-consuming phone tag with debtors
- Manual note-taking and CRM updates
- Compliance anxiety (FDCPA violations)
- High-stress conversations
- AI handles initial outreach and routine conversations
- Auto-logging of all communications
- Real-time compliance alerts
- Focus on high-value accounts requiring human touch
Persona 3: Jennifer - The Collections Manager
Demographics:- Age: 45
- Role: VP of Collections
- Experience: 20 years in AR/collections
- Tech proficiency: High
- Increase portfolio recovery rates by 25%
- Reduce compliance risk to zero
- Lower cost per collection
- Improve team productivity
- High staffing costs
- Compliance violations leading to fines
- Lack of real-time visibility into operations
- Difficulty scaling during peak periods
- Automated 80% of routine communications
- Real-time compliance monitoring dashboard
- Comprehensive analytics and reporting
- Scalable automation without adding headcount
3.2 Secondary Personas
Persona 4: Alex - The System Administrator
- Manages technical infrastructure
- Configures integrations with existing systems
- Monitors platform performance
- Manages user access and permissions
Persona 5: Rachel - The Compliance Officer
- Ensures all communications meet regulatory requirements
- Audits conversation logs
- Generates compliance reports
- Updates communication policies
4. Functional Requirements
4.1 User Management
4.1.1 Authentication & Authorization
FR-AUTH-001: The system MUST support email/password authentication- Users register with email and password
- Passwords must be minimum 8 characters with complexity requirements
- Email verification required before account activation
- Password reset via email link
- Roles: Super Admin, Business Admin, Collection Agent, Debtor
- Each role has specific permissions
- Users can only access resources authorized for their role
- Tokens expire after 7 days
- Refresh token mechanism for extended sessions
- Tokens invalidated on password change
- Optional for debtors
- Required for business users
- TOTP-based (Google Authenticator, Authy)
4.1.2 User Profile Management
FR-USER-001: Users MUST be able to view and edit their profiles- Update name, email, phone number
- Change password
- Upload profile photo
- Set notification preferences
- Invite new users via email
- Assign roles to users
- Deactivate user accounts
- View user activity logs
- Track all user actions (login, data access, modifications)
- Logs retained for 7 years (compliance requirement)
- Logs viewable by admins
4.2 Account Management (Debtor Accounts)
4.2.1 Account Creation
FR-ACC-001: Business users MUST be able to create debtor accounts manually- Enter debtor information (name, email, phone, address)
- Set account balance and due date
- Add account notes
- Upload supporting documents
- Template CSV file provided
- Validation of required fields
- Preview before final import
- Error reporting for invalid records
- RESTful API endpoint
- Authentication via API key
- Webhook notification on successful creation
- Idempotency to prevent duplicates
4.2.2 Account Information
Each account MUST store:- Personal Information: First name, last name, email, phone(s), address
- Account Details: Account number, original creditor, current balance, due date
- Payment History: All payments made (date, amount, method)
- Communication History: All messages sent/received
- Status: Active, Paid in Full, In Payment Plan, Disputed, Legal
- Tags: Custom categorization labels
- Notes: Internal notes (not visible to debtor)
- Documents: Uploaded files (bills, agreements, correspondence)
4.2.3 Account Search & Filtering
FR-ACC-010: Users MUST be able to search accounts by:- Name (partial match)
- Account number
- Phone number
- Status
- Date range
- Balance range
- Tags
- Multiple filter criteria combined
- Save filter presets
- Export filtered results to CSV
4.3 Conversation Management
4.3.1 Conversation Creation
FR-CONV-001: The system MUST automatically create conversations when:- Debtor responds to an outbound message
- Debtor initiates contact via web widget
- Business user manually starts a conversation
- Scheduled campaign triggers
- One debtor account
- One communication channel (SMS, WhatsApp, email, web)
- Zero or one agent (can be unassigned for AI-only)
- Conversation status (Active, Resolved, Escalated, Closed)
4.3.2 Message Exchange
FR-CONV-010: Debtors MUST be able to send messages via:- SMS (Twilio)
- WhatsApp (Twilio)
- Email (SendGrid)
- Web chat widget
- Message content (text)
- Sender information
- Timestamp
- Read status
- Delivery status (for SMS/WhatsApp)
- Attachments (optional, up to 5MB)
- Messages grouped by conversation
- Chronological order
- Visual distinction between sent/received
- Typing indicators (web chat only)
4.3.3 AI Chatbot Integration
FR-CONV-020: AI chatbot MUST automatically respond to debtor messages when:- No agent is assigned to conversation
- Agent is offline and auto-response is enabled
- Message is a common FAQ
- Contextually relevant to conversation history
- Compliant with FDCPA regulations
- Empathetic in tone
- Accurate regarding account information
- Debtor explicitly requests human assistance
- AI confidence score is below threshold (70%)
- Conversation involves dispute or complaint
- Legal matters are mentioned
4.3.4 Agent Assignment
FR-CONV-030: Conversations MUST be assignable to agents via:- Manual assignment by manager
- Auto-assignment based on rules (round-robin, least active, skill-based)
- Agent self-assignment from queue
- Reassignment when agent is unavailable
- New conversation is assigned
- Debtor sends new message in assigned conversation
- Conversation requires escalation
4.4 Payment Processing
4.4.1 Payment Methods
FR-PAY-001: The system MUST support payment via:- Credit card (Visa, Mastercard, Amex, Discover)
- Debit card
- ACH bank transfer
- Payment link (sent via SMS/email)
- PCI DSS compliant
- Stripe Checkout for card payments
- Stripe ACH for bank transfers
- 3D Secure authentication for cards
4.4.2 One-Time Payments
FR-PAY-010: Debtors MUST be able to make one-time payments- Enter payment amount (min $1, max account balance)
- Select payment method
- Receive confirmation email
- Payment immediately applied to account balance
4.4.3 Payment Plans
FR-PAY-020: The system MUST support payment plan creation- Business user or AI can propose payment plan
- Specify: down payment, number of installments, payment frequency
- Auto-calculate installment amounts
- Generate payment schedule
- Total amount owed
- Down payment amount (if any)
- Number of installments
- Payment frequency (weekly, bi-weekly, monthly)
- Start date
- Auto-pay option
- Late fee policy (if applicable)
- Review plan details
- Provide digital signature (checkbox consent)
- Setup auto-pay (optional)
- Receive plan confirmation email
- Automatic charge on due dates (if auto-pay enabled)
- Email/SMS reminders 3 days before due date
- Grace period of 5 days after due date
- Mark plan as defaulted after 2 missed payments
4.4.4 Payment Modifications
FR-PAY-030: Debtors MUST be able to request payment plan changes- Request payment date change
- Request payment amount adjustment
- Request payment plan pause (financial hardship)
- Requests subject to business approval
- Adjust payment amounts
- Extend payment plan duration
- Waive late fees
- Cancel payment plan
4.4.5 Failed Payments
FR-PAY-040: The system MUST handle failed payments- Retry payment 3 times over 5 days
- Notify debtor via email/SMS
- Update account status to “Payment Failed”
- Allow manual retry by debtor
4.5 Campaign Management
4.5.1 Campaign Creation
FR-CAMP-001: Business users MUST be able to create outbound campaigns- Define campaign name and description
- Select target accounts (by filter or manual selection)
- Choose communication channel(s)
- Set campaign schedule (immediate or scheduled)
- Define message template with variables
{firstName},{lastName},{accountNumber},{balance},{dueDate}- Preview with sample data before sending
- Templates stored for reuse
4.5.2 Campaign Execution
FR-CAMP-010: The system MUST execute campaigns according to schedule- Send messages at specified time
- Respect timezone of debtor
- Rate limiting (max 1000 messages per minute)
- Halt campaign if compliance violation detected
- Messages sent
- Messages delivered
- Responses received
- Conversations started
- Payments made
- ROI calculation (payments ÷ campaign cost)
4.5.3 Compliance Controls
FR-CAMP-020: The system MUST enforce communication frequency limits- Max 3 SMS per week per debtor
- Max 5 emails per week per debtor
- Max 1 WhatsApp per day per debtor
- Respect “Do Not Contact” lists
- “STOP” keyword immediately opts out of SMS
- Unsubscribe link in all emails
- Opt-out status synced across all channels
- Audit log of all opt-out events
4.6 Compliance Features
4.6.1 FDCPA Compliance
FR-COMP-001: All messages MUST include required disclosures- Debt validation notice on first communication
- Mini-Miranda warning (debt collector identification)
- Creditor name and amount owed
- Right to dispute debt
- No threats of violence or harm
- No profanity or abuse
- No false representations
- No deceptive means
- AI responses scanned before sending
- No contact before 8am or after 9pm debtor’s local time
- No contact at workplace if debtor objects
- No contact with third parties (except attorney)
- No contact if debtor is represented by attorney
4.6.2 TCPA Compliance
FR-COMP-010: The system MUST verify consent before automated communications- Explicit opt-in required for SMS/calls
- Consent stored with timestamp and IP
- Consent revocable at any time
- No marketing messages without separate consent
4.6.3 Data Privacy (GDPR/CCPA)
FR-COMP-020: The system MUST support data subject rights- Right to access: Provide all data about debtor
- Right to deletion: Permanently delete debtor data
- Right to rectification: Allow data corrections
- Right to portability: Export data in machine-readable format
- At rest: AES-256 encryption
- In transit: TLS 1.3
- Database: Encrypted fields for PII
- Backups: Encrypted
4.6.4 Audit Logging
FR-COMP-030: The system MUST log all compliance-relevant events- All communications (sent, received, failed)
- All payment transactions
- All account modifications
- All consent grants/revocations
- All data access and exports
- All compliance violations detected
- Immutable (cannot be edited or deleted)
- Retained for 7 years
- Searchable by date, user, event type
- Exportable for regulatory audits
4.7 Analytics & Reporting
4.7.1 Real-Time Dashboard
FR-ANLY-001: Business users MUST have access to real-time dashboard showing:- Total accounts managed
- Total outstanding balance
- Collections this month (amount and %)
- Active conversations (count)
- Messages sent/received today
- Payment success rate
- AI chatbot performance metrics
- Customizable (drag and drop)
- Filterable by date range
- Exportable as PDF/PNG
- Refreshable (auto-refresh every 60 seconds)
4.7.2 Collection Reports
FR-ANLY-010: The system MUST generate collection reports:- Portfolio Summary: Total accounts, total balance, aging buckets
- Recovery Report: Payments collected by time period
- Channel Performance: Effectiveness of SMS vs Email vs Web
- Agent Performance: Recovery by agent, response time, customer satisfaction
- Campaign ROI: Payments attributed to specific campaigns
- Date range selection
- Export to CSV, Excel, PDF
- Scheduled delivery via email
- Custom report builder
4.7.3 Predictive Analytics
FR-ANLY-020: The system SHOULD provide predictive insights- Likelihood to pay score (0-100)
- Optimal contact time prediction
- Recommended payment plan amount
- Churn risk score
4.8 Administration
4.8.1 Business Settings
FR-ADMIN-001: Business admins MUST be able to configure:- Company name and branding
- Default payment terms
- Communication frequency limits
- Auto-response settings
- Integration credentials
- Billing information
4.8.2 Team Management
FR-ADMIN-010: Business admins MUST be able to:- Add/remove team members
- Assign roles and permissions
- Set agent availability schedules
- Configure conversation routing rules
- Monitor team activity
4.8.3 Template Management
FR-ADMIN-020: Users MUST be able to manage templates for:- Message templates (SMS, email, WhatsApp)
- Payment plan templates
- Document templates (agreements, letters)
- Email signatures
5. Technical Architecture
5.1 System Architecture Overview
5.2 Technology Stack Details
5.2.1 Front-End Stack
Framework: React 18.2+ with TypeScript 5.0+- Why React: Large ecosystem, component reusability, strong community
- Why TypeScript: Type safety, better IDE support, fewer runtime errors
- Global State: User auth, selected account, UI preferences
- Server State: React Query (TanStack Query) for API data caching
- Why MUI: Production-ready components, accessibility built-in, customizable theming
- Components Used: DataGrid, Dialog, Snackbar, Drawer, AppBar, etc.
- Protected Routes: Higher-order component for authenticated routes
- Lazy Loading: Code splitting for better performance
- Use Cases: Live chat, notification badges, dashboard updates
- Why Vite: Fast hot module replacement, optimized builds
5.2.2 Back-End Stack
Runtime: Node.js 20 LTS- Why Node.js: JavaScript everywhere, large package ecosystem, async I/O
- Why Express: Minimalist, flexible, extensive middleware ecosystem
- Compilation: ts-node for development, compiled to JS for production
- Why Prisma: Type-safe queries, migrations, introspection, admin UI
- Database: PostgreSQL 15+
- Why Zod: TypeScript-first, runtime validation, type inference
- Tool: swagger-jsdoc + swagger-ui-express
- Why Bull: Redis-backed, reliable, retries, priorities, delayed jobs
- Authentication: JWT tokens in handshake
5.2.3 Database
Primary Database: PostgreSQL 15+- Why PostgreSQL: ACID compliance, JSON support, full-text search, mature
- Hosting: AWS RDS or managed PostgreSQL (DigitalOcean, Render)
- Use Cases: Session store, rate limiting, job queue, real-time data
- Hosting: AWS ElastiCache or managed Redis
- Use Cases: Document uploads, exported reports, email attachments
- Why S3: Durable (99.999999999%), scalable, low-cost
5.2.4 AI & NLP
LLM Provider: Anthropic Claude API- Model: claude-sonnet-4-20250514
- Why Claude: Strong reasoning, long context, safety features, compliance awareness
- System prompts define chatbot personality and constraints
- Few-shot examples for consistency
- Chain-of-thought for complex reasoning
- Compliance filters in system prompts
- Classifies messages as: Positive, Neutral, Negative, Hostile
- Triggers escalation on Hostile sentiment
5.2.5 Third-Party Services
Payment Processing: Stripe- Products: Checkout, Billing, Payment Intents, Webhooks
- Why Stripe: PCI compliance, 135+ currencies, extensive API
- Products: Programmable SMS, WhatsApp Business API
- Why Twilio: Reliability, global coverage, developer-friendly
- Products: Transactional Email API
- Why SendGrid: Deliverability, analytics, templates
- Application: Datadog, New Relic
- Errors: Sentry
- Logs: CloudWatch (AWS) or Papertrail
5.3 Security Architecture
5.3.1 Authentication Flow
5.3.2 Authorization (RBAC)
Roles:super_admin: Full system access (aiConnected staff)business_admin: Full access within their businessmanager: Manage agents, view all accountsagent: View assigned accounts, respond to conversationsdebtor: View own account, make payments
| Resource | Super Admin | Business Admin | Manager | Agent | Debtor |
|---|---|---|---|---|---|
| Create Business | ✅ | ❌ | ❌ | ❌ | ❌ |
| View All Accounts | ✅ | ✅ | ✅ | ❌ | ❌ |
| View Own Account | N/A | N/A | N/A | N/A | ✅ |
| Assign Conversations | ✅ | ✅ | ✅ | ❌ | ❌ |
| Respond to Conversations | ✅ | ✅ | ✅ | ✅ | ✅ |
| Create Payment Plan | ✅ | ✅ | ✅ | ✅ | ❌ |
| Make Payment | N/A | N/A | N/A | N/A | ✅ |
| View Analytics | ✅ | ✅ | ✅ | ❌ | ❌ |
| Manage Users | ✅ | ✅ | ❌ | ❌ | ❌ |
5.3.3 Data Encryption
At Rest:- Database: PostgreSQL with encryption enabled
- Sensitive fields (SSN, bank account): AES-256 encryption in application layer
- File storage: S3 server-side encryption (SSE-S3 or SSE-KMS)
- All HTTP traffic: TLS 1.3
- API to third-parties: HTTPS only
- WebSocket: WSS (WebSocket Secure)
- Encryption keys stored in AWS Secrets Manager or environment variables
- Key rotation every 90 days
- Separate keys for dev/staging/production
5.3.4 Rate Limiting
Global Rate Limits (per IP address):- 1000 requests per minute
- 10,000 requests per hour
- Enforced via Redis with sliding window
- Login: 5 attempts per 15 minutes per IP
- Password reset: 3 requests per hour per email
- Authenticated users: 100 requests per minute
- Public endpoints: 20 requests per minute
5.4 Scalability Considerations
5.4.1 Horizontal Scaling
API Servers:- Stateless design (no session affinity required)
- Load balancer distributes traffic (round-robin or least connections)
- Auto-scaling based on CPU (scale up at 70%, down at 30%)
- Read replicas for analytics queries
- Connection pooling (pg-pool)
- Partitioning for large tables (messages, audit_logs)
- Multiple worker processes
- Queue-based workload distribution
- Horizontal scaling by adding workers
5.4.2 Performance Optimizations
Caching Strategy:- Redis for frequently accessed data (user sessions, account summaries)
- CDN for static assets (JS, CSS, images)
- HTTP caching headers for API responses
- Indexed columns: email, phone, accountNumber, createdAt
- Composite indexes for common query patterns
- Analyze slow queries with EXPLAIN
- Code splitting (React lazy loading)
- Image compression and WebP format
- Minification and bundling (Vite)
6. Database Schema
6.1 Schema Overview
The database uses PostgreSQL with Prisma ORM. All tables use UUIDs for primary keys,createdAt and updatedAt timestamps.
6.2 Entity Relationship Diagram (ERD)
6.3 Table Definitions
6.3.1 businesses
Stores collection businesses/agencies using the platform.6.3.2 users
Stores all users (business staff and debtors).6.3.3 sessions
Stores active user sessions (for session management and revocation).6.3.4 accounts
Stores debtor account information.6.3.5 conversations
Stores chat conversations with debtors.6.3.6 messages
Stores individual messages within conversations.6.3.7 payments
Stores payment transactions.6.3.8 payment_plans
Stores payment plan agreements.6.3.9 campaigns
Stores outbound messaging campaigns.6.3.10 audit_logs
Stores comprehensive audit trail for compliance.6.3.11 documents
Stores uploaded files and generated documents.6.3.12 templates
Stores reusable templates for messages, agreements, etc.6.4 Sample Data
Seebackend/prisma/seed.ts for database seeding script.
7. API Specifications
7.1 API Design Principles
RESTful Design:- Use HTTP verbs correctly (GET, POST, PUT, PATCH, DELETE)
- Resource-based URLs (nouns, not verbs)
- Plural resource names (
/accountsnot/account)
- All endpoints prefixed with
/api/v1 - Version in URL for simplicity
- All responses in JSON
- Consistent structure
7.2 Authentication Endpoints
POST /api/v1/auth/register
Register a new user account. Request Body:400: Email already exists400: Invalid password format400: Invalid role
POST /api/v1/auth/login
Login with email and password. Request Body:401: Invalid credentials401: Account not verified401: Account suspended
POST /api/v1/auth/logout
Logout current user (invalidate token). Headers:POST /api/v1/auth/forgot-password
Request password reset email. Request Body:POST /api/v1/auth/reset-password
Reset password with token. Request Body:400: Invalid or expired token400: Password does not meet requirements
7.3 Account Endpoints
GET /api/v1/accounts
List all accounts (with pagination and filtering). Headers:page(number, default: 1)limit(number, default: 20, max: 100)status(string: active, paid_in_full, etc)search(string: search by name, email, phone, account number)tags(string: comma-separated tags)sortBy(string: createdAt, balance, dueDate)sortOrder(string: asc, desc)
GET /api/v1/accounts/:id
Get account details. Headers:404: Account not found403: Not authorized to view this account
POST /api/v1/accounts
Create a new account. Headers:400: Validation error403: Not authorized to create accounts
PATCH /api/v1/accounts/:id
Update account information. Headers:404: Account not found400: Validation error403: Not authorized
DELETE /api/v1/accounts/:id
Delete (soft delete) an account. Headers:404: Account not found403: Not authorized400: Cannot delete account with active payment plan
POST /api/v1/accounts/bulk-import
Import multiple accounts from CSV. Headers:7.4 Conversation Endpoints
GET /api/v1/conversations
List conversations. Headers:page,limitstatus(active, resolved, escalated, closed)channel(sms, whatsapp, email, web_chat)assignedTo(user ID)accountId(filter by account)
GET /api/v1/conversations/:id
Get conversation details with messages. Headers:POST /api/v1/conversations
Create new conversation (start outreach). Headers:POST /api/v1/conversations/:id/messages
Send message in conversation. Headers:PATCH /api/v1/conversations/:id
Update conversation (e.g., assign agent, change status). Headers:7.5 Payment Endpoints
POST /api/v1/payments
Process a one-time payment. Headers:400: Insufficient amount400: Payment method required402: Payment failed (card declined, etc.)
GET /api/v1/payments
List payments for an account. Headers:accountId(required)status(succeeded, failed, refunded)
POST /api/v1/payment-plans
Create a payment plan. Headers:GET /api/v1/payment-plans/:id
Get payment plan details. Response: Full payment plan object with payment history.PATCH /api/v1/payment-plans/:id
Modify payment plan. Request Body:7.6 Campaign Endpoints
POST /api/v1/campaigns
Create campaign. Headers:GET /api/v1/campaigns/:id
Get campaign details and metrics. Response (200 OK):7.7 Analytics Endpoints
GET /api/v1/analytics/dashboard
Get dashboard summary. Headers:period(today, week, month, year, custom)startDate(for custom period)endDate(for custom period)
GET /api/v1/analytics/collection-report
Get detailed collection report. Query Parameters:startDate,endDategroupBy(day, week, month)
GET /api/v1/analytics/channel-performance
Compare performance across channels (SMS, email, WhatsApp). Response: Metrics per channel (response rate, payment rate, etc.).7.8 Admin Endpoints
GET /api/v1/admin/users
List all users in business.POST /api/v1/admin/users
Create new user.PATCH /api/v1/admin/users/:id
Update user (change role, activate/deactivate).GET /api/v1/admin/settings
Get business settings.PATCH /api/v1/admin/settings
Update business settings.7.9 Webhook Endpoints
POST /api/v1/webhooks/stripe
Stripe webhook handler for payment events. No authentication (verified via Stripe signature). Events handled:checkout.session.completedinvoice.payment_succeededinvoice.payment_failedcustomer.subscription.updatedcustomer.subscription.deleted
POST /api/v1/webhooks/twilio/sms
Twilio webhook for incoming SMS. Request Body (from Twilio):POST /api/v1/webhooks/twilio/whatsapp
Twilio webhook for incoming WhatsApp messages. Similar to SMS handler.POST /api/v1/webhooks/sendgrid
SendGrid webhook for email events (delivered, opened, clicked, bounced).8. User Interface Requirements
8.1 Design Principles
Consistency:- Use Material-UI components throughout
- Consistent spacing (8px grid)
- Consistent color palette
- Consistent typography
- WCAG 2.1 AA compliance
- Keyboard navigation support
- Screen reader friendly
- Sufficient color contrast (4.5:1 minimum)
- Mobile-first design
- Breakpoints: xs (0px), sm (600px), md (900px), lg (1200px), xl (1536px)
- Touch-friendly targets (minimum 44x44px)
- Initial load < 3 seconds
- Time to interactive < 5 seconds
- Lazy load images and heavy components
- Optimize bundle size (code splitting)
8.2 Color Palette
Primary Colors:- Primary: #1976d2 (Blue)
- Secondary: #dc004e (Pink/Red)
- Success: #4caf50 (Green)
- Warning: #ff9800 (Orange)
- Error: #f44336 (Red)
- Info: #2196f3 (Light Blue)
- Gray 50: #fafafa
- Gray 100: #f5f5f5
- Gray 200: #eeeeee
- Gray 300: #e0e0e0
- Gray 400: #bdbdbd
- Gray 500: #9e9e9e
- Gray 600: #757575
- Gray 700: #616161
- Gray 800: #424242
- Gray 900: #212121
- Active: #4caf50
- Pending: #ff9800
- Failed: #f44336
- Completed: #2196f3
8.3 Typography
Font Family: Roboto (Material-UI default) Font Sizes:- h1: 96px (page titles, rarely used)
- h2: 60px
- h3: 48px
- h4: 34px (section headings)
- h5: 24px (card titles)
- h6: 20px (sub-headings)
- body1: 16px (default body text)
- body2: 14px (secondary text)
- button: 14px (all caps, medium weight)
- caption: 12px (help text, labels)
8.4 Application Layouts
8.4.1 Debtor Portal Layout
- Dashboard: Account overview, balance, payment history
- Chat: Active conversations with AI/agents
- Payments: Make payment, view payment plans
- Profile: Update contact info, preferences
8.4.2 Business Dashboard Layout
- Dashboard (home icon)
- Accounts (folder icon)
- Conversations (chat icon)
- Campaigns (megaphone icon)
- Analytics (chart icon)
- Settings (gear icon)
- Dashboard: Key metrics, recent activity
- Accounts: Table of all debtor accounts
- Conversations: Live chat inbox
- Campaigns: Create and manage campaigns
- Analytics: Reports and charts
- Settings: Business settings, team management
8.4.3 Admin Panel Layout
Similar to Business Dashboard but with additional sections:- Businesses: Manage all business accounts
- Users: Global user management
- Billing: Subscription and usage monitoring
- System: Health checks, logs
8.5 Key UI Components
8.5.1 Account Table (Business Dashboard)
Component: MUI DataGrid Columns:- Account Number
- Name
- Phone
- Balance
- Due Date
- Status (chip with color)
- Actions (view, edit, delete icons)
- Sortable columns
- Filterable
- Search bar
- Bulk actions (tag, export, delete)
- Pagination
8.5.2 Chat Interface (Both Portals)
Layout: Split view (list + conversation)- Outbound: Blue, right-aligned
- Inbound: Gray, left-aligned
- AI-generated: Badge indicating “AI” or robot icon
- Timestamp and delivery status icons
- Real-time updates (Socket.io)
- Typing indicators
- File attachments
- Quick actions (propose payment plan, escalate)
8.5.3 Payment Form (Debtor Portal)
- Amount must be > $0 and <= balance
- Card details validated by Stripe
- Show errors inline
8.5.4 Dashboard Widgets (Business Dashboard)
Widget Grid: 2x2 or 3x3 grid of cards Example Widgets:- Total Outstanding:
- Collections This Month:
- Active Conversations:
- AI Performance:
8.5.5 Analytics Charts
Library: Recharts Chart Types:- Line Chart: Collections over time
- Bar Chart: Channel performance comparison
- Pie Chart: Account status distribution
- Area Chart: Recovery rate trends
8.6 Mobile Responsiveness
Breakpoint Behavior: Desktop (>900px):- Full sidebar navigation
- Multi-column layouts
- Large data tables
- Collapsible sidebar
- 2-column layouts become single-column
- Simplified tables (hide less important columns)
- Bottom navigation bar instead of sidebar
- Single column layouts
- Card-based UI instead of tables
- Hamburger menu for secondary navigation
8.7 Loading States
Skeleton Screens: Use MUI Skeleton for loading states Example:8.8 Error States
Error Messages: Use Snackbar (toast) for temporary errors Persistent Errors: Use Alert component Form Validation Errors: Inline below field with helper text Empty States: Friendly illustrations and call-to-action Example:9. AI & Chatbot Specifications
9.1 AI Architecture
Primary LLM: Anthropic Claude Sonnet 4 (claude-sonnet-4-20250514) Conversation Flow:9.2 Prompt Engineering
9.2.1 System Prompt
9.2.2 User Message Template
9.2.3 Required Disclosures (First Contact)
9.3 Intent Recognition
Claude identifies user intent to route conversations appropriately. Common Intents:- Request Payment Plan: “Can I set up a payment plan?”
- Dispute Debt: “I don’t owe this money”
- Request Information: “How much do I owe?”
- Make Payment: “I want to pay now”
- Financial Hardship: “I lost my job and can’t pay”
- Request Human: “I want to speak to a person”
- Hostile/Abusive: Profanity, threats
- Cease Contact: “Stop contacting me”
- Payment Plan → Generate plan options
- Dispute → Provide validation rights, escalate
- Information → Provide account details
- Make Payment → Send payment link
- Hardship → Empathize, propose reduced plan
- Request Human → Escalate immediately
- Hostile → Apologize, escalate, log
- Cease Contact → Confirm, mark account DNR, stop all contact
9.4 Sentiment Analysis
Sentiment Levels:- Positive: Cooperative, grateful
- Neutral: Matter-of-fact, informational
- Negative: Frustrated, stressed
- Hostile: Angry, threatening, abusive
- Positive: Continue AI conversation
- Neutral: Continue AI conversation
- Negative: Adjust tone to be more empathetic, monitor
- Hostile: Escalate to human agent immediately
9.5 Payment Plan Generation
AI generates payment plan proposals based on:- Total debt amount
- Debtor’s stated affordability
- Historical payment behavior
- Business policies
9.6 Compliance Checking
Every AI-generated message is checked for compliance violations before sending. Compliance Prompt:- Log violation
- Regenerate response with stricter constraints
- If still non-compliant after 2 attempts, escalate to human
- Alert compliance team
9.7 Conversation Handoff to Human
Handoff Triggers:- Debtor explicitly requests human
- AI confidence below threshold (70%)
- Sentiment is hostile
- Legal matters mentioned
- Dispute filed
- Complex negotiation required
- AI sends acknowledgment: “I’m connecting you with one of our specialists who can better assist you.”
- Conversation marked as “escalated”
- Notification sent to available agents
- Agent sees full conversation history
- Agent takes over conversation
9.8 AI Performance Metrics
Tracked Metrics:- AI Handled Rate: % of conversations fully handled by AI without human intervention
- Average Confidence Score: Average Claude confidence across all responses
- Escalation Rate: % of conversations escalated to humans
- Resolution Rate: % of AI conversations resulting in payment/plan
- Compliance Pass Rate: % of messages passing compliance check on first attempt
- Average Response Time: Time from debtor message to AI response
- AI Handled Rate: >75%
- Average Confidence: >0.85
- Escalation Rate: <15%
- Compliance Pass Rate: >99%
- Average Response Time: <5 seconds
10. Payment Processing
10.1 Stripe Integration
Stripe Products:- Stripe Checkout: For one-time payments
- Stripe Payment Intents: For custom payment flows
- Stripe Billing: For subscription management (business billing)
- Stripe ACH: For bank transfers
- Stripe Webhooks: For event notifications
10.2 One-Time Payment Flow
Frontend (Debtor Portal):10.3 Payment Plan Setup
Frontend:10.4 Recurring Payment Processing
Job Scheduler (Bull Queue):10.5 Failed Payment Handling
Retry Logic:10.6 Subscription Billing (Business Customers)
Stripe Setup:- Create Products in Stripe for each tier (Free, Basic, Premium)
- Create Price for each product
- Create Price for overage messaging (usage-based)
11. Multi-Channel Communication
11.1 SMS Integration (Twilio)
Setup:- Create Twilio account
- Purchase phone number with SMS capability
- Configure webhook URL:
https://your-domain.com/api/webhooks/twilio/sms
11.2 WhatsApp Integration (Twilio)
Setup:- Apply for WhatsApp Business API access through Twilio
- Configure webhook URL:
https://your-domain.com/api/webhooks/twilio/whatsapp
11.3 Email Integration (SendGrid)
Setup:- Create SendGrid account
- Verify sender email/domain
- Configure inbound parse webhook
11.4 Web Chat Widget
Widget Embed Code (for debtor portal or external websites):widget.js):
11. Security & Compliance
11.1 Security Requirements
11.1.1 Data Encryption
In Transit:- All API communication over HTTPS (TLS 1.3)
- WebSocket connections over WSS
- Strong cipher suites only
- HSTS headers enabled
- Database encryption (PostgreSQL transparent data encryption)
- AES-256 encryption for sensitive fields (SSN, payment data)
- Encrypted backups
11.1.2 Authentication & Authorization
Authentication:- JWT tokens with 24-hour expiration
- Refresh tokens with 30-day expiration
- Secure password hashing (bcrypt, cost factor 12)
- Password requirements:
- Minimum 12 characters
- Uppercase, lowercase, number, special character
- No common passwords (check against list)
- Role-based access control (RBAC)
- Principle of least privilege
- Resource-level permissions
- API key authentication for integrations
- Tokens stored in httpOnly cookies (web)
- Tokens in secure storage (mobile)
- Auto-logout after 30 min inactivity
- Session invalidation on logout
11.1.3 Input Validation & Sanitization
- Validate all user inputs server-side
- Sanitize inputs to prevent XSS
- Parameterized queries to prevent SQL injection
- Rate limiting on all endpoints
- File upload validation (type, size, content)
11.1.4 API Security
- API versioning
- Rate limiting per user/organization
- Request size limits
- CORS configuration (whitelist origins)
- API key rotation every 90 days
- Webhook signature verification
11.2 Compliance Requirements
11.2.1 FDCPA (Fair Debt Collection Practices Act)
Communications:- No contact before 8 AM or after 9 PM (debtor local time)
- Max 3 contact attempts per week
- Honor cease-and-desist requests immediately
- Include disclosure statement in first communication
- No false or misleading statements
- No threats or harassment
- No disclosure to third parties
- Automated quiet hours check before every message
- Frequency limit tracking per debtor
- Content scanning for prohibited phrases
- Opt-out list management
- Complete audit trail (7-year retention)
11.2.2 TCPA (Telephone Consumer Protection Act)
Requirements:- Obtain prior express written consent for automated calls/texts
- Include opt-out mechanism in every message
- Honor opt-out requests within 24 hours
- Maintain Do Not Call (DNC) list
- Consent record for each debtor
- Opt-out link/keyword in every SMS/WhatsApp
- Automated DNC list checking
- Scrubbing against national DNC list (monthly)
11.2.3 CFPB (Consumer Financial Protection Bureau)
Requirements:- Clear and conspicuous disclosures
- Accurate debt validation
- Dispute handling process
- Recordkeeping (3 years minimum)
- Disclosure templates
- Dispute workflow with tracking
- Validation documentation storage
- Comprehensive logging
11.2.4 GDPR & CCPA (Data Privacy)
GDPR (if applicable):- Right to access (export user data)
- Right to deletion (“forget me”)
- Right to rectification (update data)
- Data portability
- Consent management
- Data processing agreements
- Notice at collection
- Right to know
- Right to delete
- Right to opt-out of sale
- Non-discrimination
- Data export API endpoint
- Data deletion workflow (soft delete)
- Privacy policy acceptance tracking
- Cookie consent banner
- Third-party data processing list
11.2.5 PCI DSS (Payment Card Industry)
Requirements:- Never store card numbers, CVV, or magnetic stripe data
- Use Stripe.js for PCI compliance (SAQ-A)
- Tokenize all payment methods
- Secure transmission of cardholder data
- Regular security assessments
- All payment forms use Stripe Elements
- No card data touches our servers
- Stripe handles all sensitive data
- Annual PCI compliance certification
11.3 Audit & Logging
What to Log:- All communications (sent, received, failed)
- Payment transactions
- User actions (login, data changes)
- System events (errors, warnings)
- Compliance checks (passed/failed)
- Access to sensitive data
- Compliance logs: 7 years
- Transaction logs: 7 years
- System logs: 1 year
- Access logs: 1 year
- Encrypted at rest
- Tamper-proof (append-only)
- Separate storage from application database
- Regular backups
- Access restricted to admins
11.4 Security Monitoring
Real-Time Alerts:- Failed login attempts (>5 in 1 hour)
- Unusual API activity
- Compliance violations
- Payment failures (>10% rate)
- System errors (>1% rate)
- Dependency vulnerability scanning (weekly)
- Penetration testing (annually)
- Code security review (quarterly)
- Infrastructure security audit (quarterly)
12. Integration Requirements
12.1 Stripe Integration
Purpose: Payment processing Setup:- Create Stripe account
- Get API keys (test and live)
- Set up webhook endpoints
- Configure products and prices
payment_intent.succeededpayment_intent.failedcharge.refundedcustomer.subscription.createdcustomer.subscription.updatedcustomer.subscription.deletedinvoice.payment_succeededinvoice.payment_failed
12.2 Twilio Integration
Purpose: SMS and voice communications Setup:- Create Twilio account
- Purchase phone numbers
- Configure webhooks for incoming messages
- Set up messaging service
- SMS incoming: POST
/webhooks/twilio/sms - SMS status: POST
/webhooks/twilio/sms/status - Voice incoming: POST
/webhooks/twilio/voice(future)
12.3 WhatsApp Business API Integration
Purpose: WhatsApp messaging Setup:- Apply for WhatsApp Business API access
- Verify business
- Create message templates
- Configure webhooks
- Payment reminder
- Payment confirmation
- Payment plan created
- Account statement
12.4 Email Integration (SendGrid)
Purpose: Transactional emails Email Types:- Welcome email
- Password reset
- Payment receipt
- Payment plan created
- Payment failed
- Compliance notices
12.5 OpenAI/Anthropic Integration
Purpose: Conversational AI Implementation:13. Testing Requirements
13.1 Unit Testing
Framework: Jest Coverage: 80% minimum What to Test:- Business logic functions
- API service functions
- Component rendering
- Redux reducers and actions
13.2 Integration Testing
Framework: Jest + Supertest What to Test:- API endpoints
- Database operations
- External service integrations (mocked)
- Authentication/authorization flows
13.3 End-to-End Testing
Framework: Cypress or Playwright Critical Flows:- User registration and login
- Create debtor and debt
- Conversation flow (SMS chatbot)
- Payment processing
- Payment plan creation
13.4 Performance Testing
Tools: k6 or Artillery Targets:- API: 95th percentile < 500ms
- Page load: < 3 seconds
- Support 1,000 concurrent users
14. Deployment & Infrastructure
14.1 Cloud Provider
AWS (Amazon Web Services) Services:- ECS Fargate (container orchestration)
- RDS PostgreSQL (database)
- ElastiCache Redis (caching)
- S3 (file storage)
- CloudFront (CDN)
- Route 53 (DNS)
- ALB (load balancing)
- Secrets Manager (credentials)
14.2 Environments
- Development - Local development
- Staging - QA testing
- Production - Live
14.3 CI/CD Pipeline
Tool: GitHub Actions Stages:- Code push
- Run tests
- Build Docker images
- Deploy to staging
- Run E2E tests
- Manual approval
- Deploy to production
15. Success Metrics
15.1 Product Metrics
- Daily Active Users (DAU)
- Conversations per day
- AI resolution rate
- Payment rate
- Average time to payment
- Customer satisfaction (NPS)
15.2 Business Metrics
- Monthly Recurring Revenue (MRR)
- Customer acquisition cost (CAC)
- Lifetime value (LTV)
- Churn rate
15.3 Technical Metrics
- API response time (p95)
- Uptime (%)
- Error rate
- Database query performance
16. Development Phases
Phase 1: MVP (Months 1-4)
Features:- User authentication
- Debtor/debt management
- SMS chatbot
- Basic payment processing
- Dashboard
Phase 2: Growth (Months 5-8)
Features:- WhatsApp integration
- Advanced analytics
- Payment plan AI
- Risk scoring
Phase 3: Scale (Months 9-12)
Features:- Voice IVR
- Mobile apps
- White-label
- Performance optimization
17. Glossary
AI/ML - Artificial Intelligence / Machine Learning API - Application Programming Interface FDCPA - Fair Debt Collection Practices Act TCPA - Telephone Consumer Protection Act JWT - JSON Web Token NLP - Natural Language Processing RBAC - Role-Based Access Control TLS - Transport Layer Security UUID - Universally Unique IdentifierEND OF DOCUMENT This comprehensive PRD provides junior developers with all the information needed to build funnelChat from scratch, including detailed technical specifications, database schemas, API endpoints, UI/UX requirements, and step-by-step implementation guidance.