# ABM SMS Gateway SaaS — Product & Engineering Spec

Status: **source of truth**. Any change to this document should be a deliberate, called-out decision — not a silent drift during implementation. See [PLAN.md](PLAN.md) for the phased build plan derived from this spec.

## 0. Role & Mission

Senior PHP/CodeIgniter 4 engineering effort building a multi-tenant SMS Gateway SaaS for the Bangladesh market.

**Business model:** ABM Soft holds one (or more) commercial accounts with an upstream Bangladeshi SMS provider. This platform resells that capacity to ~100 bike showroom clients. Each client:

- Gets a tenant account on the SMS platform.
- Buys SMS credit (prepaid).
- Calls our REST API from their existing CodeIgniter 3 bike management system to send SMS.
- Pulls delivery reports via API, or receives them via webhook.

Our platform is the only thing that talks to the upstream provider. Clients never see the provider credentials.

**Non-negotiable properties:**

- Money must never be lost or double-spent. Credit accounting is the highest-risk area in this system.
- One tenant must never be able to read, send as, or bill another tenant.
- The API must be trivially easy to integrate from CI3 (a legacy codebase we do not want to rewrite 100 times).
- Every SMS must be traceable end-to-end: who sent it, what it cost, what the provider said, what the final DLR was.

## 1. Tech Stack

| Layer | Choice |
|---|---|
| Framework | CodeIgniter 4.5+ |
| PHP | 8.2+ |
| DB | MySQL 8 / MariaDB 10.6+, InnoDB, utf8mb4_unicode_ci |
| Queue | DB-backed job table + spark worker under supervisor (Redis optional, behind an interface) |
| Cache/rate-limit | File driver by default, Redis driver swappable via config |
| Frontend (admin + tenant portal) | Bootstrap 5 + server-rendered CI4 views + DataTables. No SPA. |
| HTTP client | CI4 CURLRequest wrapped in our own HttpClient service |
| Table prefix | `sms_` |
| Timezone | Asia/Dhaka everywhere. Store all timestamps in UTC in DB, render in Asia/Dhaka. |

**Directory layout** (namespaces under `app/`):

```
app/
  Config/
  Controllers/
    Api/V1/          <- tenant-facing REST API
    Admin/           <- ABM Soft super-admin panel
    Tenant/           <- client self-service portal
    Webhook/          <- inbound DLR from provider
  Services/
    Sms/              <- SmsSender, MessageBuilder, EncodingDetector, NumberNormalizer
    Billing/          <- CreditService, RateResolver
    Provider/          <- ProviderManager, ProviderInterface, Adapters/
    Webhook/          <- OutboundWebhookDispatcher
  Models/
  Entities/
  Filters/            <- ApiAuthFilter, RateLimitFilter, TenantScopeFilter, IpWhitelistFilter
  Libraries/
  Commands/           <- spark commands for workers
  Database/Migrations/
  Database/Seeds/
```

## 2. Bangladesh-Specific Rules (get these right or the whole thing is wrong)

### 2.1 Number normalization

Accept any of these and normalize to `8801XXXXXXXXX` (13 digits, no `+`):

- `01712345678`
- `1712345678`
- `+8801712345678`
- `8801712345678`
- With spaces, dashes, or brackets.

Reject anything else with a clear error. Valid operator prefixes after 880:

| Prefix | Operator |
|---|---|
| 013, 017 | Grameenphone |
| 014, 019 | Banglalink |
| 015 | Teletalk |
| 016 | Airtel |
| 018 | Robi |

Store the detected operator on the message row — needed for routing and provider-side cost reconciliation.

### 2.2 Encoding & SMS part counting (this drives billing)

| Encoding | Single SMS | Per part when concatenated |
|---|---|---|
| GSM-7 (English) | 160 chars | 153 chars |
| UCS-2 (Bangla / any non-GSM char) | 70 chars | 67 chars |

