# CYDM Microfinance System - Comprehensive Features Specification

## Project Overview

**CYDM** (Community Youth Development Microfinance) is a multi-tenant SaaS platform that provides a complete microfinance management system for small microfinance institutions (MFIs), SACCOS, and community microfinance groups in Tanzania. Each member institution gets a customized subdomain (e.g., `mfi1.cydm.co.tz`, `saccos2.cydm.co.tz`) with their own branding, while sharing a single codebase and infrastructure.

---

## 1. Multi-Tenancy & Subdomain Architecture

### 1.1 Core Multi-Tenancy Features
- **Subdomain-based routing**: Each tenant accesses via `tenant-slug.cydm.co.tz`
- **Custom domain support**: Tenants can map their own domain (e.g., `mfi1.co.tz` → CNAME to platform)
- **Automated tenant provisioning**: Self-service onboarding with subdomain selection
- **Tenant isolation**: Complete data isolation using `tenant_id` global scopes
- **Central admin panel**: Super-admin at `admin.cydm.co.tz` for platform management

### 1.2 Tenant Lifecycle Management
- **Tenant registration**: Multi-step onboarding wizard (details → branding → products → users → go-live)
- **Trial period**: 14-day free trial with full features
- **Subscription plans**: Starter / Growth / Enterprise tiers with feature gating
- **Tenant suspension/reactivation**: Grace period, data retention policies
- **Tenant deletion**: Soft delete with 30-day recovery, then GDPR-compliant purge

---

## 2. Membership & Client Management (Tier 4 / SACCOS Compliant)

### 2.1 Member Onboarding & KYC
- **Digital KYC (e-KYC)**: NIDA (National ID) verification via API integration
- **Biometric capture**: Fingerprint/face capture for high-value transactions
- **Member application workflow**: Multi-stage (draft → submitted → verified → approved → active)
- **Required fields per Microfinance Regulations 2019**:
  - Full names (first, middle, last)
  - Date of birth, place of birth, gender, marital status
  - NIDA number, TIN number
  - Permanent address, phone, email
  - Occupation/business type, monthly income
  - Next of kin / emergency contacts
  - Passport photo, ID document uploads
  - Signature specimen capture

### 2.2 Member Account Types
- **Membership Shares (Compulsory)**: Non-withdrawable until membership cessation
  - Configurable minimum shares per Cooperative Societies Act (default 20% of total)
  - Progress tracking toward full share capital (24-month configurable period)
- **Voluntary Shares**: Withdrawable per SACCOS bylaws, usable as loan collateral
- **Savings Accounts**: 
  - Compulsory savings (linked to loan eligibility)
  - Voluntary savings (multiple products: regular, target, fixed-term)
  - Interest calculation (daily/monthly accrual, configurable rates)
- **Time/Fixed Deposits**: Multiple tenors (30, 90, 180, 365 days) with tiered rates

### 2.3 Group Lending (Solidarity Groups)
- **Group formation**: 5-30 members, group constitution, leadership roles
- **Group guarantee**: Cross-guarantee mechanism for loan applications
- **Group meetings**: Schedule, attendance tracking, minutes recording
- **Group savings**: Collective savings with individual sub-accounts
- **Group loans**: Disbursement to group, internal allocation tracking

---

## 3. Loan Management (Full Lifecycle)

### 3.1 Loan Products Configuration
- **Product types**: Individual, Group, Asset Financing, Emergency, Agricultural, Business
- **Interest calculation methods**:
  - Reducing balance (mandatory per BOT)
  - Flat rate (for specific products only)
  - Configurable per product
- **Fee structures**: Processing fee, insurance, legal, appraisal, late payment penalties
- **Repayment frequencies**: Weekly, Bi-weekly, Monthly, Quarterly, Custom
- **Grace periods**: Configurable per product (0-90 days)
- **Loan limits**: Min/max amounts, % of savings/shares, % of income

### 3.2 Loan Application Workflow (4-Stage Maker-Checker)
```
SUBMIT → APPRAISE → APPROVE → DISBURSE
```
- **Stage 1 - Submit**: Member/loan officer creates application with purpose, amount, collateral
- **Stage 2 - Appraise**: Credit officer reviews, field verification, credit scoring, guarantor validation
- **Stage 3 - Approve**: Committee approval (configurable thresholds: LO → BM → Credit Committee → Board)
- **Stage 4 - Disburse**: Payment processing (M-Pesa, Airtel Money, Mixx, HaloPesa, Bank Transfer, Cash)

