# MICROFINANCE SYSTEM — STEP-BY-STEP DEVELOPMENT PROMPTS

## GLOBAL INSTRUCTION

Use `MICROFINANCE_SPEC.md` as the authoritative specification for this project.

Important rules for EVERY development step:

- Read the relevant sections of `MICROFINANCE_SPEC.md` before coding.
- Implement only the phase requested in the current prompt.
- Do not remove or break previously completed functionality.
- Do not create fake functionality or placeholder buttons.
- Every form must save real data.
- Every list must use real database data.
- Every financial calculation must happen on the backend.
- Use database transactions for financial operations.
- Do not use floating-point numbers for money.
- Financial records must not be hard deleted.
- Enforce permissions on the backend, not only the UI.
- Add validation.
- Add audit logging where appropriate.
- Add automated tests for business-critical functionality.
- Run tests before completing each phase.
- Fix errors before reporting the phase complete.
- At the end of each phase report:
  1. What was implemented
  2. Database changes
  3. Main files created/modified
  4. Routes/endpoints added
  5. Tests added
  6. Test results
  7. Anything remaining for that phase

Do not implement future phases unless they are technically necessary for the current phase.

---

# STEP 1 — PROJECT FOUNDATION

Implement the foundation of the Microfinance Management System.

Build:

1. Authentication
2. Business/company configuration
3. Branch management
4. Employees/system users
5. Roles
6. Permissions
7. User-to-branch assignments
8. Audit-log foundation
9. Application settings
10. Secure file-storage foundation

Business configuration must support:

- Business name
- Logo
- Registration number
- TIN
- Business licence
- Address
- Region
- District
- Country
- Phone
- Email
- Website
- Postal address
- Currency
- Currency symbol
- Number format
- Financial year
- Accounting period
- Default interest calculation method
- Default penalty configuration
- Company stamp

Create the initial roles:

- Super Administrator
- Branch Manager
- Loan Officer
- Loan Inspector
- Cashier
- Accountant
- Debt Collector
- HR/Payroll Officer
- Auditor

Implement real permission checking.

Branch employees must not access another branch unless specifically permitted.

Super Administrator can access all branches.

Create clean responsive screens for:

- Business Settings
- Branches
- Employees
- Roles
- Permissions

Add seeders for default roles and permissions.

### Default Administrator Seed

Create a dedicated `AdminUserSeeder` and call it from `DatabaseSeeder`.

Default administrator account:

- Name: `System Administrator`
- Email: `admin@microfinance.local`
- Password: `Admin@12345`
- Role: `Super Administrator`

Seeder requirements:

- Use `firstOrCreate` or an equivalent idempotent approach.
- Re-running the seeder must not create duplicate administrator accounts.
- Re-running the seeder must not overwrite the password of an existing administrator.
- Mark the seeded administrator email as verified.
- Hash the password using Laravel's secure password hashing.
- Once roles and permissions are implemented, automatically assign the seeded administrator the `Super Administrator` role.
- The `Super Administrator` must have access to all branches and all system permissions.
- The default password must be changed before production use.

Run the seed with:

```bash
php artisan db:seed
```

Or during a fresh installation:

```bash
php artisan migrate --seed
```

Add automated tests for:

- Login
- Permissions
- Branch isolation
- Super Administrator access
- Unauthorized access

Do not implement customers or loans yet.

Complete and test this phase before stopping.

---

# STEP 2 — CUSTOMER MANAGEMENT

Using the existing project foundation, implement complete customer management.

Do not alter working functionality from Step 1.

Build:

1. Customer registration
2. Customer profile
3. Customer unique number
4. Customer with NIN workflow
5. Customer without NIN workflow
6. Address
7. Next of kin
8. Customer photo
9. Customer documents
10. Guarantors
11. Duplicate-customer detection
12. Customer blacklist/watchlist
13. Customer risk-profile foundation

Customer fields must include:

- Customer ID
- First name
- Middle name
- Last name
- Gender
- Date of birth
- NIN
- Phone
- Alternative phone
- Email
- Occupation
- Employer/business
- Monthly income
- Marital status
- Region
- District
- Ward
- Street/village
- House number
- GPS coordinates

Allow unlimited document uploads.

Documents must support:

- Document type
- File
- Uploaded date
- Uploaded by
- Expiry date
- Notes

Support documents such as:

- National ID
- Voter ID
- Passport
- Driving licence
- Introduction letter
- Employer letter
- Business licence
- Salary slip
- Bank statement
- Proof of residence
- Customer photograph
- Guarantor documents

Customer documents must be securely stored.

For NIN:

Create an integration/service abstraction.

If no NIN provider is configured, the application must still work through manual entry.

Duplicate detection must check at least:

- NIN
- Phone
- Email

Do not silently create duplicates.

