Loan Management Module¶
Overview¶
The Loan Management module handles the complete loan lifecycle from product definition, application processing, underwriting, disbursement, repayment tracking, and collection. It includes advanced features like automated loan scoring, fraud detection, collateral management, and portfolio analytics.
API Prefix: /api/v1/loan
Route Verification Status¶
- Source Router:
app/api/v1/endpoints/loan.py - Live Route Count: 87
- Verification State: Verified (2026-06-28)
- Canonical Tracking:
docs/API_ROUTE_DOCUMENTATION_TODO.md - Verification Method: Route decorators extracted from
@r.<method>(...)inapp/api/v1/endpoints/loan.py.
Key Features¶
1. Loan Product Management¶
- Define loan products with configurable terms
- Set interest rates, fees, and repayment schedules
- Support for multiple loan types (personal, business, secured, unsecured)
- Product activation/deactivation
- Lock products to prevent modification
2. Loan Application Processing¶
- Online loan application submission
- Application workflow (Submitted → Under Review → Approved/Rejected)
- Document collection and verification
- Multi-level approval workflows
- Application history and audit trail
3. Loan Scoring & Underwriting¶
- Internal Scoring: Rule-based scoring using customer data
- External Scoring: Integration with external credit bureaus
- Machine Learning Models: Trained models for risk assessment
- Risk Categorization: High, Medium, Low risk profiles
- Automated Decision: Approve/Reject based on score thresholds
- Manual Override: Loan officers can override automated decisions
4. Disbursement Management¶
- Approve and disburse loans to customer accounts
- Partial disbursements for staged funding
- Disbursement tracking and audit
- Integration with transaction system
- Notification on disbursement
5. Repayment Management¶
- Automated repayment scheduling (daily, weekly, monthly, quarterly)
- Flexible payment options
- Partial and full prepayment support
- Repayment reversal for failed transactions
- Repayment history tracking
6. Collateral Management¶
- Record collateral offered
- Track collateral ownership and valuation
- Accept/Reject collateral
- Collateral-based lending decisions
7. Fraud Detection¶
- Fraud Rules Engine: Configurable rules for fraud detection
- Fraud Flags: Automatic flag suspicious applications
- Fraud Cases: Escalate and investigate suspected fraud
- Rule Groups: Organize fraud rules by category
- Decision Workflow: Approve/Reject/Investigate fraudulent cases
- False Positive Tracking: Mark incorrectly flagged cases
8. Default & Collection Management¶
- Mark loans as defaulted
- Track delinquency periods
- Write-off accounts
- Collection case management
- Collection notes and case assignment
9. Portfolio Management¶
- Portfolio summary and metrics
- Delinquency reports
- Exposure analysis
- Portfolio by status/product
- Portfolio performance analytics
10. Guarantor Management¶
- Add guarantors to loans
- Guarantor verification
- Accept/Reject guarantor
- Track guarantor relationships
API Endpoints (Verified Against Live Router)¶
For the complete loan endpoint inventory (all 87 routes with method, effective path, and source line), use:
- docs/API_ROUTE_LIVE_REFERENCE.md -> section loan.py (87 routes)
This document focuses on workflow and domain behavior. The live reference above is the canonical endpoint parity source.
Database Models¶
Core Loan Models¶
- Loan: Main loan record with amount, term, interest rate, status
- LoanProduct: Loan product definition and configuration
- LoanApplication: Loan application with status tracking
- LoanInstallment: Scheduled installment/repayment schedule
- LoanRepayment: Recorded repayment transaction
- LoanStatusHistory: Audit trail of status changes
Scoring & Risk Assessment¶
- LoanScoreLog: Scoring result with score, factors, decision
- RiskProfile: Risk assessment per customer/agent
- RiskParameter: Configuration for risk calculation
Collateral & Guarantors¶
- Collateral: Collateral offered for loan
- GuarantorAssignment: Guarantor linked to loan
- GuarantorVerification: Verification status of guarantor
Fraud Management¶
- FraudFlag: Flagged suspicious loan application
- FraudCase: Investigation case for flagged application
- FraudRule: Rule for detecting fraud patterns
- FraudRuleGroup: Group of related fraud rules
Collection & Default¶
- LoanBlacklist: Blacklisted customers/entities
- CollectionCase: Case for defaulted loan collection
- CaseAssignment: Assign case to collector
- CollectionNote: Document collection activities
Loan Lifecycle¶
Standard Loan Flow¶
1. Loan Product Creation
├─ Define product terms
├─ Set interest rate & fees
└─ Activate product
2. Loan Application
├─ Customer submits application
├─ Provide supporting documents
└─ Application queued for review
3. Application Review & Scoring
├─ Run internal scoring engine
├─ Check credit bureau (if enabled)
├─ Assess fraud risk
├─ Loan officer reviews & adjusts
└─ Decision: Approve/Reject/Refer
4. Loan Approval
├─ Notify customer
├─ Collect signatures/consent
└─ Create loan record
5. Disbursement
├─ Generate disbursement instruction
├─ Execute fund transfer
├─ Create repayment schedule
└─ Send disbursement notification
6. Repayment
├─ Receive payment from customer
├─ Apply payment to schedule
├─ Update loan balance
└─ Send receipt
7. Loan Closure
├─ Final payment received
├─ Mark loan as paid off
└─ Archive loan record
Delinquency & Default Handling¶
1. Missed Payment
├─ Flag overdue
├─ Send reminder notification
└─ Start grace period
2. Delinquency (30+ days)
├─ Escalate to dunning
├─ Create collection case
└─ Notify collection team
3. Default (90+ days)
├─ Mark as defaulted
├─ Remove from good standing
├─ Begin recovery process
└─ Optional write-off
4. Write-off
├─ Remove from active portfolio
├─ Record loss
└─ Continue collection attempts
Scoring System¶
Internal Scoring Algorithm¶
Base Score: 100
Deductions based on:
- Credit history: -0 to -30
- Income level: -0 to -20
- Debt-to-income ratio: -0 to -25
- Employment stability: -0 to -15
- Payment history: -0 to -10
Final Score Ranges:
- 80-100: Approved
- 60-79: Manual Review
- Below 60: Rejected
External Scoring Integration¶
- Query credit bureau via integration APIs
- Return credit score (if available)
- Combine with internal score
- Adjust thresholds based on bureau data
Fraud Rule Examples¶
Rule 1: Duplicate Application
IF (customer_id, phone, email) in (applications last 7 days)
THEN flag_as_fraud()
Rule 2: Suspicious Income
IF income > 1000000 AND customer_age < 25
THEN flag_for_review()
Rule 3: High Velocity
IF (customer_id applications count last 24h) > 3
THEN flag_as_fraud()
Rule 4: Mismatched Data
IF phone_owner_name != customer_name
THEN flag_for_verification()
Controllers & Business Logic¶
Key Controllers¶
controller/loan.py: Loan lifecycle managementcreate_loan_application(): Submit applicationapprove_loan(): Approve for disbursementdisburse_loan(): Execute disbursementrecord_repayment(): Process repayment-
mark_loan_default(): Handle default -
controller/loan_scoring.py: Scoring engine run_internal_scoring(): Calculate scorerun_external_scoring(): Query bureaus-
get_risk_category(): Risk assessment -
controller/fraud.py: Fraud detection evaluate_fraud_rules(): Check all rulesflag_application(): Flag suspicious app-
create_fraud_case(): Start investigation -
controller/collection.py: Collection management create_collection_case(): Create caseassign_case(): Assign to collectorauto_assign_cases(): Batch assignment
Configuration¶
Loan Product Configuration¶
{
"name": "Personal Loan",
"min_amount": 10000,
"max_amount": 500000,
"min_term_months": 6,
"max_term_months": 60,
"interest_rate_percent": 15.5,
"processing_fee_percent": 2.5,
"insurance_fee_percent": 0.5,
"repayment_frequency": "monthly",
"collateral_required": false,
"min_credit_score": 60,
"active": true
}
Fraud Rule Configuration¶
{
"name": "High Velocity Rule",
"description": "Flag multiple applications in 24h",
"rule_type": "velocity_check",
"parameters": {
"time_window_hours": 24,
"max_applications": 3
},
"severity": "high",
"action": "flag_and_escalate",
"enabled": true
}
Scoring Configuration¶
INTERNAL_SCORE_WEIGHT=0.7
EXTERNAL_SCORE_WEIGHT=0.3
APPROVAL_THRESHOLD=70
REVIEW_THRESHOLD=60
FRAUD_CHECK_ENABLED=true
AUTO_APPROVE_ENABLED=false
Common Use Cases¶
1. Loan Application & Approval¶
1. Customer fills application form
2. System runs fraud checks
3. System runs scoring (internal + external)
4. Results presented to loan officer
5. Officer approves/rejects
6. Notification sent to customer
2. Fraud Detection Workflow¶
1. New application received
2. Fraud rules engine evaluates all rules
3. Multiple rules trigger → flag as suspicious
4. Flag escalated to fraud analyst
5. Analyst investigates by reviewing:
- Phone owner verification
- Address validation
- Income verification
6. Decision: Approve/Reject/Refer back
3. Loan Disbursement¶
1. Approved loan officer triggers disbursement
2. System validates loan status
3. Generates payment instruction
4. Executes fund transfer to customer account
5. Creates repayment schedule based on terms
6. Sends disbursement confirmation
4. Repayment Processing¶
1. Customer makes payment via channel (Mobile, USSD, Agent, Web)
2. Payment received and verified
3. Applied to oldest overdue installment first
4. Loan balance updated
5. Next installment due date calculated
6. Receipt/confirmation sent
5. Default & Collection¶
1. Loan marked as defaulted (90+ days)
2. Automatically creates collection case
3. Case auto-assigned to available collector
4. Collector attempts to contact customer
5. Documents collection notes
6. Options: Payment arrangement, write-off, legal action
Integration Points¶
External Services¶
- Credit Bureau: External loan scoring and credit checks
- Transaction System: Disbursement and repayment execution
- Notification System: Customer and staff notifications
- Document Management: Store application documents
- AI Agent: Query loan data via conversational interface
Internal Modules¶
- Customer Management: Access customer profile and verification
- Transaction Processing: Record disbursement/repayment transactions
- Wallet System: Update balances on disbursement
- Campaign Management: Apply loan offers and promotions
- Policy Management: Enforce risk policies
- Audit Logging: Track all loan operations
Performance Considerations¶
- Batch Processing: Run EOD jobs in background (Celery)
- Scoring Optimization: Cache credit bureau responses
- Database Indexing: Index on loan_id, customer_id, status
- Portfolio Reports: Pre-calculate for dashboard display
- Fraud Rules: Cache rule evaluation results per application
Error Handling¶
Common Errors¶
INSUFFICIENT_FUNDS: Account lacks funds for disbursementINVALID_AMOUNT: Requested amount outside product limitsAPPLICATION_ALREADY_APPROVED: Duplicate approval attemptLOAN_NOT_FOUND: Loan ID doesn't existFRAUD_FLAG_EXISTS: Application already flaggedINVALID_REPAYMENT_AMOUNT: Amount exceeds balanceLOAN_ALREADY_PAID: Cannot process repayment on paid loan
Fraud-Specific Errors¶
FRAUD_RULE_FAILED: Application flagged by fraud ruleFRAUD_INVESTIGATION_PENDING: Decision pending investigationBLACKLIST_VIOLATION: Customer is blacklisted
Testing¶
Test Categories¶
- Loan application and approval workflows
- Scoring engine accuracy
- Fraud rule detection
- Repayment processing
- Default and collection workflows
- Portfolio reporting and analytics
Test Files¶
tests/test_loan.py: Loan operationstests/test_fraud.py: Fraud detectionFRAUD_DETECTION_TESTS_QUICK_REF.md: Test reference guide
Security & Compliance¶
- Data Privacy: Mask sensitive data in logs/reports
- Audit Trail: Log all loan status changes and operations
- Role-Based Access: Restrict operations by user role
- Approval Workflows: Require authorized approvals
- Fraud Detection: Automatic fraud flagging and escalation
- Compliance Reporting: Generate regulatory reports
- Document Management: Secure storage of application docs