# 🏦 IntentFX Microfinance ERP — Complete Features

> **পূর্ণাঙ্গ মাইক্রোফাইন্যান্স ম্যানেজমেন্ট সিস্টেম**  
> ERP + Mobile Apps (Customer + Field Officer) + AI Assistant + PWA

---

## 📑 Table of Contents

1. [System Architecture](#-system-architecture)
2. [Core Modules](#-core-modules)
3. [Mobile Apps](#-mobile-apps)
4. [Smart Features](#-smart-features)
5. [Security & Compliance](#-security--compliance)
6. [Technical Stack](#️-technical-stack)
7. [Screens & Views](#-screens--views)

---

## 🏗️ System Architecture

```
┌──────────────────────────────────────────────────────────────┐
│                    PWA Frontend (Browser)                     │
├──────────────────────────────────────────────────────────────┤
│                   PHP 8.x Backend (MVC)                      │
├──────────────────────────────────────────────────────────────┤
│                  MySQL Database (RDBMS)                       │
├──────────────────────────────────────────────────────────────┤
│      External APIs: Razorpay | OpenAI | Twilio | FCM         │
└──────────────────────────────────────────────────────────────┘
```

| Layer | Technology |
|-------|-----------|
| **Frontend** | HTML5, CSS3, JavaScript, Chart.js, Leaflet.js, DataTables |
| **Backend** | PHP 8.0+, Custom MVC Framework |
| **Database** | MySQL 8.0+ (InnoDB, UTF8MB4) |
| **Mobile** | PWA (Progressive Web App) — Installable on Android/iOS |
| **AI** | OpenAI GPT Integration |
| **Payments** | Razorpay Payment Gateway |
| **Maps** | Leaflet.js + OpenStreetMap / Google Maps |
| **Notifications** | Firebase Cloud Messaging (FCM), WhatsApp Cloud API |
| **Documents** | TCPDF, FPDI (PDF Generation) |

---

## 📦 Core Modules

### 1. 👥 Customer Management (`/customers`)

| Feature | Description |
|---------|-------------|
| **CRUD Operations** | Add, Edit, View, Search, Delete customers |
| **KYC Management** | Document upload (Aadhaar, PAN, Photo, Bank, Signature) |
| **Document Verification** | Verify/reject KYC documents with remarks |
| **Duplicate Detection** | Phone, Aadhaar, PAN duplicate check |
| **Bulk Import** | CSV import with template download |
| **Credit Check** | Real-time credit assessment dashboard |
| **Guarantor Management** | Add/remove guarantors with KYC |
| **Account Statement** | PDF statement generation |
| **Risk Scoring** | Automated risk assessment with AI |
| **PII Masking** | Automatic masking of Aadhaar/PAN/Phone (role-based) |

### 2. 💰 Loan Management (`/loans`)

| Feature | Description |
|---------|-------------|
| **Loan Origination** | Full lifecycle: Apply → Verify → Approve → Disburse |
| **Multi Scheme Support** | Multiple loan schemes with different rates/types |
| **Interest Types** | Flat Rate, Reducing Balance |
| **EMI Frequencies** | Daily, Weekly, Monthly, Quarterly, Half-Yearly, Yearly |
| **EMI Schedule** | Auto-generated amortization schedule |
| **Collection** | Collect EMI, Part Payment, Full Payment |
| **Foreclosure** | Early closure with interest rebate calculation |
| **Restructuring** | Extend tenure, reduce EMI (with restructure history) |
| **Interest/Penalty Waiver** | Waive interest, penalty, or custom amount |
| **Write-off** | Bad debt write-off with accounting entries |
| **One-Time Settlement (OTS)** | Settle loan at reduced amount |
| **Penalty Engine** | Auto-calculate late payment penalty (configurable grace days) |
| **Loan Origination System (LOS)** | Stage-based verification (document, field, business, reference) |
| **Maker-Checker** | 2-level approval system for high-value actions |
| **EMI Calculator** | Standalone tool for calculating EMIs (public) |
| **Payment Link** | Generate Razorpay payment links for online collection |
| **Agreement/Voucher PDF** | Loan agreement, disbursement voucher, NOC, overdue notice |
| **Regenerate EMI** | Fix loans with missing EMI schedules (super admin) |

### 3. 📊 Loan Schemes (`/schemes`)

| Feature | Description |
|---------|-------------|
| **Scheme Types** | Flat Rate, Reducing Balance, Custom |
| **Configurable** | Min/Max amount, tenure, interest rate, fees |
| **Charges** | Processing fee (%), GST (%), Insurance (%), Penalty (%) |
| **Branch-Specific** | Schemes can be restricted to specific branches |

### 4. 💳 Recurring Deposits — RD (`/rd`)

| Feature | Description |
|---------|-------------|
| **RD Account** | Open, manage, close RD accounts |
| **Installment Collection** | Daily collection with receipt |
| **Premature Closure** | Early closure with penalty calculation |
| **Maturity Calculator** | Interest calculation (compound/simple) |
| **Withdrawal** | Partial withdrawal facility |
| **Certificate** | RD maturity certificate PDF |
| **Receipts** | Individual installment receipts |
| **Daily Report** | Daily RD collection report |
| **RD Schemes** | Configurable interest rates, penalties |

### 5. 👥 Loan Groups (`/groups`)

| Feature | Description |
|---------|-------------|
| **Group Creation** | Create loan groups (SHG/JLG model) |
| **Member Management** | Add/remove members from groups |
| **Status Toggle** | Activate/deactivate groups |
| **Group Collections** | Collect EMIs for entire group at once |
| **Search** | Search customers to add to groups |

### 6. 🏢 Branch Management (`/branches`)

| Feature | Description |
|---------|-------------|
| **Multi-Branch** | Full multi-branch support |
| **Branch Config** | Name, code, address, contact, weekly off |
| **Status Toggle** | Activate/deactivate branches |
| **Branch Isolation** | Data isolation by branch (staff see only their branch) |

### 7. 👨‍💼 Staff Management (`/staff`)

| Feature | Description |
|---------|-------------|
| **Staff CRUD** | Add, Edit, View, Delete staff |
| **Role Assignment** | Assign roles with granular permissions |
| **Attendance** | Daily mark attendance with date range |
| **Attendance Report** | Monthly attendance summary |
| **Leave Management** | Apply, approve/reject leave requests |
| **Performance** | Staff performance metrics (collections, targets) |
| **Target Setting** | Set collection targets per staff |
| **Live Tracking** | GPS-based field staff tracking |
| **Staff Transfers** | Transfer staff between branches with PDF order |
| **Payroll** | Salary management, payslip generation |
| **Incentives** | Performance-based incentive calculation |
| **Appointment Letter** | PDF appointment letter generation |
| **ID Card** | Staff ID card PDF generation |

### 8. 💸 Collection Management (`/collections`)

| Feature | Description |
|---------|-------------|
| **Daily Collections** | Today's collection summary |
| **Map View** | Visual collection map (Leaflet.js) |
| **GPS Check-in** | Track collection location |
| **Filters** | By branch, staff, date range |
| **Receipts** | Print and WhatsApp receipts |

### 9. 📋 Receipts (`/receipt`)

| Feature | Description |
|---------|-------------|
| **Digital Receipt** | Auto-generated receipt numbers |
| **Print** | Print-friendly receipt format |
| **WhatsApp Share** | Send receipt via WhatsApp |
| **Multiple Methods** | Cash, Bank Transfer, Cheque, UPI, Online |

### 10. 📈 Reports (`/reports`)

| Feature | Description |
|---------|-------------|
| **EMI Daily** | Daily EMI collection report |
| **EMI Calendar** | Monthly calendar view of EMIs |
| **Loan Report** | Comprehensive loan portfolio report |
| **Due Report** | Upcoming EMI due list |
| **Collection Report** | Collection performance report |
| **Overdue Report** | Overdue loans tracker |
| **Branch Comparison** | Compare branches side-by-side |
| **Export** | Export reports to CSV/Excel |

### 11. 💹 Accounting (`/accounting`)

| Feature | Description |
|---------|-------------|
| **Cashbook** | Real-time cash flow tracking |
| **Expenses** | Expense management with categories |
| **Profit & Loss** | P&L statement generation |
| **Balance Sheet** | Balance sheet with configurable accounts |
| **Ledger** | General ledger view |
| **Trial Balance** | Trial balance report |
| **Journal Entries** | Manual journal entry with debit/credit |
| **Fund Management** | Multi-source fund tracking |
| **NPA Classification** | NPA (Non-Performing Asset) classification |
| **Financial Years** | Year-end closing process |

### 12. 🎯 Fund Management (`/fund`)

| Feature | Description |
|---------|-------------|
| **Fund Sources** | Add multiple fund sources (Bank, NBFC, Own) |
| **Deposit/Withdraw** | Track fund movements |
| **Transfer** | Transfer between fund accounts |
| **Allocation** | Allocate funds to branches |
| **History** | Complete fund transaction history |
| **Reports** | Fund utilization reports |

### 13. 🏛️ Roles & Permissions (`/roles`)

| Feature | Description |
|---------|-------------|
| **Role-Based Access** | Granular permission system |
| **50+ Permissions** | Create, View, Edit, Delete, Approve per module |
| **Super Admin** | Full system access |
| **Dynamic Permissions** | Permissions version tracking (auto-refresh) |
| **Route Guard** | Automatic permission check per route |

### 14. 📜 Audit Logs (`/audit-logs`)

| Feature | Description |
|---------|-------------|
| **Immutable Logs** | SHA-256 hash chain (tamper-proof) |
| **Full Tracking** | Who, What, When, IP, User Agent |
| **Old/New Data** | Before/after snapshots |
| **Chain Verification** | Audit integrity verification tool |
| **6-Month Retention** | Auto-cleanup for old logs |

### 15. ✅ Approvals (Maker-Checker) (`/approvals`)

| Feature | Description |
|---------|-------------|
| **2-Level Approval** | Maker submits, Checker approves |
| **Configurable** | Per-action type, threshold-based |
| **Pending Queue** | Dashboard with pending approval count |
| **Audit Trail** | Full approval history |
| **Supports** | Loan approve, disbursement, write-off, RD close |

### 16. 🛠️ Settings (`/settings`)

| Feature | Description |
|---------|-------------|
| **Dynamic Settings** | All config via UI (no code changes) |
| **App Branding** | Name, logo, brand customization |
| **Secret Encryption** | API keys stored encrypted (AES-256-GCM) |
| **Maintenance Mode** | Toggle system on/off for maintenance |
| **Backup** | Database backup with download |
| **Session Control** | Force logout all users |

### 17. 🤖 AI Assistant (`/ai`)

| Feature | Description |
|---------|-------------|
| **Chat Interface** | Natural language queries (OpenAI GPT) |
| **Data Analysis** | Ask questions about loans, customers, collections |
| **Forecasting** | Collection forecast with trend analysis |
| **Risk Analysis** | AI-powered loan risk assessment |
| **Actionable Insights** | "Show overdue loans", "How was this month?" |
| **Action Confirmation** | AI can execute actions after user confirmation |
| **Chat History** | Persistent conversation history |
| **Scan All** | Bulk AI risk scoring |

### 18. 🎯 AI Services

| Service | Features |
|---------|----------|
| **RiskEngine** | Multi-factor risk scoring (documents, repayment history, fraud detection) |
| **AIToolService** | Dashboard metrics, collection forecasts, disbursement trends |
| **AIActionService** | Natural language → System actions (summaries, alerts) |
| **WhatsAppAIService** | WhatsApp-based loan status, EMI due, overdue reminders |
| **LoanOriginationService** | Stage-based auto-approval workflow |
| **NpaService** | NPA classification rules engine |

### 19. 📱 PWA — Progressive Web App

| Feature | Description |
|---------|-------------|
| **Installable** | "Add to Home Screen" on Android/iOS |
| **Service Worker** | Offline support, caching |
| **Manifest** | Dynamic app manifest with branding |
| **Push Notifications** | FCM push notification support |

### 20. 🔗 External Integrations

| Integration | Purpose |
|-------------|---------|
| **Razorpay** | Payment gateway, webhook, payment links |
| **OpenAI (GPT)** | AI assistant, chat, risk analysis |
| **Firebase Cloud Messaging** | Push notifications |
| **WhatsApp Cloud API** | WhatsApp notifications, receipts, AI chat |
| **Twilio** | SMS and voice call notifications |
| **MSG91 / Fast2SMS** | SMS gateway |
| **Google Maps / OpenStreetMap** | Staff tracking, collection map |

### 21. 📱 Customer Mobile App (`/app/*`)

| Feature | Description |
|---------|-------------|
| **Login with PIN** | Customer self-service portal |
| **Dashboard** | Loan summary, next EMI, overdue count |
| **Loan View** | Active loans, EMI schedule, payment history |
| **Apply Loan** | Online loan application |
| **Online Payment** | Pay EMI via Razorpay (UPI, Card, NetBanking) |
| **RD Accounts** | View RD balance, pay installments |
| **Documents** | Upload KYC documents |
| **Notifications** | Push notifications for EMI due, approvals |
| **Support Tickets** | Raise support tickets |
| **Profile** | Update profile, change PIN |

### 22. 📱 Field Officer Mobile App (`/officer/*`)

| Feature | Description |
|---------|-------------|
| **Login** | Officer authentication |
| **Dashboard** | Today's collection target, performance |
| **Collections** | Collect EMI + RD on field |
| **Customer Search** | Search customers by name/phone/account |
| **GPS Tracking** | Auto GPS logging during field visits |
| **GPS Sync** | Sync offline GPS data |
| **Route Planning** | Optimized collection route |
| **Day Summary** | End-of-day collection summary |
| **Attendance** | Mark attendance with GPS |
| **Leaves** | Apply for leave from mobile |
| **Performance** | Personal collection performance |
| **Group Collections** | Collect group EMIs at meetings |
| **Payment Links** | Generate online payment links |
| **Customer Detail** | View customer loan/RD details |
| **Reminders** | Send payment reminders via WhatsApp |
| **Promise to Pay** | Record customer payment promises |
| **Add Leads** | Capture new customer leads in field |
| **RD Management** | Create RD accounts, collect RD installments |

---

## 🧠 Smart Features

### 🤖 AI-Powered Capabilities

- **Natural Language Queries**: "Show me overdue loans this month"
- **Predictive Forecasting**: Collection trends using historical data
- **Automated Risk Scoring**: Multi-factor customer risk assessment
- **Fraud Detection**: Pattern analysis for suspicious activity
- **Auto-Approval**: LOS stage-based automatic loan approval
- **Smart Chat**: Context-aware responses with action capabilities

### 🛡️ Security Features

| Feature | Description |
|---------|-------------|
| **AES-256-GCM Encryption** | Secret settings encrypted at rest |
| **SHA-256 Hash Chain** | Tamper-proof audit logs |
| **CSRF Protection** | Token-based cross-site request forgery protection |
| **SQL Injection Prevention** | All queries use prepared statements |
| **PII Masking** | Role-based Aadhaar/PAN/Phone masking |
| **Session Security** | HTTP-only, SameSite=Strict, Secure cookies |
| **CSP Headers** | Content-Security-Policy in .htaccess |
| **Rate Limiting** | Via web server configuration |
| **Force Logout** | Global session invalidation |
| **Input Validation** | Centralized Validator class with 20+ rules |

### 📊 Dashboard Widgets

- Total Active Loans & Outstanding Amount
- Today's Collection & Collection Rate
- Overdue Loans & Penalty Summary
- Branch-wise Performance Comparison
- Monthly Collection Chart (Current vs Previous)
- Portfolio at Risk (PAR) Indicators
- Staff Performance Rankings
- AI-Generated Insights & Alerts

---

## 📂 Views & UI Pages

### Admin Panel (50+ Pages)

| Module | Pages |
|--------|-------|
| **Auth** | Login, Forgot Password |
| **Dashboard** | Main dashboard with widgets, charts, stats |
| **Customers** | List, Create, Edit, Show, Import, Credit Check |
| **Loans** | List, Create, Show, EMI Schedule, Schemes |
| **RD** | List, Create, Show, Schemes, Daily Report |
| **Groups** | List, Create, Show |
| **Branches** | List/Manage |
| **Staff** | List, Create, Edit, Show, Attendance, Leaves, Tracking, Performance |
| **Payroll** | Salary, Payslip, Incentives |
| **Collections** | Daily, Map, History |
| **Receipts** | Show, Print |
| **Accounting** | Cashbook, Expenses, P&L, Balance Sheet, Ledger, Trial Balance, Journal, NPA |
| **Fund** | Accounts, Deposits, Withdrawals, History, Report |
| **Reports** | 7+ report types with export |
| **Roles** | List, Edit Permissions |
| **Audit** | Audit log viewer |
| **Approvals** | Pending queue, Approve/Reject |
| **Settings** | All system settings, Branding, Backup |
| **AI** | Chat interface, Analysis, Forecast |
| **Support** | Tickets, Leads |
| **Recovery** | Recovery cases, Demand Notice |
| **Collateral** | Collateral management |
| **Tracking** | Live map, Heatmap, Alerts |
| **Profile** | User profile, Password change |
| **License** | Developer dashboard, Logs |
| **Tools** | EMI Calculator |

### Customer App (15+ Pages)

| Page | Description |
|------|-------------|
| Login | PIN-based authentication |
| Dashboard | Loan summary, EMI status |
| My Loans | Active loans list with details |
| Apply Loan | Online application form |
| Payments | Payment history, online payment |
| My Documents | Upload/view KYC documents |
| RD Accounts | RD balance, installments |
| Notifications | Push notifications list |
| Support | Raise tickets |
| Profile | Update profile, change PIN |

### Field Officer App (20+ Pages)

| Page | Description |
|------|-------------|
| Login | Officer authentication |
| Dashboard | Collection targets, performance |
| Collections | Todays collection list |
| EMI Collect | Collect EMIs on field |
| EMI Paid | Already paid EMIs |
| EMI Overdue | Overdue EMIs |
| Search | Search customers |
| Customer Detail | Full customer view |
| Route | Collection route planning |
| Day Summary | End-of-day report |
| Attendance | Mark attendance (GPS) |
| Leaves | Apply for leave |
| GPS Sync | Sync offline GPS data |
| Group Collections | Group meeting collections |
| RD Management | Create/collect RD |
| Performance | Personal stats |
| Notifications | App notifications |
| Profile | Password change |

---

## ⚙️ Technical Details

### Database
- **Engine**: MySQL 8.0+ InnoDB
- **Encoding**: utf8mb4 (full Unicode support)
- **Tables**: 70+ tables covering all modules
- **Relations**: Proper foreign keys with indexes

### PHP Framework (Custom MVC)
- **Router**: Regex-based with parameterized routes
- **Database**: Singleton PDO with prepared statements
- **Validation**: Centralized Validator with 20+ rules
- **Caching**: Dual-layer (memory + file) Cache service
- **Logging**: Structured PSR-3-style Logger
- **Environment**: Proper .env loader with `vlucas/phpdotenv` support
- **Autoloading**: PSR-4 autoloader with legacy class fallback

### Services Layer (20+ Services)

| Service | Purpose |
|---------|---------|
| EMICalculator | Loan EMI, schedule, penalty, charges |
| RiskEngine | Customer risk scoring, fraud detection |
| PaymentService | Razorpay payment gateway |
| NotificationService | In-app, push, SMS notifications |
| PushService | FCM push notifications |
| WhatsAppAIService | WhatsApp chatbot + notifications |
| PdfService | PDF generation (TCPDF) |
| OcrService | Document OCR processing |
| ApprovalService | Maker-checker workflow |
| RollbackService | Transaction rollback with audit |
| DeleteService | Secure deletion with verification |
| RDService | Recurring deposit operations |
| NpaService | NPA classification |
| FundService | Fund management operations |
| LoanOriginationService | Stage-based loan processing |
| AttendanceService | Staff attendance operations |
| ExternalApiService | Third-party API integrations |
| BusinessRuleEngine | Business rule validation |
| NbfcService | NBFC compliance features |
| VoiceCallService | Voice call notifications |
| AIToolService | AI analytics & forecasting |
| AIActionService | AI action execution |

---

## 📊 Database Schema (70+ Tables)

```
Core:           settings, users, roles, permissions, branches
Customers:      customers, guarantors, documents, customer_groups
Loans:          loans, loan_schemes, loan_types, emi_schedule
Collections:    collections, receipts, payment_requests
RD:             rd_schemes, rd_accounts, rd_schedule, rd_collections
Accounting:     cashbook, expenses, expense_categories, fund_accounts
                journal_entries, financial_years
Staff:          staff_attendance, staff_locations, leaves, payroll
                staff_targets, staff_transfers
Security:       audit_logs, approval_requests, transaction_rollbacks
AI:             ai_risk_scores, ai_chat_history, npa_classification
Support:        support_tickets, support_leads
Tracking:       tracking_alerts, recovery_cases, collateral
Notifications:  notifications, fcm_tokens, message_log
                whatsapp_chat_history
Others:         loan_writeoffs, loan_verifications, customer_devices
                phonepe_payouts, bulk_sms_logs, api_logs
```

---

## 🚀 Quick Stats

| Metric | Count |
|--------|-------|
| **Controllers** | 30+ |
| **Services** | 20+ |
| **Views** | 100+ |
| **Routes** | 200+ |
| **Database Tables** | 70+ |
| **Unit Tests** | 47 (PHPUnit) |
| **Permissions** | 50+ granular |
| **Mobile Apps** | 2 (Customer + Officer) |
| **External Integrations** | 8+ |

---

> **Built with** ❤️ using PHP 8.x, MySQL, JavaScript, and modern web technologies.