Create customer profile tabs for:

- Overview
- Personal details
- KYC
- Documents
- Guarantors
- Blacklist
- Activity

Loan-related tabs may remain empty until loans are implemented.

Add permissions and audit logging.

Add tests.

---

# STEP 3 — LOAN PRODUCTS AND CALCULATION ENGINE

Implement the loan-product and loan-calculation engine.

Do not build disbursement or payment yet.

Create Loan Products.

Each product supports:

- Product name
- Minimum amount
- Maximum amount
- Duration
- Duration unit
- Interest rate
- Interest calculation method
- Repayment frequency
- Grace period
- Late-payment penalty
- Processing fee
- Insurance fee
- Other charges
- Collateral required
- Guarantor required
- Status

Support interest methods:

1. Flat interest
2. Reducing balance
3. Fixed interest amount

Support frequencies:

- Daily
- Weekly
- Every two weeks
- Monthly
- Lump sum
- Custom repayment dates

Create a centralized Loan Calculation Service.

It must calculate:

# Principal + Interest + Fees

Total repayment

Create a centralized repayment-schedule generator.

Each installment stores:

- Number
- Principal
- Interest
- Fees
- Amount due
- Due date
- Amount paid
- Remaining
- Status

Ensure installment totals reconcile exactly with the loan total.

Use fixed-precision decimal calculations.

Add comprehensive automated tests for:

- Flat interest
- Reducing balance
- Fixed interest
- Fees
- Different terms
- Different frequencies
- Rounding
- Schedule totals

---

# STEP 4 — COLLATERAL / DHAMANA MANAGEMENT

Implement complete collateral management.

Build configurable collateral categories.

Examples:

- Television
- Refrigerator
- Phone
- Laptop
- Bed
- Sofa
- Motorcycle
- Car
- Land documents
- House documents
- Jewellery
- Business equipment
- Other

Every collateral item gets a unique number.

Example:

COL-DOM-000145

Store:

- Customer
- Branch
- Category
- Item
- Brand
- Model
- Serial number
- Colour
- Description
- Estimated value
- Accepted value
- Condition
- Date received
- Storage location
- Photos
- Documents
- Received by
- Status

Statuses:

- Pending Inspection
- Accepted
- In Custody
- Released
- Repossessed
- Scheduled for Sale
- Sold
- Returned

Generate printable barcode or QR identification.

Create collateral receipt.

Maintain permanent collateral movement/status history.

Implement storage location such as:

Branch → Store Room → Shelf

Implement collateral search by code.

Add permissions, audit logs and tests.

### Implementation Status — COMPLETED (12 August 2026)

Step 4 has been implemented in the application.

Implemented:

- Configurable collateral categories with active/inactive status.
- Default seeded categories from this specification.
- System-generated branch-specific collateral codes in the format `COL-{BRANCH}-000001`.
- Customer, branch and category linkage with backend branch isolation.
- Item details, brand, model, serial number, colour, condition and description.
- Fixed-precision estimated and accepted values.
- Date received, receiving staff, status and physical storage location.
- Private collateral photo and document storage/downloads.
- Printable Code 39 barcode identification labels.
- Printable collateral receipt.
- Printable release/return acknowledgement after a release or return movement is recorded.
- Permanent custody movement/status/location history.
- Storage hierarchy represented as `Branch → Store Room → Shelf`.
- Search by collateral code, customer, item and serial number.
- Status tabs and category filtering on the collateral list.
- Collateral permissions integrated into existing roles.
- Audit logging for collateral creation, updates, custody changes, category changes and file uploads.
- No collateral delete route; database relationships protect custody/file history from hard deletion.

Database changes:

- `collateral_categories`
- `collaterals`
- `collateral_files`
- `collateral_movements`

Main routes/endpoints added:

- Collateral list, create, view and edit.
- Collateral category management.
- Custody/status/location movement posting.
- Secure attachment upload/download.
- Printable collateral receipt.
- Printable barcode label.
- Printable release acknowledgement.

Automated coverage includes:

- System-generated collateral codes.
- Initial custody history.
- Secure photo metadata/storage flow.
- Permanent movement history.
- Branch isolation.
- Search by collateral code.
- Barcode/receipt rendering.
- Configurable categories.

Remaining for Step 4:

- None. Loan linkage will be implemented in Step 5 as defined below.

---

# STEP 5 — LOAN APPLICATION AND CONTRACT

Implement loan applications.

Workflow starts with selecting:

1. Customer
2. Loan product
3. Principal requested
4. Purpose
5. Collateral
6. Guarantor if required
7. Supporting documents

Generate unique loan number such as:

LN-DOM-2026-000125

Use the calculation engine created earlier.

Display:

- Principal
- Interest
- Fees
- Total repayment
- Proposed repayment schedule

