# TREVO API: Architecture (Phase 1)

## Layers
Controllers/API → Form Requests → Services → Models. Controllers hold no business logic.
All money moves only through `WalletService`.

## Money model
- `wallets`: `available` and `reserved` (decimal 18,2; DB CHECK >= 0 on MySQL).
- `wallet_transactions`: append-only ledger (model blocks update/delete), unique `reference` = idempotency key.
- Order flow: `reserve` → provider → `capture` (successful items) + `release` (failed items).
- Packages are a separate entitlement (`user_packages`): validity, quota, rate limit, allowed services.
  Buying one debits the wallet once (idempotent on `purchase_reference`).

## Deposits
`PaymentGatewayInterface` + `NullGateway`. No gateway is selected, so deposits refuse to start.
`DepositService::settleVerified` credits only the amount stored on our own deposit row, and only if a
server-verified payment matches reference, currency and amount. Otherwise `manual_review`, no credit.
Callback replays are deduped through `payment_gateway_events (gateway, event_id)`.

## Phases
1. **Foundation (done):** schema, wallet ledger, packages, deposit settlement core, tests.
2. **Auth + reseller panel shell (done, untested):** register/login/logout, password reset, optional email verification, dashboard, wallet history, package store + purchase, deposit history, Add Money (disabled until a gateway exists), account/security, honest placeholder pages for later sections.
3. **Reseller API foundation (done, untested):** API keys (SHA-256 hashed, rotate/disable/delete), IP allowlist, `/api/v1` auth + rate limits + JSON error envelope + request logs, `GET /balance|/packages|/services`. Order idempotency arrives with Phase 4.
4. **Catalog, pricing, orders (done, untested):** products + package pricing, idempotent order placement with reserve, item-level settlement (capture/release), order status API + panel history. Provider adapter intentionally absent.
5. **Pinbot adapters (done, untested, disabled by default):** Unipin + Shell submit, callback receiver, lookup-based reconciliation, voucher inventory. See `docs/PROVIDER.md`.
6. **Admin panel (done, untested):** least-privilege roles, audit trail, reseller/wallet/deposit/order/voucher/catalog/package/API-key management, tickets, announcements, settings + maintenance mode, provider status. See `docs/ADMIN.md`.
7. **Reseller webhooks, in-panel API reference, hardening, deployment guide (done, untested):** see `docs/WEBHOOKS.md` and `docs/DEPLOYMENT.md`.

## Needed from the owner (blocking for later phases)
- Payment gateway name + official docs (before real deposits).
- Pinbot API docs confirmation: callback authentication, whether HTTPS is supported (Phase 5).
- Pricing, min/max deposit, refund policy, and whether each service requires package, wallet, or both (Phase 4).
- Unipin voucher stock/source and Shell account details only if those methods are enabled (Phase 5).

## Known limits
- SQLite (used by default in Laravel tests) ignores `lockForUpdate`, so row-lock concurrency must be
  verified against MySQL before launch. Idempotency and balance rules are still tested.
- `users.role` is a simple column for now; Phase 6 may swap in spatie/laravel-permission.

## Phase 2 notes
- Auth is hand-written (no Breeze/Fortify) to avoid extra dependencies: `LoginRequest` rate-limits 5 attempts per email+IP,
  `RegisterRequest::userData()` is a whitelist so `role`/`status` can never be mass-assigned,
  `EnsureUserIsActive` signs out suspended users on their next request.
- Panel pages are always scoped by `user_id = auth()->id()`; there are no `{id}` routes to other users' data.
- Package purchase forms carry a per-render UUID idempotency key; double-submits cannot double-charge.
- Add Money goes through `DepositService::initiate`; with `NullGateway` it refuses and creates nothing.
- Pages for API keys, usage, orders, API docs, support and announcements are labelled placeholders, with no fake data.

## Phase 3 notes
- **Routing:** `routes/api_v1.php` is loaded by `TrevoServiceProvider` under `/api/v1` with *no* `web` group (no sessions, cookies, CSRF). `bootstrap/app.php` is untouched.
- **Middleware chain:** `ApiRequestContext` (request id, per-IP flood limit, error normalisation, logging) → `AuthenticateApiKey` (bearer parse, hash lookup, status/verification/IP checks, failed-auth limiter) → `ApiRateLimit` (per reseller).
- **Error safety:** every 4xx/5xx is rewritten into the TREVO envelope, so debug pages, stack traces or framework messages cannot reach clients.
- **Keys:** `trv_<8 hex prefix>_<40 alnum>`; lookup by prefix, constant-time compare of SHA-256. Soft delete keeps log references while the key stops authenticating.
- **Logs:** `api_request_logs` stores metadata only (no headers, bodies, query strings, keys). Prune with `php artisan trevo:prune-api-logs` (schedule it daily).
- **Secrets:** Pinbot settings exist in `config/trevo.php` but nothing reads them yet; a test asserts they never appear in API output or logs.
- **Services:** the `services` table + inactive seed rows hold the catalogue. Pricing/products and order endpoints are Phase 4.
- **Assumption to confirm:** a package with empty `allowed_services` covers every service.

