# IntentFX Microfinance ERP — Complete Feature Presentation

> **Stack:** PHP 8 · MySQL · Vanilla JS · Leaflet.js · OpenAI GPT · Razorpay · Twilio · Firebase FCM  
> **Architecture:** Multi-branch · Role-based access · Double-entry accounting · PWA-ready

---

## Table of Contents

1. [System Overview](#1-system-overview)
2. [Authentication & Security](#2-authentication--security)
3. [Smart Dashboard](#3-smart-dashboard)
4. [Customer Management](#4-customer-management)
5. [Loan Management](#5-loan-management)
6. [Loan Origination System (LOS)](#6-loan-origination-system-los)
7. [EMI & Collections](#7-emi--collections)
8. [Recurring Deposits (RD)](#8-recurring-deposits-rd)
9. [Staff Management & Payroll](#9-staff-management--payroll)
10. [Field Officer Mobile App](#10-field-officer-mobile-app)
11. [Customer Mobile App](#11-customer-mobile-app)
12. [Live GPS Tracking](#12-live-gps-tracking)
13. [AI Assistant & Risk Engine](#13-ai-assistant--risk-engine)
14. [WhatsApp AI Bot](#14-whatsapp-ai-bot)
15. [Accounting & Finance](#15-accounting--finance)
16. [NPA / IRAC Compliance](#16-npa--irac-compliance)
17. [Reports & Analytics](#17-reports--analytics)
18. [Recovery & Legal](#18-recovery--legal)
19. [Collateral Management](#19-collateral-management)
20. [Group Lending](#20-group-lending)
21. [Approval Workflow (Maker-Checker)](#21-approval-workflow-maker-checker)
22. [Notifications & Bulk Messaging](#22-notifications--bulk-messaging)
23. [Documents & PDF Generation](#23-documents--pdf-generation)
24. [Settings & Administration](#24-settings--administration)
25. [Integrations & Webhooks](#25-integrations--webhooks)
26. [Architecture & Security](#26-architecture--security)

---

## 1. System Overview

IntentFX is a **full-stack microfinance ERP** built for NBFCs, MFIs, and cooperative societies. It covers the complete loan lifecycle — from lead capture and KYC verification to loan disbursement, EMI collection, recovery, and accounting — with AI-powered risk scoring and a built-in WhatsApp chatbot.

### Three User Zones

| Zone | URL Prefix | Users |
|------|-----------|-------|
| Admin ERP | `/` | Branch managers, accountants, super admin |
| Field Officer App | `/officer/` | Field collection staff (mobile WebView) |
| Customer App | `/app/` | Borrowers (mobile WebView) |

### Key Numbers (features at a glance)

- **34 controllers**, **22 services**, **200+ routes**
- **26 major feature modules**
- **19 AI read-tools** + **3 AI action-tools** (with human confirmation gate)
- **7 PDF document types**
- **3-language AI** (English / Hindi / Bengali)

---

## 2. Authentication & Security

### Admin Login
- Phone + password authentication
- Brute-force lockout: 5 failed attempts → 15-minute lockout per IP+phone
- Session regeneration on login
- Last login timestamp and IP stored per user

### Role-Based Access Control (RBAC)
- Granular permission matrix per role (30+ permissions across 12+ modules)
- `super_admin` holds all permissions automatically
- Live permission sync — if an admin edits a role's permissions, the affected user's session is refreshed on the **very next request** (no logout needed) via `perm_version`
- Route-to-permission mapping covers all sensitive routes
- 403 page with JSON fallback for AJAX requests

### Session Security
- `session_salt` force-logout mechanism — changing the salt logs out all sessions instantly
- `HTTPS`-aware secure cookies with `SameSite: Strict`
- CSRF tokens on all state-changing forms

### Audit Trail
- Every create / update / delete / approve operation is logged to `audit_logs`
- **Tamper-evident hash chain**: each entry includes the SHA-256 hash of the previous entry
- Hash chain can be verified at any time to detect tampering

---

## 3. Smart Dashboard

A real-time command center with live stats, charts, and alerts.

### Summary Cards
- Total customers, active/overdue/pending/closed loans
- Total disbursed, collected, outstanding, total payable
- **Recovery %** = collected / total payable × 100
- Today's collection (count + amount), today's due count & amount
- RD collections today, new customers this month, new loans this month

### Live Sections
| Section | What it shows |
|---------|--------------|
| **Recent Collections** | Last 10 EMI collections with customer, loan, collector |
| **Pending Approvals** | Loans awaiting approval (top 5) |
| **Overdue Alerts** | Top 5 loans by overdue EMI count |
| **Branch Comparison** | All branches — customers, active loans, today's collection, outstanding (super admin) |
| **Top Collectors Today** | Staff ranked by today's collection |
| **Live GPS Map** | All staff on-route with last seen time |
| **Defaulter List** | Customers with 2+ overdue EMIs, sorted by days overdue |
| **Risk Customers** | Customers with overdue EMIs + total outstanding |

### AJAX Chart Data
- 30-day collection trend (line chart)
- Loan status distribution (pie/donut)
- Monthly collection vs disbursement (6-month bar)
- EMI frequency breakdown (active loans)

---

## 4. Customer Management

### Profile
Full customer profile with:
- Personal: name, phone, DOB, gender, address, GPS coordinates
- Family: guardian name, nominee name + phone + relation
- Financial: monthly income, occupation, CIBIL score
- Banking: bank name, account number, IFSC code
- KYC: Aadhaar, PAN, voter ID (stored with PII masking — only users with `customers.kyc` permission see full values)

### Features
- **AJAX duplicate detection** — checks phone, Aadhaar, PAN in real-time before save
- **Bulk CSV import** — with downloadable template; skips duplicates
- **KYC Document Management** — upload, verify, delete documents; auto-OCR extracts Aadhaar/PAN numbers from scanned images
- **Guarantor management** — add/delete guarantors with photo
- **External credit check** — connects to CIBIL/bureau API and saves score
- **Customer Statement PDF** — loans, payments, RD accounts, all in one document
- Activate / deactivate customer
- Delete with security code (checks for active loans)

---

## 5. Loan Management

### Loan Lifecycle

```
Lead → Application → LOS Verification → Approved → Disbursed → Active → Closed
                                                                ↓
                                                          Overdue → Recovery
```

### Create Loan
- Select customer, scheme, amount, tenure, branch, assigned officer
- **Auto EMI calculation**:
  - Flat rate: fixed interest on original principal
  - Reducing balance: interest on outstanding principal
  - Frequencies: daily, weekly, biweekly, monthly
- Auto-compute: processing fee, insurance, GST, net disbursed amount
- **Dynamic loan number**: `{TypeCode}{BranchShort2}{DDMMYY}{seq4}` (e.g., `FLJA0806260001`)

### Loan Actions

| Action | Description |
|--------|-------------|
| **Approve** | Set first EMI date, generate EMI schedule (respects branch weekly-off) |
| **Disburse** | Activate loan, set disbursement mode (cash/bank/cheque/UPI) + ref, auto cashbook debit |
| **Collect EMI** | Record payment → update EMI status → update loan totals → cashbook credit |
| **Part Payment** | Accept any amount → auto-distribute across pending EMIs |
| **Foreclosure** | Calculate unearned interest rebate + foreclosure fee → settle remaining principal |
| **Restructure** | Extend tenure, recalculate EMI, generate new schedule from today |
| **Waive Interest** | Waive interest / penalty / both / custom amount |
| **Write-Off** | Mark as bad debt, record in `loan_writeoffs`, cashbook memo debit |
| **Settlement (OTS)** | Customer pays agreed amount, rest waived, loan closed |
| **Reject** | Reject pending loan with reason |
| **Apply Penalty** | Auto-calculate penalty by overdue days × penalty_pct / 30 (with grace days) |
| **Rollback Collection** | Reverse a collection with reason (security code required) |
| **Delete Loan / Collection** | Security code required; full audit trail maintained |

### Loan Schemes
- Unlimited schemes per loan type, optionally branch-scoped
- Configurable: interest rate, interest type, amount range, tenure range, EMI frequency, processing fee %, GST %, insurance %, penalty %

---

## 6. Loan Origination System (LOS)

A configurable multi-stage verification workflow before loan approval.

### Workflow Stages (fully configurable)
```
Application → Field Visit → Document Check → Credit Check → Committee → Approve
```

### Features
- Stages configured as a comma-separated list in Settings (`los_stages`)
- Each stage: pass / fail / waive + optional score (0–100) + remarks
- Automatically advances `workflow_stage` on each pass
- Saves `field_visit_date`, `credit_check_date`, `credit_score` on relevant stages
- **Overall verification score** = average of all stage scores
- **Auto-approve gate**: amount < threshold + all stages passed + score ≥ minimum (all configurable)
- LOS can be enabled/disabled globally

---

## 7. EMI & Collections

### EMI Schedule
- Generated at approval or at disbursal
- Branch weekly-off respected (skips EMI due dates that fall on the branch's off day)
- Full amortization: principal, interest, balance per installment

### Collection Entry (Admin)
- Select EMI, enter amount, choose payment method (cash/UPI/bank/cheque/online)
- Auto-updates: EMI status, loan totals, outstanding, loan closure on full payment
- Auto cashbook credit entry
- Receipt number auto-generated

### Collection Views
- Paginated full collection list with date/branch/staff filters
- **Daily Collection Sheet**: all due vs completed for any date
- **GPS Collection Map**: Leaflet.js map with customer pins (due/collected/pending badges)

---

## 8. Recurring Deposits (RD)

### RD Schemes
- Interest rate, tenure range, premature closure penalty
- Daily / weekly / monthly frequency support

### RD Account
- Open for customer, assign scheme, set installment amount + tenure + start date + nominee
- Auto-generate installment schedule with due dates

### RD Operations

| Action | Description |
|--------|-------------|
| **Collect Installment** | Record deposit → update schedule → update totals + interest earned |
| **Partial Withdrawal** | Withdraw from account balance |
| **Close Account** | Maturity or premature (with penalty calculation) |
| **Delete Account / Collection** | Security code required |

### RD Documents
- **RD Certificate PDF** — for matured/closed accounts
- **Collection Receipt PDF**

### RD Reports
- Daily RD collection dashboard (cash vs online, per-staff, per-customer)
- RD collection report (CSV/PDF export)

---

## 9. Staff Management & Payroll

### Staff Profile
- Employee ID (auto or manual), role, branch, photo, joining date, designation, contact, address

### Attendance
- Admin marks attendance with status: present / half_day / absent / leave / late
- **Auto-calculation**:
  - Late minutes from check-in time
  - Working seconds / overtime seconds from check-in + check-out
- Monthly attendance report: present/half/absent/leave/late, working hours, overtime per staff

### Performance Tracking
- Monthly collection target setting per staff
- Performance dashboard: target vs achieved, achievement %, daily trend
- Branch ranking

### Leave Management
- Staff applies for leave (casual/sick/earned/other)
- Admin approves or rejects with notes

### Payroll
- **Individual payslip generation**:
  - Earned salary = base × (payable days / working days in month)
  - Incentive = collection total × incentive_%
  - Overtime pay
  - Bonus (manual)
  - Late deduction
- **Bulk payslip generation** for all staff in one click (skips already-paid)
- Mark paid → auto cashbook debit (salary expense)
- Printable payslip

### Staff Incentive Tiers
- Configurable rules: if achievement ≥ X% of target → incentive at Y% of collections
- Multiple tiers (e.g., 100%+ → 3%, 80–99% → 2%, 60–79% → 1%)
- Incentive calculation and save per staff per month

### Staff Documents
- **Appointment Letter PDF**
- **Staff ID Card** (printable HTML page)
- **Transfer Order PDF**

---

## 10. Field Officer Mobile App

A full-featured mobile WebView app for field collection staff.

### Dashboard
- Daily target, collected today/month, pending/overdue customers, due amount
- Attendance status (checked in / out), today's collection list with timing badges

### EMI Collection
- Today's EMI list (by branch)
- **Inline collection form** per customer — no page navigation needed
- **Duplicate protection**: same loan + officer + amount within 60 seconds → blocked
- Payment method (cash / UPI / bank / cheque)
- Auto GPS check-in on collection

### Customer Features
- Customer list with filters: due / overdue / paid today / all EMI
- Customer detail: loans, pending EMIs, recent payments
- AJAX customer search
- **New lead capture from field**: photo, Aadhaar photo, PAN photo, GPS coordinates

### GPS & Attendance
- Continuous GPS pings with battery %, network type, speed, **mock-GPS detection**
- **Offline sync**: GPS points queued locally and bulk-uploaded when internet returns
- Check-in/check-out with selfie + GPS, auto late-minutes and working-hours calculation

### Communication
- Send SMS/WhatsApp payment reminder directly from the field
- **Promise-to-Pay (PTP)** recording with date and amount

### Route Planning
- Route map: today's due customers sorted by due amount, with visit status
- Day summary: cash / online / total reconciliation

### RD (Field)
- RD due list (unseen by today's collector only)
- Collect installment (single or bulk), with backdate support
- Open new RD account
- Generate Razorpay payment link for RD
- RD collection history

### Group Collections
- Group list with total due
- Group EMI list: all members' due/overdue EMIs in one view
- Collect per-EMI from group screen

### Performance
- Monthly target vs collected, daily trend chart, branch rank

---

## 11. Customer Mobile App

A self-service WebView portal for borrowers.

### Authentication
- Phone + 4-6 digit PIN
- Brute-force protection (5 attempts → 15-min lockout)
- First login forces PIN change (default PIN = last 4 of phone, which must be changed)

### Features

| Section | What the customer can do |
|---------|--------------------------|
| **Dashboard** | See total loan, outstanding, next EMI, total paid |
| **My Loans** | List of all loans with status and scheme |
| **Loan Detail** | Full EMI schedule with status |
| **Apply for Loan** | Submit loan application with amount, scheme, purpose |
| **Online Payment** | Pay EMI via Razorpay payment link |
| **Payment History** | Last 100 loan collections |
| **Documents** | View and self-upload KYC documents (verified by staff) |
| **RD Accounts** | View RD list, schedule, payment history |
| **RD Payment** | Pay RD installment online via Razorpay |
| **Notifications** | In-app notification inbox |
| **Support** | Submit complaint tickets, see officer and branch contact |
| **Profile** | View profile, change PIN |

---

## 12. Live GPS Tracking

A real-time field intelligence module for admin.

### Staff Map
- Full-screen Leaflet.js map showing all active staff
- Color-coded: online (seen in last 10 minutes) vs offline
- Per-staff: last seen, battery %, network type, mock GPS warning

### Officer Detail View
- Full GPS route path for any day (polyline)
- Customer visit pins with name + address
- Collection pins with amount
- Telemetry panel: battery, network, mock GPS, GPS status
- Distance traveled (km) computed via Haversine formula

### Heatmap
- Aggregated density map: all GPS points / collections / customer visits
- Filter by date and type

### Smart Alert Engine (runs via cron)
Alert type | Trigger
-----------|--------
`gps_off` | No ping for 30+ minutes during working hours
`mock_gps` | Fake GPS app detected
`low_battery` | Battery ≤ 15%
`no_movement` | < 100m movement in 2 hours
`route_deviation` | Outside all branch geo-fences
`missed_visit` | Past noon, has due customers, no visits/collections

- Alerts are deduplicated (one per type per staff per day)
- Admin can resolve alerts
- Alert count shown on dashboard

---

## 13. AI Assistant & Risk Engine

### AI Risk Scoring (Rule-Based, no API key needed)

**7-factor risk score (0–100)**:

| Factor | Weight | Positive | Negative |
|--------|--------|----------|---------|
| KYC Status | 15 | Verified | Rejected |
| Document Completeness | 10 | 3+ docs | 0 docs |
| Income/EMI Burden | 20 | <30% | >50% |
| Repayment History | 25 | 0 late, 5+ paid | >30% overdue |
| Active Loan Count | 15 | 0 | 4+ loans |
| Account Age | 10 | >1 year | <90 days |
| Guarantor | 5 | Has one | None |

- **Trust score** = 100 − risk score
- **Fraud probability**: duplicate phone/Aadhaar, zero docs, 5+ overdue EMIs, 3+ active loans
- **Approval suggestion**: approve (≤25) / review (≤50) / reject (>50)
- **Max safe loan amount**: income × multiplier based on risk band

### Business Rule Engine (BRE)
- Configurable JSON rules in Settings
- Auto-reject: 3+ active loans, existing overdue, KYC unverified, amount > 5× income
- Flag for review: high-value loan, age <21 or >60, low income
- Auto-approve: small loans (≤₹25K), good repayment history
- Returns decision + reasons + score

### Predictive Analytics
- **Defaulter prediction**: ranks active loans by overdue EMIs + risk score + outstanding
- **30-day cash flow forecast**: expected daily collections from EMI schedule, adjusted by historical collection rate
- **Collector fraud detection**: late-hour patterns, duplicate same-day collections, micro-amount patterns

### AI Chat Assistant (with OpenAI GPT)

```
User Question
    ↓
Intent detection (defaulters / loan info / monthly stats / etc.)
    ↓
If OpenAI enabled:
  → Tool-calling loop (up to 4 rounds of live DB queries)
  → Action tool → Preview → User confirms → Execute
Else:
  → Built-in rule engine with grounded DB facts
    ↓
Save to chat history (per user)
    ↓
Reply in user's language (EN / HI / BN)
```

**19 Read Tools** (AI can call any combination):
`get_overview`, `get_financial_stats`, `find_loan`, `list_defaulters`, `list_top_collectors`, `list_schemes`, `list_branches`, `get_customer_stats`, `get_loan_stats`, `get_overdue_summary`, `get_rd_stats`, `get_rd_collections`, `get_npa_summary`, `get_recovery_status`, `get_collateral_summary`, `get_staff_incentives`, `get_branch_comparison`, `get_pending_approvals`, `get_loan_verification_status`

**3 Action Tools** (human confirmation required):
- `send_payment_reminder` — SMS or WhatsApp to customer
- `create_payment_link` — Razorpay link, optionally send via SMS/WhatsApp
- `make_voice_reminder` — Twilio text-to-speech call

---

## 14. WhatsApp AI Bot

An inbound WhatsApp chatbot for customers.

### How it works
1. Customer messages company's WhatsApp number
2. System identifies customer by phone (last 10 digits)
3. Builds live context: active loans, next EMI, overdue count, last payment, RD accounts
4. Detects language: Bengali Unicode / Hindi Devanagari / Bengali romanised / English
5. If OpenAI enabled → GPT reply grounded in real data (6-turn memory)
6. Else → rule-based shortcuts

### Quick Keyword Commands

| Keyword | Response |
|---------|---------|
| `DUE` / `EMI` / `কিস্তি` | Next EMI number, amount, due date, overdue count |
| `BALANCE` / `বকেয়া` | Loan amount, paid, outstanding |
| `PAID` / `পেমেন্ট` | Last payment date, amount, receipt no |
| `RD` / `আরডি` | RD account, installment, deposited, maturity |
| `SCHEDULE` / `তালিকা` | Next 5 EMIs with status icons |
| `HELP` / `হ্যালো` | Full command menu in customer's language |

### Multilingual Support
- Full Bengali (Unicode বাংলা) support
- Hindi (Devanagari)
- English
- Auto-detects script and responds in the same language

---

## 15. Accounting & Finance

### Cashbook
- Manual credit / debit entries with category and reference
- **Auto-entries** created automatically on:
  - Loan disbursement → debit
  - EMI collection → credit
  - Expense recorded → debit
  - Salary paid → debit
  - Write-off → memo debit

### Expenses
- Category-based expense tracking
- Receipt file upload (photo/PDF)
- Category-wise summary and breakdown

### Profit & Loss
- Income: interest collections + processing fees + penalty income
- Expenses: all expense categories
- Net profit = income − expenses
- Filter by date range and branch

### General Ledger
- Chronological entries with running balance
- Opening balance computed from all prior transactions

### Balance Sheet
- Assets: loans outstanding + cash in hand (from cashbook net)
- Liabilities & equity: capital deployed + retained earnings (collections − expenses)

### Trial Balance (Double-Entry)
- Verifies debits = credits across all accounts
- `chart_of_accounts` + `journal_entries` + `journal_lines` tables
- Balanced indicator shown

### Journal (Double-Entry)
- View journal entries with account code, name, debit, credit per line

### Financial Year Management
- Create, manage, and **close** financial years
- Closing computes net profit = income − expenses for the year
- Closed years locked from further edits

---

## 16. NPA / IRAC Compliance

Full RBI IRAC norms implementation for asset classification.

### Asset Classification (by DPD)

| Class | DPD Range | Provision Rate |
|-------|-----------|---------------|
| Standard | 0 DPD | 0.40% |
| SMA-0 | 1–30 DPD | 0.40% |
| SMA-1 | 31–60 DPD | 0.40% |
| SMA-2 | 61–90 DPD | 0.40% |
| NPA Sub-standard | 91–365 DPD | 15% |
| NPA Doubtful (1yr) | 366–730 DPD | 25% |
| NPA Doubtful (2yr) | 731–1095 DPD | 40% |
| Loss | 1095+ DPD | 100% |

### Features
- **On-demand batch reclassification**: recalculates DPD, asset class, NPA date, provision % and provision ₹ for all active loans
- **GNPA %** = NPA outstanding / total outstanding × 100
- Loan-level NPA detail report with customer, branch, staff, DPD, provision
- NPA summary on accounting dashboard

---

## 17. Reports & Analytics

### Available Reports

| Report | Filters | Export |
|--------|---------|--------|
| Due Report | Date | CSV, PDF |
| Collection Report | Date range, daily summary | CSV, PDF |
| Overdue Report | Branch | CSV, PDF |
| EMI Daily Report | Date range, staff, branch, status | View, CSV |
| EMI Calendar | Month | View |
| Branch Comparison | Date range | View |
| Loan Report | Status, branch, staff, scheme, date, amount range | CSV, Excel, PDF |
| Customer List | — | CSV |

### EMI Daily Report Highlights
- Timing badge: **Perfect** (paid on due date) / **Advance** (paid early) / **Late** (paid after due date)
- Summary: total due, total paid, paid amount vs due amount

### EMI Calendar
- Visual month grid
- Each day shows due / paid / overdue counts with color coding

### Export Formats
- **CSV** (UTF-8 BOM for correct Excel encoding)
- **Excel** (.xls, SpreadsheetML format, styled header row)
- **PDF** (branded table via TCPDF/FPDF, landscape for wide reports)

---

## 18. Recovery & Legal

### Recovery Workflow

```
Overdue Loan
    ↓
reminder_call → demand_notice → legal_notice → arbitration / lok_adalat / sarfaesi
                                                        ↓
                                              write_off / settlement
```

### Features
- Initiate recovery action with type, priority (critical/high/medium/low), assigned officer, remarks
- Status tracking: initiated → sent → acknowledged → escalated → resolved
- **Demand Notice PDF** auto-generated with loan details, overdue amount, DPD, 15-day deadline, company letterhead
- Marks action as `sent` on PDF generation
- Recovery dashboard with stats (total / initiated / sent / escalated / resolved / total due)

---

## 19. Collateral Management

### Supported Types

| Type | Specific Fields |
|------|----------------|
| **Gold** | Weight (grams), purity (18K/22K/24K), rate/gram → auto market value |
| **Property** | Address, area (sq ft), type (land/house/commercial) |
| **Vehicle** | Registration no, make, model, year |

### Features
- Auto LTV calculation: pledged value = market value × LTV%
- Portfolio stats: total, pledged, total market value, total pledged value, type breakdown
- Release collateral on loan closure
- Linked to loan and customer

---

## 20. Group Lending

### Group Management
- Create groups with unique code, leader name + phone, meeting day
- Add/remove members (prevents multiple group memberships)
- Activate/deactivate groups

### Group Collection
- Group EMI list: all members' due/overdue/partial EMIs in one view, sorted by urgency
- Collect per-EMI from group screen
- Total due, overdue count, due count shown at group level

---

## 21. Approval Workflow (Maker-Checker)

A 2-level authorization system for high-value or sensitive operations.

### Supported Actions
- `loan_approve` — triggered when loan amount exceeds configured threshold
- `loan_disburse`
- `loan_writeoff`
- `rd_close`

### Workflow
1. **Maker** initiates action → system creates approval request (not executed yet)
2. **Checker** reviews request → approve or reject with note
3. On approval → action executes (EMI schedule generated, loan activated, etc.)
4. Staff cannot approve their own requests

### Dashboard
- Pending requests list with requester, action type, loan reference, created time
- Full history with status

---

## 22. Notifications & Bulk Messaging

### In-App Notifications
- Notification inbox with unread count badge
- Mark single / all as read
- Unread count AJAX endpoint (for live badge update)

### Bulk Messaging
- **Audience targeting**: overdue customers / due today / all active loans
- **Message templates** with `{name}`, `{loan_no}`, `{amount}` placeholders
- **Channels**: SMS only / WhatsApp only / Both
- Results summary: sent, failed, skipped

### Push Notifications (FCM)
- FCM push notification test from settings
- Device token registration from mobile apps
- Webhook handler auto-confirms Razorpay payment → pushes notification to customer

---

## 23. Documents & PDF Generation

All PDFs are branded with the company logo and address from Settings.

| Document | Who for | Content |
|----------|---------|---------|
| **Loan Agreement** | Customer | Full legal agreement with lender info, borrower info, loan terms, default clauses, signature blocks, guarantor field |
| **Disbursement Voucher** | Customer | Amount breakdown (disbursed − fees), mode, reference, acknowledgement |
| **NOC** | Customer | No-dues certificate for closed/settled loans |
| **Overdue Notice** | Customer | Table of overdue EMIs with days late, total due, recovery warning |
| **EMI Schedule** | Customer | Full amortization table (principal, interest, balance, status) |
| **Customer Statement** | Customer | Loans, RD accounts, last 100 payments |
| **Demand Notice** | Legal | Formal demand notice for recovery action |
| **Staff ID Card** | Staff | Printable HTML card |
| **Appointment Letter** | Staff | Formal appointment with terms and conditions |
| **Payslip** | Staff | Salary breakdown (base, incentive, deduction, net) |
| **Transfer Order** | Staff | Branch transfer letter |

---

## 24. Settings & Administration

### App Branding
- App name, brand name (used in SMS/WhatsApp messages)
- Logo upload (shown in header, PDFs, emails)
- Company address, phone, email, registration number

### Integrations

| Integration | Settings |
|-------------|---------|
| **Razorpay** | Key ID + Secret (encrypted) |
| **OpenAI GPT** | API key (encrypted), model selection |
| **SMS Gateway** | API key (encrypted), provider config |
| **WhatsApp Cloud API** | Token (encrypted), Phone number ID, verify token |
| **Twilio Voice** | Account SID, Auth Token (encrypted), From number |
| **Firebase FCM** | Server key (encrypted) |

All secret values are **AES-256-GCM encrypted** at rest in the database. The UI masks them as `enc:****`.

### Loan Configuration
- Penalty grace days
- LOS: enable/disable, workflow stages, auto-approve threshold, minimum score
- BRE: custom rule JSON editor
- Incentive tier rules

### System Administration
- System info: PHP version, MySQL version, DB size, table record counts
- **Database backup** — download full SQL backup
- Maintenance mode — shows maintenance page to all users
- Force logout all users — changes session salt
- DB optimize (ANALYZE/OPTIMIZE tables)
- Log viewer
- Developer impersonation (developer login zone)
- Factory reset (developer only)
- License management

---

## 25. Integrations & Webhooks

### Razorpay
- Create payment links (for EMI and RD)
- **Webhook**: HMAC-verified → auto-confirm payment → allocate to EMI/RD → cashbook entry → push notification to customer

### WhatsApp Cloud API
- **Webhook verify** (GET — token challenge)
- **Inbound message** (POST — routes to WhatsApp AI service)

### Twilio
- **Voice call**: text-to-speech payment reminder placed from AI assistant

### Firebase FCM
- Device token registration from both mobile apps
- Push notification on payment confirmation

### PWA (Progressive Web App)
- Dynamic `/manifest` endpoint (reads app name + logo from settings)
- Service worker (`/sw.js`) for offline support
- Both mobile apps installable as PWA

---

## 26. Architecture & Security

### Multi-Branch Architecture
- Every query is scoped to the user's branch if not super_admin
- Super admin sees all branches
- Branch code embedded in loan numbers

### EMI Calculation Engine (`EMICalculator`)
- Flat rate: `(principal × rate × tenure) / tenure_months`
- Reducing balance: standard reducing balance formula per frequency
- All frequencies: daily, weekly, biweekly, monthly
- Branch weekly-off respected in date generation (skips off days)

### Security Patterns
- All DB queries use parameterized statements (no SQL injection)
- CSRF token on every state-changing form
- Security code required for destructive operations (delete loan, delete collection, rollback)
- File uploads: extension + MIME type validation + 5MB limit + GD image compression (max 1200px, 75% quality)
- PII masking: Aadhaar/PAN/phone shown masked unless user has `customers.kyc` permission

### Auto-Cashbook Integration
Every financial event auto-creates a cashbook entry:
- Loan disbursed → debit (disbursement)
- EMI collected → credit (emi_collection)
- Expense added → debit (expense)
- Salary paid → debit (salary)
- Write-off → memo debit (bad_debt)
- Settlement → credit (settlement)

### Cron Jobs
- `/cron/run` — daily automated tasks (EMI status updates, NPA reclassification, GPS alert scan, backup)
- `/cron/daily` — automated database backup

---

## Quick Reference — URL Map

```
/                          Dashboard
/customers                 Customer management
/loans                     Loan management
/rd                        Recurring deposits
/collections               Collection management
/staff                     Staff management
/payroll                   Payroll
/groups                    Group lending
/reports                   All reports
/accounting/cashbook       Cashbook
/accounting/expenses       Expenses
/accounting/profit-loss    P&L
/accounting/ledger         General ledger
/accounting/balance-sheet  Balance sheet
/accounting/npa            NPA / IRAC
/accounting/trial-balance  Trial balance
/accounting/journal        Journal entries
/ai                        AI risk dashboard & chat
/tracking                  Live GPS tracking
/recovery                  Recovery & legal
/collateral                Collateral
/approvals                 Maker-checker queue
/notifications             Notifications
/audit-logs                Audit trail
/roles                     Role & permission management
/branches                  Branch management
/settings                  System settings

/app/*                     Customer mobile app
/officer/*                 Field officer mobile app
```

---

*Document generated from codebase scan — June 2026*