Validate product minimum and maximum amount.

Validate required collateral.

Validate required guarantor.

Build loan detail page.

Generate professional loan contract PDF containing:

- Business details
- Customer
- Loan number
- Principal
- Interest
- Fees
- Total
- Schedule
- Collateral
- Guarantor
- Terms
- Late-payment rules
- Obligations
- Signature areas

Allow signed contract upload.

Create business setting:

Require Signed Contract Before Disbursement

Add statuses:

- Draft
- Application Submitted
- Waiting for Documents
- Contract Generated
- Contract Signed
- Under Review

Implement valid transitions only.

Add tests.

### Implementation Status — COMPLETED (12 August 2026)

Step 5 has been implemented in the application.

Implemented:

- Branch-scoped loan application creation, listing, editing and detail views.
- System-generated branch/year loan numbers in the format `LN-{BRANCH}-{YEAR}-000001`.
- Customer, loan product, principal, purpose, collateral, guarantor and supporting-document workflow.
- Existing fixed-precision calculation engine reused for principal, interest, fees and total repayment.
- Repayment schedules persisted as immutable application snapshots outside controlled draft/correction edits.
- Loan product minimum/maximum validation and required collateral/guarantor enforcement.
- Secure private supporting-document and signed-contract storage/downloads.
- Downloadable professional loan contract PDF containing business, customer, financial, schedule, collateral, guarantor, terms and signature sections.
- Business setting for `Require Signed Contract Before Disbursement`.
- Application statuses and valid lifecycle transitions through `Under Review`.
- Permanent loan status history, branch isolation, permissions and audit logging.
- Standardized loan list, bordered form and detail workspace UI.

Database changes:

- `loans`
- `loan_collateral`
- `loan_installments`
- `loan_documents`
- `loan_status_histories`
- `businesses.require_signed_contract_before_disbursement`

Main routes/endpoints added:

- Loan application list, create, view and draft edit/update.
- Backend repayment-schedule preview.
- Application status transition endpoint.
- Contract PDF generation/download.
- Signed-contract upload.
- Supporting-document upload/download.

Automated coverage includes:

- Unique loan-number generation.
- Exact financial snapshot and schedule reconciliation.
- Product amount limits and collateral/guarantor requirements.
- Secure supporting-document flow.
- Contract PDF generation and signed-contract upload.
- Valid/invalid application transitions.
- Branch isolation and standardized UI rendering.

Remaining for Step 5:

- None. Approval decisions and `Ready for Disbursement` are implemented in Step 6 below.

---

# STEP 6 — LOAN APPROVAL

Implement complete approval workflow.

Support:

MODE 1:
Approval Required

MODE 2:
Auto Approval for authorized users

Approval Required workflow:

Loan Officer
→ submits
→ Inspector/Manager reviews

Reviewer can:

- Approve
- Reject
- Request Correction
- Request Documents
- Request Additional Collateral

Every decision stores:

- User
- Date
- Comments
- Previous status
- New status

Implement optional Maker-Checker.

When enabled:

Creator cannot approve their own application.

Approved application becomes:

Ready for Disbursement

Do not disburse money yet.

Add configurable approval thresholds.

Example:

Loans above a configured amount require manager approval.

Add audit logs and tests.

### Implementation Status — COMPLETED (12 August 2026)

Step 6 has been implemented in the application.

Implemented:

- Configurable `Approval Required` mode.
- Configurable `Auto Approval for Authorized Users` mode using an explicit backend permission.
- Branch-scoped loan approval queue for inspectors/managers.
- Reviewer actions: approve, reject, request correction, request documents and request additional collateral.
- Permanent approval decisions storing reviewer, timestamp, comments, previous status, new status and automatic/manual flag.
- Optional Maker-Checker control that blocks the application creator from approving their own loan.
- Configurable manager approval threshold using fixed-precision money comparison.
- Loans above the configured threshold require a manager-authorized approver.
- Correction requests reopen controlled core-term editing and recalculation before resubmission.
- Document requests reuse the secure loan-document upload flow.
- Additional-collateral requests allow only available collateral belonging to the same customer and branch, followed by resubmission.
- Approved loans transition to `Ready for Disbursement` and store approver/date.
- Approval and disbursement remain separate; no account or money movement is implemented in this phase.
- Dedicated approval, manager-approval and auto-approval permissions integrated into existing roles.
- Approval settings added to the standardized Business Settings form.
- Audit logging and permanent loan status history for approval workflow events.

Database changes:

- `businesses.loan_approval_mode`
- `businesses.maker_checker_enabled`
- `businesses.manager_approval_threshold`
- `loans.approved_at`
- `loans.approved_by`
- `loan_approval_decisions`

Main routes/endpoints added:

