# Payments Module — Branch Performance Upgrade

## Deployment order

1. Back up the application files and MySQL database.
2. Replace the existing `modules/payments` folder with the upgraded `payments` folder.
3. While logged in as an administrator or finance manager, open:
   `modules/payments/install_branch_performance.php`
4. Click **Run Upgrade** once.
5. Open `modules/payments/branch_performance.php` and verify totals for a known date range.
6. Rotate the SMS credentials that were previously stored inside `save_payment.php`.
7. Configure optional SMS environment variables on the server:
   - `SMS_API_KEY`
   - `SMS_CLIENT_ID`
   - `SMS_ACCESS_KEY`
   - `SMS_SENDER_ID`
   - `PAYMENT_SMS_RECIPIENT`

## Main improvements

- New executive branch scorecard and CSV export.
- Multi-branch payments are split from allocation lines instead of assigning the entire payment to one branch.
- Payment-register KPIs use the full filtered dataset; the 500-row display cap no longer limits totals.
- Register branch filtering uses invoice allocations.
- Payment entry captures settlement status.
- Cash/M-Pesa/bank methods default to cleared; cheques default to pending, but the user can change the status before posting.
- New payments automatically store a header branch when all allocations belong to one branch.
- Allocation branch snapshots preserve historical reporting.
- Supplier branch statements use the branch allocation amount rather than the complete payment header.
- Production error display is disabled on the updated core pages.
- SMS secrets are no longer hard-coded.

## Important accounting note

`payments.branch_id` is only a convenience field for single-branch payments. The authoritative source for branch performance is:

`payment_allocations -> invoices -> branch_id`

Unallocated supplier advances cannot be split by invoice branch. They are attributed only when the payment header has an originating branch; otherwise they appear as unassigned.

## Validation checks after deployment

- Pick a payment allocated to invoices from two branches. Confirm the branch dashboard splits it correctly.
- Compare a branch statement payment total with the allocations shown on the payment view.
- Confirm pending cheques appear under pending settlement and cleared payments under cleared.
- Confirm a date range containing more than 500 payments shows correct KPI totals.
- Confirm older payment allocations have `branch_id` populated after running the installer.