### 3.3 Collateral & Guarantor Management
- **Collateral types**: Shares, Savings, Fixed Deposits, Land/Property, Vehicle, Equipment, Guarantors
- **Collateral valuation**: Internal/appraiser valuation with photo documentation
- **Collateral locking**: Prevent withdrawal of pledged savings/shares/deposits
- **Guarantor tracking**: Multiple guarantors per loan, guarantor capacity analysis
- **Insurance integration**: Credit life insurance, asset insurance

### 3.4 Loan Servicing & Collections
- **Repayment schedules**: Auto-generated (reducing balance), manual override capability
- **Payment channels**: Mobile money (M-Pesa, Airtel, Mixx, HaloPesa), Bank, Cash, Check, Internal transfer
- **Partial payments**: Supported with allocation rules (fees → interest → principal)
- **Early settlement**: Prepayment penalty calculation, schedule recalculation
- **Arrears management**: 
  - Automated SMS/WhatsApp reminders (configurable: 3 days before, due date, 1/7/14/30 days overdue)
  - PAR (Portfolio at Risk) tracking: 1-30, 31-60, 61-90, 91-180, 180+ days
  - Collection officer assignment, field visit scheduling
  - Promise-to-pay tracking, repayment negotiations

### 3.5 Loan Restructuring & Recovery
- **Restructuring**: Reschedule, refinance, consolidate, grace period extension
- **Write-off**: Board-approved write-off with provision reversal
- **Collateral realization**: Auction process, legal proceedings tracking
- **Credit Reference Bureau (CRB) reporting**: Automated monthly submission to CRB

---

## 4. Savings & Deposits Management

### 4.1 Savings Products
- **Compulsory Savings**: Linked to loan eligibility (configurable % of loan amount)
- **Voluntary Savings**: 
  - Regular savings (daily/weekly/monthly deposits)
  - Target savings (goal-based: school fees, business expansion, assets)
  - Youth/Children savings products
- **Fixed/Term Deposits**: 30, 60, 90, 180, 365 days with auto-renewal options
- **Interest calculation**: Daily balance method, monthly/quarterly/annual posting
- **Tiered interest rates**: Higher balances earn better rates

### 4.2 Transactions
- **Deposits**: Cash, Mobile money, Bank transfer, Internal transfer, Check
- **Withdrawals**: Counter, Mobile money, ATM (if card issued), Check
- **Transfers**: Between member accounts, to loan repayment, to shares
- **Statements**: Monthly/quarterly/on-demand, PDF/email/SMS
- **Passbook printing**: Physical passbook support for offline members

---

## 5. Shares & Dividends Management

### 5.1 Share Capital Management
- **Share classes**: Membership (compulsory), Voluntary, Preferred, Institutional
- **Share register**: Digital share certificate generation, transfer tracking
- **Share valuation**: Periodic revaluation, price per share computation
- **Share transfers**: Member-to-member, inheritance, redemption on exit

### 5.2 Dividend Processing
- **Surplus allocation**: Per AGM resolution, regulatory compliance (capital adequacy)
- **Dividend calculation**: Price per share × shares held
- **Pre-payment deductions**: Outstanding loans, fees, penalties auto-deducted
- **Dividend payment**: Cash, capitalization (bonus shares), mobile money
- **Tax compliance**: Withholding tax (WHT) calculation and remittance

---

## 6. Accounting & Financial Management (Double-Entry)

### 6.1 General Ledger
- **Chart of Accounts**: Configurable per tenant (standard Tanzanian SACCOS CoA template)
- **Journal entries**: Auto-generated from all transactions (loans, savings, shares, fees, expenses)
- **Sub-ledgers**: Member ledger, Loan ledger, Savings ledger, Shares ledger, Fixed assets
- **Trial balance**: Real-time, exportable
- **Financial statements**: 
  - Balance Sheet (Statement of Financial Position)
  - Income Statement (Statement of Comprehensive Income)
  - Cash Flow Statement
  - Statement of Changes in Equity
- **Accrual basis**: Full accrual accounting per regulations

### 6.2 Fixed Assets & Depreciation
- **Asset register**: Acquisition, disposal, transfer, revaluation
- **Depreciation methods**: Straight-line, reducing balance, units of production
- **Asset categories**: Land, Buildings, Vehicles, Equipment, Furniture, ICT
- **Insurance tracking**: Policy details, renewal reminders