- Detect encoding by scanning for characters outside the GSM 03.38 basic + extension table.
- GSM-7 extension characters (`^ { } \ [ ] ~ | €`) count as 2 characters.
- If any single character in the body is non-GSM, the entire message becomes UCS-2. A single Bangla character in an otherwise-English message triples the cost — the API must return the computed part count before sending so clients aren't surprised.
- Write `EncodingDetector` as a pure, side-effect-free class and unit test it hard. Test cases must include: pure English, pure Bangla, Banglish mixed, emoji, € sign, exactly 160 chars, exactly 161 chars, exactly 70 chars, exactly 71 chars.

### 2.3 Masking vs non-masking

- Non-masking: sender shows as a numeric shortcode. Cheaper. Always available.
- Masking (branded sender ID): sender shows as e.g. `ABM-BIKE`. More expensive, and must be pre-approved by the operator/provider before it can be used.

So: `sms_sender_ids` rows have a status (`pending`, `approved`, `rejected`, `suspended`). A tenant may only send with an approved sender ID belonging to them, or with the platform default non-masking route. Rates differ per type — see billing.

### 2.4 Do-not-disturb / blacklist

Maintain a blacklist table (global + per-tenant). Blocked numbers are rejected at submit time with no charge, and logged.

## 3. Database Schema

CI4 migrations, one file per logical group. Every table gets `created_at`, `updated_at` (and `deleted_at` where soft-delete makes sense). Every tenant-owned table gets `tenant_id` with an index and a foreign key.

### 3.1 Tenancy & auth

- **sms_tenants** — id, uuid, name, company_name, contact_phone, contact_email, district, status (active|suspended|closed), balance_cached (DECIMAL(14,4)), credit_limit (DECIMAL(14,4), default 0 — allows a controlled negative balance for trusted clients), default_sender_id, timezone, notes.
- **sms_tenant_users** — portal logins. tenant_id, name, email (unique), password_hash, role (owner|operator|viewer), last_login_at, status. Use CI4 Shield if convenient, otherwise a simple hand-rolled auth — but do not mix the two.
- **sms_api_credentials** — tenant_id, api_key (public, unique, prefix `abmsms_live_`), api_secret_hash (hash the secret, show plaintext exactly once at creation), label, ip_whitelist (JSON array, nullable = any IP), scopes (JSON: send, report, balance), rate_limit_per_min, last_used_at, status, revoked_at. A tenant may hold multiple credentials (staging + production).

### 3.2 Sender IDs & pricing

- **sms_sender_ids** — tenant_id, sender_id (the mask string), type (masking|non_masking), status, approved_at, approved_by, provider_reference, rejection_reason.
- **sms_price_plans** — name, is_default, status.
- **sms_plan_rates** — plan_id, route_type (masking|non_masking), encoding (gsm7|ucs2|any), rate_per_part DECIMAL(10,4), currency fixed BDT.
- **sms_tenant_rates** — per-tenant override of a plan rate. Resolution order: tenant override → tenant's plan → default plan. Implement this in a single `RateResolver` class; nothing else in the codebase may guess a price.

### 3.3 Credit ledger (append-only — this is the money)

**sms_credit_ledger** — tenant_id, entry_type (topup|reserve|charge|refund|adjustment|reversal), amount DECIMAL(14,4) (signed: credits positive, debits negative), balance_after DECIMAL(14,4), reference_type (message|batch|payment|manual), reference_id, description, created_by, idempotency_key (unique, nullable).

Rules the agent must follow exactly:

- `sms_tenants.balance_cached` is a cache only. Truth = `SUM(amount)` of the ledger.
- Never `UPDATE ... SET balance = balance - x` outside a transaction that also inserts a ledger row.
- Every balance mutation: `beginTransaction()` → `SELECT ... FOR UPDATE` on the tenant row → check sufficiency against `balance_cached + credit_limit` → insert ledger row → update `balance_cached` → `commit()`.
- Ledger rows are never updated or deleted. Corrections are new reversal rows.
- Build a `spark sms:audit-balances` command that recomputes every tenant's balance from the ledger and reports drift. Run it nightly via cron. Drift is a P1 bug, not a rounding curiosity.