- Branch-scoped loan approval queue.
- Approval decision posting.
- Additional collateral response posting.
- Existing loan transition endpoint integrated with required/automatic approval mode.

Automated coverage includes:

- Approval-required workflow through `Ready for Disbursement`.
- Reviewer correction/document/additional-collateral/rejection actions.
- Required reviewer comments for non-approval decisions.
- Maker-Checker enforcement.
- Manager approval threshold enforcement.
- Authorized auto-approval permission behavior.
- Approval queue permission and branch isolation.
- Approval settings and standardized UI rendering.

Test result at implementation verification:

- 58 tests passed.
- 379 assertions passed.

Remaining for Step 6:

- None. Financial accounts and accounting foundation are implemented in Step 7. Actual loan disbursement remains Step 8.

---

# STEP 7 — FINANCIAL ACCOUNTS AND ACCOUNTING FOUNDATION

Before disbursement, implement financial accounts.

Account types:

- Cash
- Mobile Money
- Bank
- Petty Cash
- Safe
- Collection
- Other

Each account stores:

- Name
- Account type
- Branch
- Opening balance
- Current balance
- Status
- Account/reference details

Create account transaction ledger.

Every transaction shows:

- Date
- Reference
- Type
- Description
- Money in
- Money out
- Running balance
- User
- Branch
- Related record

Implement business capital injection.

Capital must increase funds but NOT income.

Create accounting-ledger infrastructure capable of distinguishing:

- Assets
- Capital
- Principal
- Interest
- Fees
- Penalties
- Expenses
- Payroll
- Write-offs

Implement account transfers.

Example:

M-Pesa → CRDB

M-Pesa decreases.

CRDB increases.

Total business funds remain unchanged.

Transfers must run inside database transactions.

Add concurrency protection.

Add tests.

### Implementation Status — COMPLETED (12 August 2026)

Step 7 has been implemented in the application.

Implemented:

- Branch-scoped financial accounts for Cash, Mobile Money, Bank, Petty Cash, Safe, Collection and Other account types.
- Account name, branch, opening balance, current balance, status and account/reference details.
- Fixed-precision balance calculations through the existing `MoneyMath` service; no floating-point posting logic is used for balance mutation.
- Opening balances are posted as balanced `Assets` debit and `Capital` credit entries rather than income.
- Permanent account transaction statements with system-generated `FTX-{BRANCH}-{YEAR}-000001` transaction numbers.
- Statements preserve posting order and show date, reference, type, description, money in, money out, running balance, user, branch and related source record.
- Permanent business-capital source records with system-generated `CAP-...` numbers.
- Capital injection atomically increases the selected account, creates an account transaction and balanced `Assets`/`Capital` journal entries, and never posts capital as income.
- Accounting ledger infrastructure supports `Assets`, `Capital`, `Principal`, `Interest`, `Fees`, `Penalties`, `Expenses`, `Payroll` and `Write-offs` categories for this and later phases.
- Permanent account transfers with system-generated `TRF-...` numbers and linked source/destination account transactions.
- Transfers credit the source asset and debit the destination asset so total company funds and profit remain unchanged.
- All financial posting occurs inside database transactions.
- Balance-changing operations use database row locks; multi-account transfers lock accounts in deterministic ID order for concurrency/deadlock protection.
- Insufficient-funds transfers fail before any account, transaction, transfer or ledger mutation is committed.
- Backend branch and permission enforcement applies to account lists, statements, capital posting, transfers and the accounting ledger.
- No financial-account delete route is exposed, protecting transaction/ledger history from hard deletion.
- Audit logging is implemented for account creation/update, capital injection and account transfers.
- Standardized table/form UI is used for financial account lists/forms, account statements, capital injection, transfers and the accounting ledger.

Database changes:

- `financial_accounts`
- `capital_injections`
- `financial_transfers`
- `financial_account_transactions`
- `accounting_entries`

Main routes/endpoints added:

- Financial account list, create, view and edit/update.
- Business capital injection form and posting endpoint.
- Financial account transfer form and posting endpoint.
- Branch-scoped accounting ledger browser.

Automated coverage includes:

- Opening balance accounting and non-income treatment.
- Permanent capital source records and capital/accounting traceability.
- Capital injection balance and journal posting.
- Transfer debit/credit balance changes and preservation of total company funds.
- Atomic rejection of insufficient-funds transfers.
- Backend branch and permission isolation.
- Related-record traceability in account statements.
- Standardized Step 7 list/form UI rendering.

Test result at implementation verification:

- 64 tests passed.
- 441 assertions passed.

Remaining for Step 7:

- None. Loan disbursement remains Step 8 and is intentionally not implemented in this phase.

---

# STEP 8 — LOAN DISBURSEMENT

Implement loan disbursement.

Only loans with:

Ready for Disbursement

may be disbursed.

If signed-contract requirement is enabled, block disbursement unless signed contract exists.

User selects:

- Loan
- Amount
- Financial account
- Date
- Reference
- Notes

Disbursement must:

1. Decrease selected financial account
2. Create financial transaction
3. Create accounting entry
4. Store disbursement record
5. Activate loan
6. Generate repayment schedule
7. Generate disbursement receipt
8. Trigger appropriate notification

Prevent:

- Double disbursement
- Disbursement of rejected loan
- Disbursement without permission
- Insufficient account balance
- Contract bypass

Use a database transaction.

Add tests.

### Implementation Status — COMPLETED (12 August 2026)

Step 8 has been implemented in the application.

Implemented:

- Branch-scoped disbursement queue containing only loans with `Ready for Disbursement` status.
- Dedicated `loans.disburse` backend permission kept separate from loan approval permissions.
- One permanent disbursement per loan, enforced both by workflow validation and a unique database relationship.
- System-generated branch/year disbursement numbers in the format `DSB-{BRANCH}-{YEAR}-000001`.
- Disbursement amount must exactly match the approved loan principal using fixed-precision `MoneyMath` comparison.
- Selected financial account must be active and belong to the same branch as the loan.
- Business `Require Signed Contract Before Disbursement` setting is enforced on the backend; UI disabling alone cannot bypass it.
- Rejected, non-ready, already-disbursed and contract-incomplete loans are blocked before financial posting.
- Full disbursement runs inside a database transaction with row locking on the loan and selected financial account.
- Selected financial account balance decreases atomically and creates a linked permanent financial-account transaction.
- Balanced accounting journal posts an `Assets` credit for funds leaving the account and a `Principal` debit for loan principal receivable; disbursement is not treated as an expense or income event.
- Permanent `loan_disbursements` source records link the loan, branch, account, amount, date, reference, notes, user and financial transaction.
- The persisted approved repayment schedule is activated at disbursement instead of recalculating from potentially changed product settings.
- Loan status changes from `Ready for Disbursement` to `Active`, with disbursed/activated/schedule-activated timestamps and permanent status history.
- Printable business-branded loan disbursement receipt with customer/staff acknowledgement areas.
- A real in-system database notification is triggered for the customer after successful disbursement. SMS, WhatsApp and email provider delivery remain Step 11.
- Disbursement list/history, posting form and receipt are branch-scoped and permission-protected.
- Audit logging records each completed disbursement.
- No disbursement delete route is exposed; financial and source history remains permanent.
- Loan-payment allocation and repayment collection are intentionally not implemented in this phase.

Database changes:

- `notifications`
- `loan_disbursements`
- `loans.disbursed_at`
- `loans.disbursed_by`
- `loans.activated_at`
- `loans.schedule_activated_at`

Main routes/endpoints added:

- Branch-scoped ready-for-disbursement queue and disbursement history.
- Loan disbursement form.
- Atomic disbursement posting endpoint.
- Printable disbursement receipt.

Automated coverage includes:

- Successful account deduction, financial transaction and balanced accounting posting.
- Loan activation and persisted repayment-schedule activation.
- System-generated disbursement number and receipt rendering.
- In-system customer notification creation.
- Signed-contract requirement and bypass prevention.
- Rejected/non-ready loan blocking.
- Double-disbursement prevention without a second account deduction.
- Exact approved-principal validation.
- Atomic insufficient-funds rejection.
- Backend disbursement permission and branch isolation.
- Standardized Step 8 list/form UI rendering.

Test result at implementation verification:

- 71 tests passed.
- 522 assertions passed.

Remaining for Step 8:

- None. Office loan repayment processing and payment allocation remain Step 9 and are intentionally not implemented in this phase.

---

# STEP 9 — LOAN PAYMENTS

Implement complete repayment processing.

Allow office payment search by:

- Loan number
- Customer number
- Customer name
- Phone number

Cashier enters:

- Amount
- Date
- Method
- Receiving account
- Reference
- Notes

Payment posting must:

1. Increase receiving account
2. Update loan
3. Update repayment schedule
4. Allocate principal
5. Allocate interest
6. Allocate fees
7. Allocate penalties
8. Update outstanding amount
9. Update customer statement
10. Update accounting ledger
11. Update daily collections
12. Generate receipt

Support:

- Partial payments
- Exact installment payments
- Multiple-installment payments
- Larger-than-installment payments

Create unique receipt number.

Example:

REC-DOM-2026-001245

IMPORTANT:

Principal repayment must NOT be counted as profit.

Add extensive financial tests.

### Implementation Status — COMPLETED (12 August 2026)

Step 9 has been implemented in the application.

Implemented:

- Branch-scoped office payment search by loan number, customer number, customer name and phone number.
- Only active loans can receive office payments; direct posting and search results both enforce backend branch permissions.
- Cashier payment entry supports amount, date, method, receiving financial account, reference and notes.
- System-generated branch/year receipt numbers in the format `REC-{BRANCH}-{YEAR}-000001`.
- All payment and allocation calculations use the fixed-precision `MoneyMath` service; no floating-point values are used for financial posting.
- Payments allocate to the oldest unpaid installments first, with deterministic component priority `Penalties → Fees → Interest → Principal` within each installment.
- Permanent component-level installment balances track principal paid, interest paid, fees paid, penalty due and penalty paid.
- Partial payments, exact-installment payments, multi-installment payments and payments larger than one installment are supported and reconcile exactly.
- Payments greater than the total current outstanding amount are rejected before any account, schedule, statement or accounting change is committed.
- Receiving account balance increases atomically and receives a permanent linked `loan_payment` financial-account transaction.
- Each payment creates a balanced accounting journal: `Assets` is debited for the full cash received, while `Principal`, `Interest`, `Fees` and `Penalties` are credited separately according to the actual allocation.
- Principal recovery reduces principal receivable and is never classified as income/profit; only the separate interest, fees and penalties categories are available as earned-income components for later reports.
- Loan-level principal, interest, fees, penalties, total outstanding and total-paid balances are persisted and updated after every payment.
- A final fully allocated payment automatically changes the loan from `Active` to `Completed`, records completion time and writes permanent loan lifecycle history.
- Permanent `loan_payments` source records store receipt, loan, customer, branch, account, amount, allocation totals, date, method, reference, notes, receiver and account transaction.
- Permanent `loan_payment_allocations` records preserve the per-installment component allocation of every payment.
- Customer statement entries are created at disbursement and every payment adds a credit with the resulting running loan balance.
- Existing active/disbursed loans are backfilled with outstanding balances and opening statement obligations during the Step 9 migration.
- Daily collection summaries aggregate amount, principal, interest, fees, penalties and payment count by branch, account and date.
- Printable business-branded loan payment receipts show the component allocation and remaining balance.
- Loan statement screens show permanent debit/credit history, running balance, installment component progress and receipt history.
- Payment forms and history use the existing standardized compact table/form UI patterns.
- `payments.receive` remains the dedicated posting permission; receipt/statement viewing uses loan-view permission.
- Audit logging records each successfully posted office payment and its component totals.
- No payment delete route is exposed; payment, allocation, financial-account, accounting and statement history remain permanent.
- Remote payment submission/verification is intentionally not implemented in this phase.

Database changes:

- `loans.principal_outstanding`
- `loans.interest_outstanding`
- `loans.fees_outstanding`
- `loans.penalties_outstanding`
- `loans.total_outstanding`
- `loans.total_paid`
- `loans.last_payment_at`
- `loans.completed_at`
- `loan_installments.principal_paid`
- `loan_installments.interest_paid`
- `loan_installments.fees_paid`
- `loan_installments.penalty_due`
- `loan_installments.penalty_paid`
- `loan_payments`
- `loan_payment_allocations`
- `customer_statement_entries`
- `daily_collections`

Main routes/endpoints added:

- Branch-scoped office loan search and recent payment history.
- Active-loan payment posting form.
- Atomic loan payment posting endpoint.
- Printable loan payment receipt.
- Loan/customer running statement and repayment-progress view.

Automated coverage includes:

- Partial payment allocation and account/loan/installment updates.
- Exact-installment and multi-payment loan completion.
- Larger-than-installment payments spanning multiple installments.
- Penalty-first allocation priority.
- Fixed-precision principal/interest/fees/penalties accounting separation.
- Verification that principal recovery is not posted as capital or income.
- Customer statement and running balance updates.
- Daily collection aggregation.
- Unique receipt generation and printable receipt rendering.
- Atomic overpayment rejection.
- Backend payment permission and branch isolation.
- Standardized Step 9 form/statement rendering.

Test result at implementation verification:

- 78 tests passed.
- 603 assertions passed.

Remaining for Step 9:

- None. Remote payment submission and verification remain Step 10 and are intentionally not implemented in this phase.

---

# STEP 10 — REMOTE PAYMENTS

Implement remote loan payment submission.

Customer/staff can submit:

- Loan
- Amount
- Payment channel
- Transaction reference
- Screenshot/receipt
- Notes

Status:

Pending Verification

Authorized employee can:

- Approve
- Reject

Only approved payment changes financial balances.

Prevent duplicate approval.

Reuse the same payment-posting service used by office payments.

Prepare a payment-provider abstraction for future:

- M-Pesa
- Airtel Money
- Mixx by Yas
- Bank APIs
- Other payment gateways

Add tests.

---