### 6.3 Cash Management
- **Cashbook**: Daily cash position, denomination tracking
- **Bank reconciliation**: Multi-bank, auto-match, manual reconciliation
- **Petty cash**: Float management, reimbursement workflow
- **Teller management**: Multi-teller, shift handover, cash limits

---

## 7. Regulatory Reporting (BOT/TCDC Compliance)

### 7.1 Monthly Supervision Plan (MSP) Reports
All 10 standard BOT forms generated from live data:
1. **Form MSP1**: Balance Sheet
2. **Form MSP2**: Income Statement
3. **Form MSP3**: Capital Adequacy
4. **Form MSP4**: Asset Quality (Loan Classification)
5. **Form MSP5**: Liquidity Position
6. **Form MSP6**: Earnings & Profitability
7. **Form MSP7**: Sensitivity to Market Risk
8. **Form MSP8**: Off-Balance Sheet Items
9. **Form MSP9**: Branch Network & Outreach
10. **Form MSP10**: Operational Risk

### 7.2 Quarterly & Annual Returns
- **Quarterly financial returns** to BOT/Delegated Authority
- **Annual audited financial statements**
- **AGM report pack**: Financials, loan portfolio analysis, membership stats
- **TCDC annual returns** for SACCOS

### 7.3 Loan Classification & Provisioning (GN 679, Reg 45)

> **⚠️ Corrected 16 Aug 2026.** The buckets originally listed here
> (Performing / Watch, with Doubtful up to 180 days and Loss beyond) do not
> match the regulation and **understated provisions**. See
> [03-loans.md](03-loans.md) for the full correction.

- **5-tier classification**: Current (0–5d), Especially Mentioned (6–30d),
  Substandard (31–60d), Doubtful (61–90d), **Loss (over 90d)**
- **Automatic provisioning**: 1% / 5% / 25% / 50% / 100%
- **Separate housing microfinance schedule**: Substandard 91–180d,
  Doubtful 180–360d, Loss 361d+ (Reg 45(3)–(4))
- **Past due is whole-loan**: one day late puts the entire outstanding balance
  past due (Reg 44(2)); PAR uses that full balance
- **Non-performing loan (NPL) tracking**: PAR ratios, provision adequacy

### 7.4 Credit Reference Bureau (CRB) Integration
- **Monthly data submission**: Performing & non-performing loans
- **Credit report pulling**: During loan appraisal
- **Consent management**: Member consent for CRB sharing

---

## 8. Mobile Money & Payment Gateway Integration

### 8.1 Supported Tanzanian Payment Providers
- **M-Pesa** (Vodacom): Disbursement, Collection, C2B, B2C
- **Airtel Money**: Disbursement, Collection
- **Mixx by Yas** (TTCL): Disbursement, Collection
- **HaloPesa** (Halotel): Disbursement, Collection
- **Tigo Pesa**: Disbursement, Collection
- **Bank transfers**: NMB, CRDB, TPB, NBC, Standard Chartered, etc. via TIPS
- **Card payments**: Visa/Mastercard (for deposits/loan repayments)

### 8.2 Payment Features
- **Unified payment gateway**: Single integration, multiple providers
- **Automatic reconciliation**: Webhook handlers for each provider
- **Failed payment retry**: Dunning management (configurable retry schedule)
- **Transaction fees**: Absorbed by MFI or passed to member (configurable)
- **Settlement tracking**: Daily settlement reports per provider

---

## 9. Communications & Notifications

### 9.1 SMS Gateway Integration
- **Local providers**: Bonga, Africa's Talking, Infobip, local aggregators
- **Templates**: Loan approval, disbursement, repayment reminders, overdue, savings deposits, dividends
- **Bulk SMS**: Marketing, announcements, AGM notices
- **OTP**: 2FA, transaction verification
- **Language**: Swahili & English templates

### 9.2 WhatsApp Business API
- **Rich notifications**: Interactive buttons (Pay Now, View Schedule)
- **Document sharing**: Loan agreements, statements, receipts
- **Chat support**: Agent handoff for member queries

### 9.3 Email & In-App Notifications
- **Transactional emails**: Receipts, statements, approvals
- **Marketing emails**: Product launches, financial education
- **In-app notification center**: Real-time, mark as read, archive

---

## 10. Human Resources & Payroll

### 10.1 Staff Management
- **Employee records**: Personal info, contracts, qualifications, NIDA, TIN
- **Organizational structure**: Branches, departments, reporting lines
- **Role-based access**: Per-module permissions (Loans, Savings, Accounting, Admin, Reports)
- **Branch isolation**: Staff only see their branch data (configurable)