**Lifecycle:** on submit → reserve (negative). On provider accept → convert reserve to charge. On provider reject or pre-send validation failure → refund (positive, reversing the reserve). Never refund on a failed DLR — the operator already billed us for a delivered-to-network message. Make this policy configurable per platform setting (`refund_on_dlr_failure`, default false) but default to not refunding, and document why in the code comment.

### 3.4 Messages

- **sms_batches** — tenant_id, batch_uuid, name, total_recipients, total_parts, total_cost, status (pending|processing|completed|partial|failed), scheduled_at, submitted_at, completed_at, source (api|portal|import).
- **sms_messages** — the core table. Expect millions of rows; index deliberately.
  - id BIGINT, tenant_id, batch_id (nullable), message_uuid (unique, this is what the client sees), client_reference (client's own ID, indexed — lets a showroom look up "the SMS for invoice 4471")
  - msisdn (normalized), operator, sender_id, route_type
  - body TEXT, encoding, char_count, part_count
  - rate_per_part, total_cost
  - status (queued|submitted|sent|delivered|failed|rejected|expired|blacklisted)
  - provider_id, provider_message_id (indexed), provider_status_code, provider_response JSON
  - error_code, error_message
  - scheduled_at, queued_at, submitted_at, delivered_at, attempts, next_retry_at
  - Indexes: (tenant_id, created_at), (tenant_id, status), (provider_message_id), (message_uuid), (tenant_id, client_reference), (status, next_retry_at).
  - Partition or archive strategy: add a `spark sms:archive --older-than=180` command that moves old rows to `sms_messages_archive`. Do not let this table grow unbounded.
- **sms_idempotency_keys** — tenant_id, key (unique with tenant_id), endpoint, request_hash, response_body JSON, response_code, expires_at. If a client retries a send with the same key within 24h, return the stored original response — do not send again. This is what saves us when a showroom's cron double-fires.

### 3.5 Providers & routing

- **sms_providers** — name, adapter (class key, e.g. `bulksmsbd`), credentials JSON (encrypted at rest using CI4 Encryption), base_url, priority, supports_masking, supports_unicode, rate_limit_per_sec, status (active|degraded|disabled), balance_cached, balance_checked_at.
- **sms_provider_routes** — routing rules: provider_id, route_type, operator (nullable = all), priority. Resolution: most specific match wins, then priority, then provider status.
- **sms_dlr_logs** — raw inbound DLR payloads, provider_id, provider_message_id, raw_payload, parsed_status, matched_message_id (nullable), received_at, processed_at. Log first, process second — never lose a DLR because parsing threw.

### 3.6 Webhooks & logs

- **sms_webhook_endpoints** — tenant_id, url, secret (for HMAC signing our outbound calls), events (JSON: message.delivered, message.failed, balance.low), status, consecutive_failures.
- **sms_webhook_deliveries** — endpoint_id, event, payload, attempt, response_code, response_body, next_retry_at, status. Exponential backoff: 1m, 5m, 15m, 1h, 6h, then give up and mark the endpoint degraded.
- **sms_api_logs** — tenant_id, credential_id, endpoint, method, ip, request_body (truncated, redact secrets), response_code, duration_ms, created_at. Retain 30 days, prune via cron.
- **sms_blacklist** — tenant_id (nullable = global), msisdn, reason, created_by.
- **sms_settings** — key/value platform config editable from admin without a deploy.

## 4. Authentication (must be CI3-friendly)

Support two modes on the same endpoints. The filter tries HMAC first, falls back to bearer.

**Mode A — Bearer key (default, simple)**

```
Authorization: Bearer abmsms_live_xxxxxxxx.SECRET
Content-Type: application/json
```

Fast to integrate. Must be combined with HTTPS and, for production credentials, an IP whitelist. Enforce whitelist in `IpWhitelistFilter` when `ip_whitelist` is non-null.

**Mode B — HMAC-SHA256 signed** (for higher-value tenants)

Same scheme already used in ABM SocialFlow, so keep it identical:

```
X-Api-Key:       abmsms_live_xxxxxxxx
X-Timestamp:     1755400000        (unix seconds)
X-Nonce:         32-char random hex
X-Signature:     hex hmac_sha256(api_secret, "{method}\n{path}\n{timestamp}\n{nonce}\n{sha256(raw_body)}")
```

Validation: timestamp within ±300s; nonce unseen (store in cache with 600s TTL); signature compared with `hash_equals()`. Reject with 401 and a distinct error_code for each failure reason (`SIG_INVALID`, `TIMESTAMP_SKEW`, `NONCE_REPLAY`) so integrators can debug.

**Rate limiting**

Per credential, sliding window, default 60 req/min and 10,000 recipients/min. On breach return 429 with `Retry-After`. Store counters in cache, not DB.

## 5. REST API Specification (`/api/v1`)

All responses JSON. Always include `success` (bool), `data` or `error`, `request_id` (UUID, also logged — makes support tickets solvable), and `client_id` (the tenant's own `sms_tenants.id` — added post-launch so each tenant's own downstream systems can match a response back to a client without parsing anything else out of it; null only on the pre-auth error cases where no tenant has been identified yet, e.g. `AUTH_REQUIRED`). Not to be confused with the per-message `client_reference` in §5.1 below — `client_id` identifies *who called*, `client_reference` is a free-text tag the caller chose for *one message*.

Error shape:

```json
{
  "success": false,
  "request_id": "0f3c...",
  "client_id": 25,
  "error": {
    "code": "INSUFFICIENT_BALANCE",
    "message": "Balance 12.50 BDT is below required 45.00 BDT",
    "details": { "required": 45.0, "available": 12.5 }
  }
}
```

Define a single `ErrorCode` enum class. HTTP status mapping: 400 validation, 401 auth, 403 scope/suspended, 402 insufficient balance, 404 not found, 409 idempotency conflict, 422 business rule, 429 rate limit, 502 provider failure, 503 no route available.

### 5.1 POST /sms/send — single or small multi-recipient

```json
{
  "to": ["01712345678", "01812345678"],
  "message": "আপনার বাইকের সার্ভিস ডিউ ২০ আগস্ট।",
  "sender_id": "ABM-BIKE",
  "client_reference": "SVC-4471",
  "schedule_at": null,
  "callback_url": null
}
```

Response 202:

```json
{
  "success": true,
  "request_id": "0f3c...",
  "client_id": 25,
  "data": {
    "batch_uuid": "...",
    "encoding": "ucs2",
    "part_count": 1,
    "total_cost": 0.90,
    "balance_after": 1204.10,
    "messages": [
      {"message_uuid": "...", "to": "8801712345678", "status": "queued", "cost": 0.45},
      {"message_uuid": "...", "to": "8801812345678", "status": "queued", "cost": 0.45}
    ]
  }
}
```

Header `Idempotency-Key` is honoured. Max 100 recipients on this endpoint.

### 5.2 POST /sms/bulk — up to 50,000 recipients

Accepts either a flat recipient list with one shared body, or a personalized array:

```json
{
  "name": "Eid Offer Aug 2026",
  "sender_id": "ABM-BIKE",
  "messages": [
    {"to": "01712345678", "message": "প্রিয় করিম সাহেব, ...", "client_reference": "C-101"},
    {"to": "01812345678", "message": "প্রিয় রহিম সাহেব, ...", "client_reference": "C-102"}
  ],
  "schedule_at": "2026-08-20T10:00:00+06:00"
}
```

Behaviour: validate all → compute total cost → reserve the full amount in one ledger entry → persist rows as `queued` → return 202 immediately with `batch_uuid`. Actual sending happens in the worker. If the balance can't cover the whole batch, reject the entire batch (do not partially send) unless `"allow_partial": true` is passed.

### 5.3 POST /sms/estimate — dry run, no charge

Same payload as send. Returns encoding, part count, per-recipient cost, total, and whether the balance covers it. Tell clients to call this from their UI before they hit send — it eliminates most support tickets.

### 5.4 Reports

- `GET /sms/{message_uuid}` — single message full detail.
- `POST /sms/status` — body `{"message_uuids": [...]}` or `{"client_references": [...]}`, max 500. Bulk status lookup; this is what CI3 cron jobs will poll.
- `GET /reports/messages?from=&to=&status=&sender_id=&search=&page=&per_page=` — paginated list, max per_page 500. Include pagination meta.
- `GET /reports/summary?from=&to=&group_by=day|sender_id|status` — aggregated counts and cost. Serve this from a pre-aggregated daily table (`sms_daily_stats`, rebuilt by a nightly command and incremented live), not by scanning `sms_messages`.
- `GET /reports/export?from=&to=&format=csv` — queues an export job, returns a download token; file generated by worker. Do not stream 200k rows synchronously.
- `GET /account/balance` — balance, credit limit, plan name, current rates.
- `GET /account/ledger?from=&to=` — paginated ledger entries.
- `GET /sender-ids` — list with statuses.

### 5.5 Outbound webhook (we call the client)

POST to the tenant's registered URL:

```
X-Abm-Signature: hex hmac_sha256(endpoint_secret, raw_body)
X-Abm-Event: message.delivered
X-Abm-Delivery-Id: uuid
```

Client must return 2xx within 10s. Anything else triggers backoff retry. Ship the verification snippet in the SDK.

## 6. Sending Pipeline

```
API request
  → validate & normalize numbers
  → blacklist check
  → sender ID authorization check
  → encoding + part count
  → rate resolution
  → credit reserve (transactional, FOR UPDATE)
  → persist messages as `queued`
  → return 202
        ↓  (async)
  worker picks up batch
  → provider route resolution
  → chunk per provider batch limit
  → submit to provider adapter
  → on ACK: store provider_message_id, status `submitted`, convert reserve → charge
  → on NACK: status `rejected`, refund reserve, log provider response
        ↓
  provider POSTs DLR to /webhook/dlr/{provider_slug}
  → log raw payload immediately
  → match by provider_message_id
  → update status to delivered/failed, set delivered_at
  → dispatch outbound webhook to tenant if subscribed
```

Worker commands (all idempotent, all safe to run concurrently via `SELECT ... FOR UPDATE SKIP LOCKED`):

- `spark sms:dispatch --limit=500` — main sender loop.
- `spark sms:retry` — retries failed messages where attempts < max_attempts and the error is retryable (network/timeout/5xx). Never retry business rejections (invalid number, blocked mask).
- `spark sms:webhooks` — outbound webhook delivery.
- `spark sms:poll-dlr` — for providers that don't push DLRs, poll status.
- `spark sms:audit-balances`, `spark sms:aggregate-stats`, `spark sms:prune-logs`, `spark sms:archive`.

Provide a supervisor config sample and a crontab sample in `docs/deployment.md`.

## 7. Provider Abstraction

```php
interface ProviderInterface
{
    public function getKey(): string;
    public function supports(string $routeType, string $encoding): bool;
    public function maxBatchSize(): int;
    public function send(OutboundBatch $batch): ProviderResponse;
    public function parseDlr(array $payload): DlrResult;
    public function checkBalance(): ?float;
}
```

- Implement a `GenericHttpProvider` driven entirely by config (URL template, method, field mapping, success-detection rule). Most Bangladeshi providers are a simple GET/POST with query params — this one adapter will cover several of them without new code.
- Implement one real adapter concretely against whichever provider we sign with, plus a `NullProvider` (logs and pretends to succeed) for local dev and staging.
- `ProviderManager` handles routing, failover to next-priority provider on 502, and circuit-breaking (after N consecutive failures, mark degraded for M minutes and skip it).
- Provider credentials must be encrypted in DB and never appear in logs or API responses. Add a `redactSecrets()` helper used by the logging layer.

## 8. Admin Panel (ABM Soft internal)

- Dashboard: today's volume, revenue, failure rate, provider health, low-balance tenants.
- Tenants: CRUD, suspend/activate, manual credit top-up (writes ledger `topup` with a note + operator name — this is the record when a showroom pays by bKash), set credit limit, assign price plan, impersonate ("login as tenant" — log every impersonation).
- Sender ID approval queue.
- Providers: CRUD, priority, test-send, balance check.
- Price plans and per-tenant rate overrides.
- Message explorer: search across all tenants by MSISDN, client_reference, provider_message_id.
- Ledger explorer + balance drift report.
- Blacklist management.
- API log viewer.

Role-based access: `super_admin`, `support` (read + top-up, no provider/pricing edit), `accounts` (billing only).

## 9. Tenant Portal (client self-service)

Keep it simple — showroom staff, not engineers, will use it.

- Dashboard: balance, this month's sends, delivery rate.
- Send SMS (single, and CSV upload for bulk).
- Message history with filters and CSV export.
- Reports with a simple bar chart by day.
- Sender ID request form.
- API credentials: create, view key, reveal secret once, revoke, set IP whitelist.
- Webhook endpoint setup with a "send test event" button.
- Ledger / top-up history.
- Full Bangla language toggle. Ship both `en` and `bn` language files from day one; do not bolt it on later.

## 10. The CI3 Client SDK (do not skip this)

100 legacy CI3 installs must integrate with near-zero effort. Deliver a single dependency-free PHP file (`AbmSms.php`, PHP 7.2+ compatible so it runs on old client servers) exposing:

```php
$sms = new AbmSms('abmsms_live_xxx', 'SECRET');   // optionally: 'https://sms.nextmotogear.com/api/v1'

$sms->send('01712345678', 'আপনার বাইক সার্ভিস রেডি।', ['client_reference' => 'SVC-4471']);
$sms->sendBulk($recipientsArray, ['name' => 'Eid Offer']);
$sms->estimate($to, $message);
$sms->status($messageUuid);
$sms->balance();
AbmSms::verifyWebhook($rawBody, $signatureHeader, $secret);
```

Requirements: cURL only, no Composer, configurable timeout, automatic retry on connection failure only (never on a 4xx), returns plain arrays, throws a single `AbmSmsException`. Include a CI3 usage example showing config placement in `application/config/` and a library wrapper in `application/libraries/`.

Also ship Postman collection + `docs/api.md` in English and a Bangla quick-start.

## 11. Security Requirements

- Every DB query scoped by `tenant_id` — enforce via a base model method, not by remembering to add a `where()` each time. Write a test that proves cross-tenant reads fail.
- Query builder / prepared statements only. No string-concatenated SQL anywhere.
- CSRF on all portal and admin forms. Not on the API (it's key-authenticated).
- Escape all output; CI4 auto-escaping on.
- Passwords: `password_hash()` with `PASSWORD_DEFAULT`.
- API secrets stored hashed; shown once at creation.
- Provider credentials encrypted via CI4 Encryption with the key in `.env`.
- Redact `api_secret`, `Authorization`, provider credentials, and full message bodies over 200 chars from all logs.
- Login throttling on portal and admin (5 failures → 15 min lock).
- Force HTTPS in production; set HSTS, X-Content-Type-Options, X-Frame-Options.
- Audit log table for every admin action that touches money, credentials, or tenant status.

## 12. Testing Requirements

Do not consider a phase complete without these.

**Unit tests (mandatory):**

- `EncodingDetector` — the full table of edge cases from §2.2.
- `NumberNormalizer` — all input formats, all operator prefixes, all invalid cases.
- `RateResolver` — override precedence.
- `CreditService` — reserve/charge/refund/reversal sequences, and a concurrency test: two simultaneous sends against a balance that only covers one must result in exactly one success and one `INSUFFICIENT_BALANCE`, with a correct final balance.

**Feature tests:**

- Auth: valid key, revoked key, wrong signature, replayed nonce, skewed timestamp, non-whitelisted IP.
- Cross-tenant access attempts on every report endpoint → 404, never a leak.
- Idempotency: identical key twice → one send, two identical responses.
- Full send → DLR → webhook flow against `NullProvider`.
- Rate limit breach → 429.

Include a `spark sms:simulate --tenant=X --count=1000` command that generates realistic traffic against `NullProvider` for load-checking the worker.

## 13. Build Phases

Build in this order. Stop at the end of each phase, run its tests, and report status before continuing.

| Phase | Scope | Definition of done |
|---|---|---|
| 0 | Project skeleton, config, all migrations, seeders (1 test tenant, 1 plan, NullProvider), .env.example, docs/ structure | `php spark migrate` runs clean on empty DB; `spark db:seed` produces a working test tenant |
| 1 | NumberNormalizer, EncodingDetector, RateResolver, CreditService + full unit tests | All §12 unit tests green, including the concurrency test |
| 2 | API auth filters, rate limiting, POST /sms/estimate, GET /account/balance, error envelope, request logging | Postman collection can authenticate both ways and estimate cost correctly |
| 3 | POST /sms/send, POST /sms/bulk, idempotency, queue tables, spark sms:dispatch, NullProvider | 1,000 simulated messages send end-to-end with zero balance drift |
| 4 | Real provider adapter, GenericHttpProvider, ProviderManager routing + failover + circuit breaker | Live test-send succeeds against the real provider sandbox |
| 5 | DLR webhook receiver, status endpoints, retry command | DLR updates message status; unmatched DLRs are logged, not lost |
| 6 | Reports API, sms_daily_stats aggregation, CSV export job | Summary endpoint returns in <300ms on 1M rows |
| 7 | Outbound webhooks + backoff + signature | Test event delivers and verifies with the SDK helper |
| 8 | Admin panel | Manual top-up writes a correct ledger entry; sender ID approval works |
| 9 | Tenant portal + Bangla i18n | A non-technical user can send an SMS and read a report in Bangla |
| 10 | CI3 SDK, docs/api.md, Postman collection, deployment guide, supervisor/cron samples | A CI3 app integrates in under 15 minutes using only the docs |

## 14. Coding Standards

- PSR-12. Strict types where practical.
- Controllers stay thin: validate → call service → format response. No business logic in controllers. No DB queries in controllers.
- All business logic in `Services/`, all queries in `Models/`.
- Use CI4 Entities for Message, Tenant, LedgerEntry.
- Every service method that mutates money has a docblock stating its transaction guarantees.
- Config values via `.env` + `Config\` classes. No hardcoded URLs, keys, rates, or limits anywhere in code.
- Meaningful commits per phase.
- English code, English comments — but all user-facing strings go through language files, never inline.

## 15. Explicit Anti-Requirements

Do not build these unless asked later: OTP/2FA-as-a-service, two-way/inbound SMS, WhatsApp or Viber channels, a payment gateway (top-ups are manual admin entries in v1), drag-and-drop campaign builder, contact list management, a mobile app, an SPA frontend.

**Ask before:** changing the table prefix, adding a Composer package not in the stack list above, altering the credit ledger design, or introducing Redis as a hard dependency.