# STEP 11 — REMINDERS AND NOTIFICATIONS

Implement automated loan reminders.

Default sequence:

3 days before
→ reminder

1 day before
→ reminder

Due date
→ payment due notification

1 day overdue
→ overdue notification

Continued overdue
→ configurable reminder frequency

Support:

- Daily
- Every 2 days
- Every 3 days
- Weekly

Notification channels:

- SMS
- WhatsApp
- Email
- In-system

Create notification templates.

Create notification logs.

Store:

- Recipient
- Customer
- Loan
- Message
- Channel
- Date
- Status
- Provider response
- Error

Handle failed notifications.

Do not mark failed notifications as delivered.

Avoid duplicate reminder sending.

Implement scheduled jobs and tests.

---

# STEP 12 — ARREARS AND PENALTIES

Implement overdue-loan management.

Buckets:

- 1–7 days
- 8–30 days
- 31–60 days
- 61–90 days
- 90+ days

Show:

- Customer
- Phone
- Branch
- Loan Officer
- Outstanding principal
- Interest
- Fees
- Penalties
- Total overdue
- Days overdue
- Collateral

Implement penalties:

- Fixed
- Percentage
- Daily percentage
- Weekly percentage

Avoid duplicate penalty calculation.

Implement collection follow-up records:

- Called
- SMS
- Visit
- Promise to pay
- Guarantor contacted
- Demand notice
- Other

Store notes, employee and promise date.

Add automated overdue-update jobs.

Add tests.

---

# STEP 13 — LOAN TOP-UP

Implement complete Loan Top-Up.

Example:

Old loan total = 100,000

Paid = 80,000

Outstanding = 20,000

New principal = 120,000

New interest = 10,000

Expected:

20,000 of new principal settles old loan.

Customer physically receives:

100,000

New loan principal remains:

120,000

New total repayment:

130,000

Old loan status:

Closed Through Top-Up

Store:

- Previous loan
- Previous outstanding
- Amount settled internally
- New loan
- New principal
- Interest
- Total
- Cash actually given to customer

Implement configurable eligibility:

- 50%
- 70%
- 80%
- Custom percentage

Allow authorized override with audit record.

Top-up must use proper accounting entries.

Add comprehensive tests.

---

# STEP 14 — EARLY SETTLEMENT AND RESTRUCTURING

Implement early settlement.

Calculate:

- Outstanding principal
- Interest
- Fees
- Penalties
- Settlement adjustment
- Final amount

When fully paid:

Loan = Fully Paid

If collateral exists:

Collateral = Ready for Release

Implement restructuring.

Allow authorized staff to:

- Extend term
- Change installment amount
- Move repayment dates

Never delete original schedule.

Store:

- Previous schedule
- New schedule
- Reason
- Documents
- Approved by
- Date

Add tests.

---

# STEP 15 — LOAN WRITE-OFF

Implement write-off.

Only authorized management can perform it.

Require:

- Loan
- Write-off amount
- Reason
- Supporting documents
- Approval

Do NOT delete loan.

Status:

Written Off

Preserve:

- Customer
- Loan
- Original amount
- Payments
- Remaining balance
- Collateral
- Collection history
- Write-off information

Implement recovery of written-off loans.

If customer later pays:

Record as Written-Off Loan Recovery.

Keep original write-off history.

Update accounting correctly.

Add tests.

---

# STEP 16 — EXPENSE MANAGEMENT

Implement expenses.

Fields:

- Category
- Description
- Amount
- Date
- Branch
- Paid-from account
- Supplier
- Receipt
- Entered by
- Approved by
- Notes

Posting approved expense must:

1. Reduce selected account
2. Create account transaction
3. Create ledger entry
4. Appear in P&L

Create configurable expense categories.

Implement recurring expenses.

Support reminder for:

- Rent
- Internet
- Security
- Software
- Insurance
- Other

Add tests.

---

# STEP 17 — PAYROLL

Implement payroll.

Employee components:

- Basic salary
- Allowances
- Bonus
- Commission
- Overtime
- Deductions
- Advances
- Other deductions

Calculate:

Gross = Basic + Allowances + Bonus + Commission + Overtime

Net = Gross - Deductions - Advances - Other deductions

Create payroll periods.

Implement payroll approval and payment.

During payment:

- Select account
- Reduce account balance
- Post accounting entry
- Post expense
- Prevent double payment
- Generate payslip

Payslip must be printable/PDF.

Add tests.

---

# STEP 18 — CASH RECONCILIATION AND DAILY CLOSING

Implement cashier reconciliation.

Calculate:

Expected Cash

vs

Physical Cash

\=

Variance

Require explanation for variance.

Store permanent reconciliation history.

Implement branch end-of-day closing.

Report:

- Opening funds
- Collections
- Cash collections
- Mobile-money collections
- Bank collections
- Disbursements
- Expenses
- Transfers
- Closing funds
- Expected cash
- Actual cash
- Variance

Require manager confirmation.

Add tests.

---

# STEP 19 — FINANCIAL REPORTS

Implement actual reports from transaction data.

Build:

1. Profit & Loss
2. Cash Flow
3. Account Statement
4. Capital Report
5. Expense Report
6. Payroll Report
7. Collection Report
8. Disbursement Report

P&L income:

- Interest
- Fees
- Penalties
- Service income
- Other actual income

Do NOT include loan principal recovery as revenue.

Support:

- Date range
- Branch
- Several branches
- Entire company

Add reconciliation tests.

---

# STEP 20 — LOAN AND BRANCH REPORTS

Implement:

1. Active Loan Portfolio
2. Outstanding Principal
3. Outstanding Interest
4. Due Today
5. Overdue Loans
6. Completed Loans
7. Written-Off Loans
8. Loan Collection Rate
9. Branch Performance
10. Consolidated Company Performance
11. Loan Officer Performance
12. Collateral Report
13. Top-Up Report
14. Restructuring Report
15. Write-Off Recovery Report

Allow filters and exports.

---

# STEP 21 — MANAGEMENT DASHBOARD

Build the main owner dashboard using real data.

Show:

- Total Available Funds
- Outstanding Principal
- Expected Interest
- Collections Today
- Disbursements Today
- Expenses Today
- Overdue Amount
- Profit This Month
- Active Loans
- Completed Loans
- Written-Off Portfolio

Show account balances:

- Cash
- Mobile Money
- Bank
- Other

Charts:

- Collections
- Disbursements
- Income vs Expenses
- Portfolio Performance
- Branch Performance

Filters:

- Today
- Yesterday
- This Week
- This Month
- This Year
- Custom Range
- Branch
- Multiple Branches
- Entire Company

Dashboard numbers must reconcile with reports.

---

# STEP 22 — TASKS, CALENDAR AND MANAGEMENT ALERTS

Implement tasks.

Statuses:

- Pending
- In Progress
- Completed
- Cancelled

Allow assignment to staff.

Automatically create collection tasks where configured.

Implement calendar containing:

- Loan due dates
- Maturity
- Tasks
- Customer appointments
- Payroll
- Expense due dates
- Document expiries

Implement management alerts:

- Large loan
- Large expense
- Overdue threshold
- Low account balance
- Cash shortage
- Pending approval
- Write-off request
- Collateral ready for release
- Expiring documents

---

# STEP 23 — GLOBAL SEARCH

Implement global search.

Search:

- Customer
- Phone
- NIN
- Customer number
- Loan number
- Collateral number
- Receipt number
- Payment reference

Respect branch and user permissions.

Make result navigation immediate.

---

# STEP 24 — FINAL DOCUMENTS AND EXPORTS

Complete generation of:

- Loan agreements
- Receipts
- Statements
- Collateral receipts
- Collateral release acknowledgement
- Disbursement receipts
- Expense vouchers
- Payslips

Implement PDF/print.

Implement CSV/spreadsheet export where suitable for reports.

Use actual configured company branding.

---

# STEP 25 — SECURITY AND BACKUP REVIEW

Perform full security review.

Verify:

- Authentication
- Password hashing
- Authorization
- Branch isolation
- 2FA support
- Login monitoring
- Session security
- File upload security
- Sensitive document protection
- CSRF protection
- Rate limiting
- Input validation
- SQL/injection protection
- Audit logs
- Financial transaction protection

Implement backup procedures for:

- Database
- Customer documents
- Contracts
- Receipts
- Collateral files
- Financial documents

Document restore procedure.

---

# STEP 26 — COMPLETE INTEGRATION TEST

Now test the whole application as one system.

Create:

- Business
- Two branches
- Multiple users
- Multiple roles
- Cash account
- M-Pesa account
- Bank account

Inject business capital.

Register customer.

Upload KYC.

Register collateral.

Create loan product.

Create loan application.

Generate agreement.

Upload signed agreement.

Approve loan.

Disburse loan.

Verify account deduction.

Verify repayment schedule.

Receive partial payment.

Verify receipt.

Verify account increase.

Verify principal/interest separation.

Test remote payment.

Test reminder.

Make loan overdue.

Test penalty.

Test collection follow-up.

Test top-up.

Test early settlement.

Test restructuring.

Test write-off.

Test written-off recovery.

Create expense.

Process payroll.

Transfer accounts.

Reconcile cash.

Perform daily closing.

Release collateral.

Generate reports.

Check dashboard.

Verify P&L.

Verify cash flow.

Verify branch isolation.

Verify audit logs.

Fix every failure.

Do not declare the application complete until all critical flows pass.