### 10.2 Payroll
- **Salary configuration**: Basic, allowances (housing, transport, risk), deductions (PAYE, NSSF, NHIF, loans)
- **Payroll runs**: Monthly, with payslip generation (PDF/email)
- **Statutory compliance**: PAYE, NSSF, NHIF, SDL, WCF calculations
- **Loan deductions**: Staff loan repayment via payroll

---

## 11. Audit Trail & Security

### 11.1 Comprehensive Audit Logging
- **Every action logged**: Create, Read, Update, Delete with before/after values
- **Immutable logs**: Append-only, tamper-evident
- **User attribution**: Who, when, from where (IP, device), what changed
- **Sensitive data masking**: PII encryption in logs

### 11.2 Security Features
- **Two-Factor Authentication (2FA)**: TOTP (Google Authenticator), SMS OTP
- **Password policies**: Complexity, expiry (90 days), history (last 5), lockout (5 attempts)
- **Session management**: Concurrent session limits, idle timeout, device tracking
- **IP whitelisting**: Per tenant (branch/office IPs)
- **Data encryption**: At rest (AES-256), in transit (TLS 1.3)
- **PII protection**: PDPA 2022 compliance, data minimization, retention policies

---

## 12. Document Management

### 12.1 Document Types
- **Member documents**: ID, NIDA, photos, signatures, proof of address, references
- **Loan documents**: Application, agreement, schedule, collateral docs, guarantor forms
- **Legal documents**: Board resolutions, policies, bylaws, licenses
- **Generated documents**: Statements, certificates, receipts, reports (PDF with digital signature)

### 12.2 Features
- **Version control**: Document versions with audit trail
- **E-signature**: Integration with local e-signature providers
- **Storage**: Tenant-isolated, encrypted, backed up
- **Retention policies**: Configurable per document type (7 years default for financial)

---

## 13. Business Intelligence & Analytics

### 13.1 Dashboards
- **Executive dashboard**: Portfolio size, PAR, yield, outreach, efficiency ratios
- **Branch manager dashboard**: Branch performance, targets vs actual, team productivity
- **Loan officer dashboard**: Pipeline, collections, appointments, tasks
- **Member portal dashboard**: Account summary, loan status, savings growth, upcoming payments

### 13.2 Reports Library
- **Portfolio reports**: Aging, product mix, officer performance, branch comparison
- **Savings reports**: Growth, mobilization, cost of funds, withdrawal trends
- **Membership reports**: Growth, demographics, activity, dormancy
- **Financial ratios**: PEARLS, CAMEL, custom ratios
- **Custom report builder**: Drag-drop, scheduled delivery, export (PDF, Excel, CSV)

---

## 14. Member Self-Service Portal

### 14.1 Web Portal (Responsive)
- **Account overview**: Balances, recent transactions, loan status
- **Loan application**: Digital application with document upload
- **Loan calculator**: Quote estimator (amount, term, rate → installment)
- **Savings transactions**: Deposit via mobile money, withdrawal requests
- **Statements**: Download, email request
- **Profile management**: Update contact info, KYC documents
- **Notifications**: In-app, email, SMS preferences

