# Phase 11 — Finance and payment

Phase 11 implements student billing, collection, ledger accounting, verification, and
reconciliation. It stops before transcripts and certificates.

## Delivered

- Institution-owned fee types for tuition, registration, library, technology, and
  arbitrary custom categories.
- Fee schedules scoped by academic session and optionally by semester, programme,
  academic level, and student category.
- Compulsory and optional schedule items, currency, installment permission, and a
  configurable maximum installment count.
- Draft-to-published schedule control.
- Idempotent invoice generation with human-readable and public identifiers.
- Integer-minor-unit monetary storage throughout the finance domain.
- Immutable invoice debits and payment credits in the student ledger.
- Partial payments, installment enforcement, oldest/target-invoice allocation,
  outstanding balances, credit balances, statements, and payment history.
- Scholarships, discounts, waivers, penalties, and brought-forward outstanding
  balances as authorized adjustments with compensating ledger entries.
- Paystack and Flutterwave initialization and server-to-server verification adapters.
- Signed webhook validation, durable webhook evidence, event replay protection, and
  a second authoritative gateway verification before any ledger credit.
- Exact reference, amount, currency, and success-state matching.
- Manual bank and transfer submissions with private, hashed evidence.
- Authorized cash-office, bank, sponsor, and scholarship payment entry.
- Server-verified receipts and printable invoice/receipt views.
- Authorized partial refunds and full payment reversals without deleting history.
- Daily collection, verified revenue, outstanding balance, and student-credit totals.
- Gateway/bank reconciliation with matched totals and persisted exceptions.
- Student and finance-administrator interfaces with institution isolation.

## Payment verification architecture

The browser never marks a payment successful. Online payment initialization creates a
local pending payment with a random unique reference. The gateway receives that
reference and the expected amount/currency.

Callbacks and signed webhooks are only triggers. The server calls the provider's
verification API and compares:

1. successful provider state;
2. local reference;
3. exact integer minor-unit amount; and
4. ISO currency.

Only an exact match enters the transactional completion action. That action locks the
payment, exits idempotently if it was already completed, appends one ledger credit,
allocates the payment, and updates invoice/student financial status. Webhook event IDs
and provider transaction references are unique, preventing replay and duplicate
crediting.

Paystack webhooks use HMAC-SHA512 validation. Flutterwave webhooks require the
configured verification hash. Credentials and verification secrets are loaded only
from environment variables.

## Manual payments and evidence

Students may upload PDF/JPEG/PNG transfer evidence up to 5 MB. Evidence is stored on
the private local disk under an institution-specific path and is only downloadable by
the owning student or authorized finance staff. A finance officer must approve or
reject the submission before ledger credit. Cash-office, sponsor, scholarship, and
bank entries require an authorized staff account and use the same completion action.

## Refunds, reversals, and auditability

No completed financial record is deleted. Refunds create a financial adjustment,
debit the ledger, reduce payment allocations, and restore invoice debt. Full
reversals require `payments.reverse`, a mandatory reason, a compensating ledger debit,
and invoice balance restoration.

## Permissions

- `fees.manage`: fee types, schedules, publication, and invoices.
- `payments.manage`: payment administration and financial adjustments.
- `payments.verify`: manual evidence decisions.
- `payments.reverse`: refunds and reversals.
- `reconciliation.manage`: gateway and bank settlement reconciliation.
- `finance.reports.view`: finance workspace and reports.

All actions also require matching institution ownership. Students can only access
their own invoices, evidence, receipts, payments, and ledger.

## Configuration

Set these only through deployment secrets or environment variables:

```dotenv
PAYSTACK_PUBLIC_KEY=
PAYSTACK_SECRET_KEY=
FLUTTERWAVE_PUBLIC_KEY=
FLUTTERWAVE_SECRET_KEY=
FLUTTERWAVE_WEBHOOK_HASH=
```

Configure provider webhook URLs as:

```text
POST /payments/webhooks/paystack
POST /payments/webhooks/flutterwave
```

## Demonstration data

The development seed creates four fee types, one published installment-enabled
schedule, ten invoices, two fully paid invoices, three partially paid invoices, five
verified payments, ledger entries, and outstanding student balances.

## Verification

- Finance payment tests: 8 passed, 33 assertions.
- Full application suite: 93 passed, 342 assertions.
- Finance migration rollback, reapplication, and reseeding completed successfully.
- Finance and payment route inventories completed successfully.
- Composer audit: no security vulnerability advisories.
- npm audit: zero vulnerabilities.
- Vite production bundle built successfully.

Run this phase locally with:

```powershell
C:\xampp\php\php.exe artisan migrate:fresh --seed
C:\xampp\php\php.exe artisan test --filter=FinancePaymentTest
C:\xampp\php\php.exe artisan test
```

## Phase gate

Phase 11 is complete. Phase 12 (transcripts and certificates) requires explicit
approval before implementation.