## Phase 4 notes
- **Order placement (`OrderService::place`)** is one transaction: lock reseller → idempotency check → service/provider/entitlement checks → server-side quote → quota unit → order + items → `WalletService::reserve`. Any rejection rolls everything back (no order, no hold, quota intact). The provider job is queued only after commit.
- **Idempotency:** unique `(user_id, idempotency_key)` + request fingerprint. Same key + same request = replay; same key + different request = 409. Rejected attempts leave no row, so a key can be retried after fixing e.g. funds.
- **Settlement (`OrderSettlementService`)** is the only code that resolves order money: item-level outcomes → capture successes, release failures. Final states are immutable and re-settling is a no-op. Failure codes are normalised to snake_case so raw provider text never persists.
- **Uncertain outcomes** (`SubmitTopupOrder` error/timeout) → `manual_review` with funds still reserved. The job has `tries = 1`; it is never retried automatically.
- **Provider boundary:** `ProviderGateway` (provisional) is bound to `NullProvider`, which makes `POST /orders/*` return 503 *before* reserving anything. Phase 5 supplies the Pinbot adapter and reports outcomes through `OrderSettlementService`.
- **Catalog:** `products.price` (nullable) is the base sell price; NULL = not orderable. `product_prices` holds cheaper per-package prices; the lowest applicable price wins. Nothing is priced or active by default; `ProductSeeder` only lists the Unipin denominations from the brief (inactive, unpriced). **No Shell products** are seeded because the brief gives no package codes.
- **Assumptions awaiting owner confirmation:** quota counts accepted *orders* and a fully failed order gives its unit back; a package with empty `allowed_services` covers all services; max 5 units per order for every service; UID pattern `^[0-9]{5,15}$`.
- **Not designed yet (needs owner input):** where Unipin voucher codes come from (stock/inventory), Shell package codes and account credentials, refund policy, whether wallet funds are required for every service.

## Phase 5 notes
- **Fail-closed by design:** the provider reply format is not in the brief, so `PinbotResponseParser` accepts only what the brief names (per-item boolean `ok`, a top-level `status`) and treats everything else as *unknown*: the order stays `processing` or goes to `manual_review`, funds untouched. Real samples are required before go-live.
- **Claim-before-send:** `processing` + `submitted_at` + voucher allocation commit before the HTTP call. After that point an order is only ever resolved by lookup, never re-sent.
- **Callbacks are triggers, not truth:** unauthenticated by nature, so they only enqueue an authenticated `GET /search`; money moves only from that lookup.
- **Outcome mapping:** provider items map to order items positionally (ascending item id). Count mismatch = unknown.
- **Vouchers:** allocated at send time (stock is only *checked* at placement); if stock vanished in between, the order fails definitively (`out_of_stock`) and funds are released, since nothing was sent.
- **Scheduling:** registered in `TrevoServiceProvider` (`trevo:reconcile-orders` every 5 min, `trevo:prune-api-logs` daily); needs the Laravel scheduler running.
- **Provider binding:** `PINBOT_ENABLED=false` => `NullProvider` (503). Enabled => `PinbotProvider`, which still reports unavailable per service if configuration is incomplete.

## Phase 6 notes
- **Two gates per admin route:** `EnsureAdmin` (active admin, otherwise 404) then `EnsureAdminPermission:<perm>` (otherwise 403). `super_admin` implicitly holds every permission; `admins.manage` is not grantable (route middleware `:super`).
- **Services own the rules:** each admin operation is a service method taking the acting admin and calling `AuditLogger` inside the same DB transaction. Controllers only validate input and translate `AdminActionException` into flash errors.
- **Refund** (`OrderSettlementService::refundCaptured`): whole captured amount, once, wallet reference `order:{id}:refund`; status becomes `refunded` (final).
- **Deposit approval** reuses the normal wallet reference `deposit:{id}`, so manual approval and a late genuine gateway confirmation can never both credit.
- **Wallet adjustments** use reference `admin-adjust:{user}:{form key}`; resubmits return the original posting and are not audited twice.
- **Maintenance mode** is a cached `system_settings` flag enforced by `EnforceMaintenanceMode` (panel) and `ApiRequestContext` (API). Secrets are not settings; they stay in the environment.
- **Support:** tickets are scoped to the owner (404 otherwise); messages are plain text, escaped on output; closed tickets need a staff reopen.
- **Not in Phase 6:** 2FA for admins, email notifications for tickets (no mail pipeline is assumed), admin-side refunds of wallet *deposits*, bulk actions, CSV export.

## Phase 7 notes
- **Webhooks** (`WebhookService` queues, `WebhookSender` delivers): deliveries are rows, sent by a job and retried on a schedule with backoff. The claim window (`next_attempt_at` +5 min) stops the dispatcher re-sending while a job is queued.
- **Hooks:** `OrderSettlementService` notifies only after a real state change, once the transaction has committed (`$done = DB::transaction(...)` then `notify`). Duplicate callbacks produce no extra deliveries.
- **SSRF protection:** `UrlGuard` checks scheme, port, credentials, host and every resolved address; the sender pins the checked IP via `CURLOPT_RESOLVE`.
- **Security headers:** `SecurityHeaders` is pushed onto the `web` group in `TrevoServiceProvider`. No CSP yet.
- **Admin IP allowlist:** `EnsureAdminIp` runs first in the admin group, so non-allowlisted addresses get 404 even before the login redirect.
- **Removed:** the `PlaceholderController` and its view; no panel page is a placeholder any more.