### 14.2 Mobile App (Future Phase)
- **React Native / Flutter**: Biometric login, push notifications
- **Offline capability**: View balances, schedule
- **USSD integration**: For feature phone users (*150*xxx#)

---

## 15. Configuration & Customization (Per Tenant)

### 15.1 System Settings
- **General**: Institution name, license number, address, contacts, logo, currency (TZS)
- **Numbering series**: Member numbers, loan accounts, savings accounts, receipts, vouchers
- **Interest rate policies**: Base rates, risk premiums, savings rates, deposit rates
- **Fee schedules**: All transaction fees, penalties, service charges
- **Holiday calendar**: Tanzania public holidays + custom branch holidays
- **Working hours**: Branch operating hours, cut-off times

### 15.2 Workflow Configuration
- **Approval matrices**: Loan amounts → required approvers
- **Notification rules**: Event triggers, channels, templates, recipients
- **Document requirements**: Per loan product, per member type
- **Interest calculation rules**: Day count conventions (Actual/360, Actual/365)

---

## 16. Integration & API

### 16.1 External Integrations
- **NIDA API**: Real-time identity verification
- **CRB API**: Credit report pull, data submission
- **TIPS (Tanzania Instant Payment System)**: Interbank transfers
- **TRA (Tanzania Revenue Authority)**: EFDMS integration for receipts
- **PDPC**: Data protection compliance reporting

### 16.2 REST API (For Tenants & Partners)
- **OpenAPI/Swagger documentation**
- **API keys per tenant**: Scoped permissions
- **Webhooks**: Real-time event notifications (loan created, payment received, member updated)
- **Rate limiting**: Per tenant, per endpoint

---

## 17. Super-Admin Platform Features

### 17.1 Tenant Management
- **Tenant CRUD**: Create, configure, suspend, delete
- **Impersonation**: "Login as tenant" for support (read-only or full)
- **Usage analytics**: Active users, API calls, storage, transactions
- **Billing & subscriptions**: Stripe integration, invoice generation, payment tracking

### 17.2 Platform Monitoring
- **System health**: Uptime, response times, error rates
- **Tenant health**: Login activity, transaction volumes, support tickets
- **Audit log viewer**: Cross-tenant (super-admin only)
- **Database management**: Backup status, migration status per tenant

---

## 18. Implementation Priority (Phased Approach)

### Phase 1: Core Foundation (Weeks 1-8)
- [ ] Multi-tenancy infrastructure (Stancl/Tenancy)
- [ ] Subdomain routing + custom domains
- [ ] Tenant onboarding flow
- [ ] Authentication & RBAC (Spatie Permissions)
- [ ] SHAD UI design system (blue/orange theme)
- [ ] Member management (KYC, shares, savings)
- [ ] Basic loan application workflow

### Phase 2: Loan Engine & Accounting (Weeks 9-16)
- [ ] Full loan lifecycle (appraise → approve → disburse → collect)
- [ ] Reducing balance calculator, schedules
- [ ] Double-entry accounting (GL, sub-ledgers, trial balance)
- [ ] Mobile money integrations (M-Pesa, Airtel, Mixx, HaloPesa)
- [ ] SMS/WhatsApp notifications
- [ ] BOT MSP reporting (Forms 1-10)

### Phase 3: Advanced Features (Weeks 17-24)
- [ ] Group lending module
- [ ] Fixed assets & depreciation
- [ ] Payroll & HR
- [ ] Dividend processing
- [ ] CRB integration
- [ ] Member self-service portal
- [ ] Custom report builder

### Phase 4: Polish & Scale (Weeks 25-32)
- [ ] Performance optimization
- [ ] Advanced analytics dashboards
- [ ] API platform + webhooks
- [ ] Mobile app (React Native)
- [ ] USSD gateway
- [ ] Multi-language (Swahili/English full)
- [ ] Load testing, security audit
- [ ] Documentation & training materials

---

## 19. Technical Requirements Summary

| Requirement | Specification |
|-------------|---------------|
| **Framework** | Laravel 12 + Inertia.js + React 19 + TypeScript |
| **UI Library** | SHAD UI (shadcn/ui) with custom blue/orange theme |
| **Styling** | Tailwind CSS v4 + CSS Variables for theming |
| **Database** | PostgreSQL 16 (single DB, row-level tenancy) |
| **Cache/Queue** | Redis (Valkey) + Horizon |
| **Multi-tenancy** | Stancl/Tenancy v4 (single DB, tenant_id scopes) |
| **Payments** | Stripe (subscriptions) + 5+ Tanzanian mobile money gateways |
| **Search** | Meilisearch / Laravel Scout |
| **File Storage** | S3-compatible (MinIO/Wasabi/AWS) with tenant prefixes |
| **Monitoring** | Sentry + Laravel Pulse + Prometheus/Grafana |
| **Testing** | Pest (PHP) + Vitest (React) + Playwright (E2E) |
| **CI/CD** | GitHub Actions → Docker → Kubernetes (or VPS) |
| **Compliance** | BOT MSP, PDPA 2022, AML/CFT, PCI-DSS (for cards) |

---

## 20. Success Metrics (KPIs)

### Platform Level
- **Tenant acquisition**: 50+ MFIs in Year 1
- **Tenant retention**: >95% annual
- **System uptime**: 99.9%
- **API response time**: <200ms p95

### Tenant Level (per MFI)
- **Loan portfolio growth**: 20%+ YoY
- **PAR >30 days**: <5%
- **Operational cost reduction**: 30% vs manual/Excel
- **Regulatory reporting time**: Hours → Minutes
- **Member satisfaction**: >4.5/5 (NPS)

---

*This document serves as the master feature specification for the CYDM Microfinance Platform. All development should reference this document for scope, requirements, and compliance standards.*