# Fines, Arrears, and Amount Due

This document explains how LendCore tracks fines, arrears, and amount due, and which main code paths handle each concept.

## 1. Amount Due

### Meaning
- `amount_due` is the expected obligation for a single repayment installment.
- It is the base payable amount for that repayment period.
- It does not include any fine or penalty.

### Where it is defined
- Main source: `app/Services/LoanService.php`
- The repayment schedule is generated by `LoanService::generateRepaymentSchedule()`.
- Each repayment record is created as:
  - `amount_due` = installment amount for that period
  - `amount_paid` = 0
  - `balance` = `amount_due`
  - `status` = `pending`

### How it is used
- `app/Models/Repayment.php` stores `amount_due` as a decimal field.
- `app/Services/RepaymentService.php` uses it to compute repayment balance:
  - `balance = amount_due - amount_paid`
- If a repayment has a fine, the total owed for that installment becomes:
  - `repayment.balance + fine.amount`

### Main code paths
- `app/Services/LoanService.php` — generates the repayment schedule and assigns `amount_due` values.
- `app/Services/RepaymentService.php` — updates payment allocation and balance using `amount_due`.
- `app/Http/Resources/RepaymentResource.php` — exposes `amount_due` in API responses.

## 2. Arrears

### Meaning
- `arrears` is a loan-level summary of overdue unpaid installment balances.
- It is not a separate extra penalty charge.
- It represents overdue repayment balances only.

### Where it is calculated
- Main source: `app/Models/Loan.php`
- Loan model accessor: `Loan::getArrearsAttribute()`
- It sums repayment balances where:
  - repayment status is `pending` or `overdue`
  - `due_date` is before today

### What it includes
- overdue installments that still have remaining balance
- only principal installment balance, not fine amount

### Main code paths
- `app/Models/Loan.php` — defines the loan-level `arrears` attribute.
- `app/Services/LoanService.php` and reporting code read this attribute when building loan summaries.
- `app/Http/Resources/LoanResource.php` may expose loan totals based on repayment values.

## 3. Fines

### Meaning
- A fine is a late-payment penalty attached to a repayment.
- It is stored in `app/Models/Fine.php` and belongs to a specific repayment.
- Fines are separate from the scheduled installment amount and from arrears.

### How fines are calculated
- Main source: `app/Services/FineService.php`
- `FineService::calculateFine($repayment)` computes the current display fine using:
  - `days_overdue` from `RepaymentService::getDaysOverdue($repayment)`
  - the installment's remaining balance (`amount_due - amount_paid`)
  - `fine_daily_rate` setting (default 0.5% per day)
- Formula:
  - `fine = remaining_balance * days_overdue * daily_rate / 100`

For legacy-imported loans, `FineService::getRepaymentFineForLoan()` distributes the authoritative `loan->legacy_paid` across installments in due-date order before calculating each installment's remaining balance. This prevents duplicated or stale repayment allocation rows from changing the legacy fine foundation. Normal loans continue using their live repayment `amount_paid` values.

The daily fine configuration is stored in the key/value `settings` table:

- `fine_calculation_mode = percentage` interprets `fine_daily_rate` as a percentage of the remaining installment balance per overdue day.
- `fine_calculation_mode = flat` interprets `fine_daily_rate` as a fixed KSh amount per overdue day, for example `100.00` means KSh 100 per day.
- `fine_daily_rate` defaults to `0.50` and `fine_calculation_mode` defaults to `percentage`, preserving the existing 0.5% behavior.
- The admin settings page validates and updates both values without changing historical loan or repayment records.

### Applying and updating fines
- `FineService::applyFine($repayment)` creates or updates the `Fine` record.
- It will not apply a fine if the repayment is already `paid`.
- `FineService::getFineDetails($repayment)` returns fine amount, days overdue, and total due with fine.
- Applying a fine persists the same mode-aware and legacy-aware amount used by the display layer.

### Payment allocation with fines
- `FineService::captureFineOnPayment($repayment, $amountPaid)` splits payment:
  1. repay repayment balance
  2. pay fine amount
