# Build Plan

Derived from [SPEC.md](SPEC.md) §13. Work strictly in phase order. At the end of each phase: run its tests, report pass/fail status and any deviations from spec, and wait before starting the next phase. Commit at each phase boundary (see SPEC §14).

Open decision needed before Phase 0: which real upstream provider ABM Soft is signing with (needed for the Phase 4 adapter's field mapping — not blocking Phases 0-3, which run against `NullProvider`).

---

### Phase 0 — Skeleton
- `composer create-project codeigniter4/appstarter` (or equivalent) into this directory; init git.
- App namespaces per SPEC §1 directory layout under `app/`.
- `.env.example` with every config key the spec introduces (DB, timezone, encryption key, rate limit defaults, provider stub).
- All migrations from SPEC §3 (one file per logical group: tenancy/auth, sender IDs/pricing, credit ledger, messages, providers/routing, webhooks/logs).
- Seeders: 1 test tenant with an API credential, 1 default price plan + rates, `NullProvider` row, a global blacklist example.
- `docs/` structure started (this file, SPEC.md; deployment.md and api.md stubbed for later phases).
- **DoD:** `php spark migrate` clean on empty DB; `php spark db:seed` produces a working test tenant.

### Phase 1 — Core domain services (no HTTP yet)
- `Services/Sms/NumberNormalizer.php`
- `Services/Sms/EncodingDetector.php` (pure, side-effect-free)
- `Services/Billing/RateResolver.php`
- `Services/Billing/CreditService.php` (reserve/charge/refund/reversal, transactional per SPEC §3.3 rules)
- Unit tests for all four, including the CreditService concurrency test (two simultaneous reserves against a balance that covers only one).
- **DoD:** all SPEC §12 unit tests green, including the concurrency test.

### Phase 2 — API auth & scaffolding
- `Filters/ApiAuthFilter.php` (HMAC first, bearer fallback), `Filters/IpWhitelistFilter.php`, `Filters/RateLimitFilter.php`, `Filters/TenantScopeFilter.php`.
- `ErrorCode` enum + response envelope helper.
- `POST /sms/estimate`, `GET /account/balance`.
- `sms_api_logs` request logging (with redaction).
- Postman collection started.
- **DoD:** Postman collection authenticates both ways (bearer + HMAC) and estimate returns correct cost.

### Phase 3 — Send pipeline (against NullProvider)
- `POST /sms/send`, `POST /sms/bulk`, idempotency key handling (`sms_idempotency_keys`).
- `sms_batches` / `sms_messages` write path per SPEC §6 pipeline.
- `spark sms:dispatch` worker command, `NullProvider` adapter.
- `spark sms:simulate --tenant X --count 1000` (space-separated - CI4's CLI parser doesn't support `--flag=value`, see CLAUDE.md).
- **DoD:** 1,000 simulated messages send end-to-end with zero balance drift (verify with `sms:audit-balances`, built here or stubbed).

### Phase 4 — Real provider integration
- `ProviderInterface`, `GenericHttpProvider` (config-driven), one concrete adapter for the confirmed real provider.
- `ProviderManager`: routing (`sms_provider_routes` resolution), failover on 502, circuit breaker.
- Credential encryption (CI4 Encryption) + `redactSecrets()` used by logging.
- **DoD:** live test-send succeeds against the real provider sandbox.

### Phase 5 — DLR & retries
- `Controllers/Webhook/DlrController.php` — log raw payload first, parse second, match by `provider_message_id`.
- Status endpoints: `GET /sms/{message_uuid}`, `POST /sms/status`.
- `spark sms:retry` (retryable errors only — never business rejections).
- **DoD:** DLR updates message status; unmatched DLRs are logged, not lost.

### Phase 6 — Reporting
- `GET /reports/messages`, `GET /reports/summary`, `GET /reports/export` (async CSV via worker).
- `sms_daily_stats` table + `spark sms:aggregate-stats`, incremented live on relevant events.
- **DoD:** summary endpoint returns in <300ms on 1M rows (seed/benchmark this).

### Phase 7 — Outbound webhooks
- `Services/Webhook/OutboundWebhookDispatcher.php`, `spark sms:webhooks`.
- Exponential backoff (1m/5m/15m/1h/6h → degrade endpoint).
- HMAC signing (`X-Abm-Signature`) + verification snippet destined for the SDK.
- **DoD:** test event delivers and verifies with the SDK helper.

### Phase 8 — Admin panel
- Dashboard, tenant CRUD + top-up (ledger `topup` entries) + credit limit + plan assignment + impersonation (audit-logged).
- Sender ID approval queue, provider CRUD/test-send/balance check, price plans, message explorer, ledger explorer + drift report, blacklist management, API log viewer.
- Role-based access: `super_admin`, `support`, `accounts`.
- **DoD:** manual top-up writes a correct ledger entry; sender ID approval works.

### Phase 9 — Tenant portal + i18n
- Dashboard, send SMS (single + CSV bulk), message history/export, reports chart, sender ID request form, API credential management, webhook setup + test event, ledger/top-up history.
- `en` and `bn` language files for every user-facing string.
- **DoD:** a non-technical user can send an SMS and read a report in Bangla.

### Phase 10 — CI3 SDK & docs
- `AbmSms.php` (dependency-free, PHP 7.2+ compatible, cURL only).
- CI3 integration example (`application/config/`, `application/libraries/` wrapper).
- `docs/api.md` (English) + Bangla quick-start, Postman collection finalized, `docs/deployment.md` (supervisor + crontab samples).
- **DoD:** a CI3 app integrates in under 15 minutes using only the docs.

---

## Cross-cutting, apply throughout (not a separate phase)
- Every tenant-owned table query goes through a base-model tenant scope — write the cross-tenant-leak test once in Phase 2 and re-run it as new endpoints land.
- Every money-mutating service method gets a docblock stating its transaction guarantee (SPEC §14).
- Every admin action touching money/credentials/tenant status writes an audit log row (build the audit log table in Phase 0, wire it up starting Phase 8 but usable earlier if needed).
- Nightly cron additions accumulate per phase: `sms:audit-balances` (P3+), `sms:aggregate-stats` (P6), `sms:prune-logs` (P0/logging), `sms:archive` (P3+, low priority).