- `RepaymentService::recordPayment()` also follows this allocation order when recording a repayment.

### Admin handling
- `app/Http/Controllers/Admin/FineController.php` manages:
  - list fines
  - show fine details
  - waive or reduce a fine
- Fine waiver is performed via `FineService::waiveFine()`.

### User views and payment flow
- `app/Http/Controllers/Web/UserDashboardController.php` calculates dashboard, loan-detail, and repayment-list fines through `FineService`.
- `app/Http/Controllers/Web/RepaymentController.php` uses the computed fine for repayment details, the payment form, and payment amount validation.
- User loan schedules and repayment tables display the computed fine, including installments without a persisted `Fine` row.
- The payment form's `totalDue` and maximum payment validation include the current computed fine, so percentage and flat modes are applied consistently before payment submission.

### Officer views
- `app/Http/Controllers/Officer/OfficerDashboardController.php` calculates fine totals for officer user details and loan details through `FineService`.
- Officer user details display a total-fines summary and a computed fine for each repayment.
- Officer loan details display computed fines by installment rather than relying only on persisted fine records.
- Legacy officer views use the same due-date-ordered `legacy_paid` distribution as user and admin views.

### Main code paths
- `app/Services/FineService.php` — core fine logic, calculation, application, captures, and waivers.
- `app/Http/Controllers/Admin/FineController.php` — admin UI handling for managing fines.
- `app/Services/RepaymentService.php` — applies payments to repayments and fines.
- `app/Http/Controllers/Web/UserDashboardController.php` — supplies computed fines to user views.
- `app/Http/Controllers/Web/RepaymentController.php` — supplies computed fines to user repayment details and payment validation.
- `app/Http/Controllers/Admin/LoanController.php` and `app/Http/Controllers/Admin/UserController.php` — supply computed fines to admin loan and user views.
- `app/Http/Controllers/Admin/RepaymentController.php` — supplies computed fines to admin repayment details.
- `app/Http/Controllers/Officer/OfficerDashboardController.php` — supplies computed fines to officer views.

## 4. How the main scripts interact

### Loan creation and schedule generation
- `app/Services/LoanService.php`
  - creates `Loan` records
  - computes fees and installment amounts
  - writes repayment rows with `amount_due`

### Overdue / arrears resolution
- `app/Models/Loan.php` calculates `arrears` dynamically from overdue repayments.
- `app/Services/RepaymentService.php` tracks repayment status and overdue days.

### Fine lifecycle
- `app/Services/FineService.php` calculates fine amounts and updates fine records.
- `app/Http/Controllers/Admin/FineController.php` allows admins to view and waive fines.
- `app/Services/RepaymentService.php` routes payment amounts into installment balance first, then fine.
- User and officer display paths calculate current fines from due dates and the configured mode instead of relying solely on stored fine amounts.

### Import-specific handling
- Legacy import code can preserve repayment and loan accounting, but the core concepts remain:
  - `amount_due` is the repayment schedule amount
  - `arrears` is overdue repayment balance
  - `fine` is a repayment-specific penalty
- For legacy-imported loans, user, admin, and officer views use `legacy_paid` as the payment foundation and distribute it across installments by due date before calculating fines.

## 5. Quick reference

| Term | Stored in | Main handler | Includes | Notes |
|---|---|---|---|---|
| `amount_due` | `repayments.amount_due` | `LoanService::generateRepaymentSchedule()` | scheduled installment amount | core repayment obligation |
| `balance` | `repayments.balance` | `RepaymentService` | unpaid portion of `amount_due` | updated by payments |
| `arrears` | computed in `Loan` model | `Loan::getArrearsAttribute()` | overdue repayment balances | loan-level overdue amount |
| `Fine` | `fines.amount` | `FineService` | late penalty on one repayment | separate from `amount_due` and arrears |

## 6. Summary
- `amount_due` defines what each repayment installment should collect.
- `arrears` is the overdue unpaid portion of repayment balances across a loan.
- fines are penalties attached to overdue repayments and are handled separately.
- All three are connected by repayments, with `LoanService`, `RepaymentService`, and `FineService` providing the main logic.
