# AGENTS.md

AkotoCreative SMS is a bulk SMS website for Ghana. Users sign up, buy SMS credit (GHS) through Moolre's hosted payment link, and send bulk SMS through Moolre's SMS API.

## Stack

TanStack Start (React 19) on Netlify, Tailwind 4 + shadcn/ui (`src/components/ui`), Netlify Identity (`@netlify/identity`), Netlify Database with Drizzle ORM (`drizzle-orm@beta` / `drizzle-kit@beta`, the beta tag is required), zod.

## Layout

```
db/schema.ts               accounts (credit balance per Identity user), payments, campaigns (source dashboard|api), sender_ids, credit_adjustments, app_settings (key/value), api_keys (hashed), notifications (dashboard alerts), chat_messages (one support thread per customer), voice_calls (one row per voice SMS call; campaigns.channel is sms|voice), auto_messages (log of automatic customer texts), email_messages (log of receipt/test emails); accounts also hold name, phone, sms_alerts
db/index.ts                Drizzle client (drizzle-orm/netlify-db, no connection string)
netlify/database/migrations generated by drizzle-kit; never edit applied migrations
src/start.ts               createStart with a request middleware that creates a CSP nonce and adds security headers (CSP etc. from src/lib/security-headers.ts) to every SSR/API response
src/lib/legal.ts           Legal page content (terms, privacy, acceptable-use, security, cookies) as data; used by /legal/$doc and the footer
src/lib/pricing.ts         credit bundles and GHS formatting (shared client/server)
src/lib/sms.ts             segment counting, Ghana phone normalization (shared)
src/lib/moolre.server.ts   Moolre HTTP client: payment link, status check, SMS send, SMS balance (getSmsBalance, /open/sms/status); getMoolreConfig (app_settings `moolre.*` rows, env fallback, 30s cache)
src/lib/moolre-settings.ts Moolre settings field list shared by the admin form and server; decodeMoolreKey/moolreKeyProblem/walletMismatch (keys are JWTs naming userid/walletid or vasid) for paste-mistake warnings
src/lib/billing.server.ts  ensureAccount, settlePayment (idempotent crediting), spend/refund credits
src/lib/voice.ts            voice SMS constants (5 credits/recipient, 450 chars, 1,000 numbers), VOICES (woman|man), VOICE_FIELDS (Africa's Talking settings)
src/lib/voice.server.ts     Africa's Talking client (getVoiceConfig: app_settings `voice.*`, env fallback), sendVoiceCampaign, handleVoiceCallback (Say XML, missed-call refunds), voiceCallCounts
src/lib/voice.functions.ts  getVoicePage, sendVoiceSms
src/routes/api.voice.callback.ts Africa's Talking voice callback (set on the voice number in their dashboard)
src/lib/messaging.server.ts sendCampaign / scheduleCampaign / cancelScheduledCampaign (sender ID check, cost, batching, refunds; used by dashboard and public API), dispatchCampaign (resumable, saves progress per batch), runDueCampaigns (the every-minute job), messageRef, SendError(code, status)
src/lib/delivery.ts         per-number delivery states shared client/server (recipientState, DELIVERY_LABELS)
src/lib/delivery.server.ts  Moolre status-by-ref refresh (≤ every 20s per send, 7-day window), admin labels for Moolre status numbers (app_settings `sms.dlr.<n>`), recipientsPage
src/lib/phone-auth.server.ts App sign-in by SMS code: requestLoginCode / verifyLoginCode (login_codes, hashed, 10 min, 5 tries, 3 per number per 15 min, 10 per IP per hour), issues a "Phone app" API key
src/lib/public-api.server.ts publicHandler/readJson/clientIp for /api/v1 routes that take no API key
netlify/functions/send-scheduled.mts every-minute scheduled function: runDueCampaigns with a 20s budget
src/lib/api-keys.server.ts  key generation/hashing, authenticateApiKey, withApiKey wrapper for /api/v1 handlers
src/lib/api-keys.functions.ts dashboard server functions: listApiKeys, createApiKey, revokeApiKey
src/lib/auto-sms.ts         automatic text events (sign_in, purchase), placeholders, default templates, renderAutoSms
src/lib/auto-sms.server.ts  getAutoSmsSettings (app_settings `autosms.<event>.enabled|template`), sendAutoSms (never throws), deliverAutoSms (logs to auto_messages)
src/lib/email.ts            EMAIL_FIELDS (Gmail address, app password, sender name; app_settings `email.*`, env GMAIL_* fallback), defaults
src/lib/email.server.ts     Gmail SMTP via nodemailer: getEmailConfig (30s cache), probeEmail, deliverEmail (logs, never throws), buildReceipt (HTML + text), sendReceiptEmail
src/lib/notifications.server.ts notify (never throws), notifySignIn (1-minute dedupe, device from User-Agent)
src/lib/notifications.functions.ts listNotifications, recordSignIn (called by the browser after login), markNotificationsRead
src/lib/chat.functions.ts   "Chat with us": customer getMyChat/sendChatMessage/markMyChatRead, admin listChatConversations/getChatThread/sendChatReply/markChatThreadRead/searchChatCustomers
src/lib/settings.functions.ts recordAccountChange: after a browser-side password/email/Google change, syncs accounts.email (fresh from Identity admin API) and adds a `security` alert
src/lib/identity.functions.ts  getServerUser + requireIdentity / requireAdmin middleware
src/lib/admin.functions.ts     admin server functions: overview stats + 30-day trends (SMS and voice split), getMainBalance (Moolre SMS + Africa's Talking balances, loaded client-side after the overview), nav counts, customers + adjustCredits, payments + recheckPayment, campaigns, sender ID review, Moolre API settings + checkMoolreConnection (harmless login/checkout/VAS/sender probes on unsaved form values)
src/lib/account.functions.ts   server functions: getDashboard, startCheckout, confirmPayment, sendBulkSms, requestSenderId
src/routes/api.moolre.webhook.ts  Moolre payment callback
src/routes/api.v1.*.ts     public SMS API (sms/send incl. schedule_at, messages/$id, messages/$id/recipients, messages/$id/cancel, balance, sender-ids), API-key auth; auth/request-code and auth/verify (app sign-in, no key)
src/routes/                index (landing, incl. Developer API section), developers (API docs), login, signup, dashboard, send (dedicated Send bulk SMS page), voice (Send voice SMS page), settings (customer account: name, change email, set/change password, Google sign-in), buy, payment (return page), legal layout + legal.$doc (Terms, Privacy, Acceptable use, Security, Cookies; /legal redirects to terms), admin layout (standalone console, no public header/footer) + admin_.login (admin-only sign in) + admin.index/customers/payments/messages/chat/sender-ids/settings
src/components/admin/      SettingsUi (Section, ReadyCard, SettingField used by /admin/settings), AdminUi (status pills, avatars, panels, stat strips), charts (SVG trend/bar/sparkline/donut, no chart library)
src/components/            RecipientsField (useRecipients + one/many/CSV recipients step shared by SmsComposer and VoiceComposer), VoiceComposer (voice picker, browser speech preview, call preview), admin/VoiceSettings (Africa's Talking form on /admin/settings), SmsComposer (compose + send form shared by /send and /dashboard: one number or many, CSV/TXT import, clean list, confirm dialog), ChatThread (bubbles, composer, useChatThread 5s polling shared by dashboard and admin chat), ChatWidget (floating launcher on the landing page: signed-in customers get their thread, visitors a sign-in prompt), ApiCodeSamples (tabbed code examples, CopyButton, CodeBlock), IdentityProvider, SiteHeader/Footer, AuthForm, PricingGrid, RecoveryDialog
```

## Key decisions

- **Never trust payment callbacks or redirects.** Both the webhook and the `/payment` return page call `settlePayment`, which asks Moolre's status endpoint for the real result, checks the amount, and claims the payment with a conditional `UPDATE ... WHERE status <> 'success'` before adding credits. This makes crediting idempotent.
- **Credits** are an integer column on `accounts`. Spending uses `UPDATE ... WHERE credits >= n` so a balance can't go negative. Sends are deducted up front and refunded per failed batch (batches of 100). An `ASMS07` (unapproved sender ID) or `AIN01` (auth) error stops the remaining batches.
- **Sender IDs** need an `approved` row in `sender_ids` for that user (case-insensitive) before sending. Admins approve, reject, revoke and return requests to review in `/admin/sender-ids`. Approval is local: never register, sync or request approval from Moolre, including during sends. Moolre can still refuse delivery (`ASMS07`); stop remaining batches and refund unsent messages. Customers start with no sender ID; the platform `MOOLRE_SENDER_ID` is only used for automatic texts. Admins are Identity users with the `admin` role.
- **Public API keys** (`akc_live_…`) are stored only as SHA-256 hashes; the full key is returned once by `createApiKey`. Revoking sets `revoked_at`. API sends go through the same `sendCampaign` as the dashboard. No CORS: the API is meant to be called server-side.
- **Dashboard alerts**: sign-ins (password login, signup, OAuth/confirmation callbacks, admin login) call `recordSignIn`; `settlePayment` adds a purchase alert only when it claims the payment; admin adjustments add a balance alert. Don't use `onAuthChange` LOGIN for sign-in alerts, it also fires on hydrate and cross-tab storage events.
- **Chat with us**: no websockets; open chats poll `afterId` every 5s while the tab is visible, with a full refresh every 30s for read receipts. `readAt` on a message means the other side has seen it. Customers never see which admin replied. Customers are limited to 10 messages a minute.
- **Customer settings** run Identity mutations in the browser (`updateUser`). Changing a password re-checks the current one with `login()`; Google-created accounts have no password until `user_metadata.password_set`. Google "connect" is GoTrue matching by email: `startGoogleSignIn(userId)` stores the intent in localStorage and `IdentityProvider` warns if Google returned a different account. Google buttons only show when the provider is enabled in Identity settings (`useGoogleAvailable`). Google always returns to the home page, so `startGoogleSignIn(connectTo, next)` stores a same-site return path and `IdentityProvider` does a full `location.replace(next)` after the callback. `/buy` doesn't redirect signed-out visitors: it shows a sign-in panel (Google + email links with `?redirect=`), and login/signup accept `redirect`.
- **Voice SMS** goes through Africa's Talking (Moolre has no voice API). Credits are deducted up front (5 per number), `voice_calls` rows are inserted before dialling, and refunds happen for calls not placed and for calls whose final callback arrives while still `queued` (never answered). The conditional status update makes that refund one-time. The callback matches on `sessionId`, falling back to `clientRequestId` `V<campaignId>` + destination number. The sandbox is used when the username is `sandbox`.
- **Automatic texts**: `recordSignIn` sends the sign-in text only when `notifySignIn` records a new alert (same 1-minute dedupe); `settlePayment` sends the purchase text only when it claims the payment, falling back to the payer phone if the customer saved no number. Sent from the platform sender ID, not charged to customer credits. Admins edit wording/on-off and send tests in /admin/settings; customers set phone/opt-out in Settings → Text alerts.
- **Receipt emails**: `settlePayment` calls `sendReceiptEmail` only when it claims the payment, so each purchase is emailed once to `accounts.email`. Sent from the platform Gmail (default creativeakotoansah@gmail.com) over SMTP with an app password; `email.receipts.enabled` turns them off. Admins configure, check and send sample receipts in /admin/settings (EmailSettings).
- Admin credit adjustments use the same conditional update (removals can't go below zero) and are logged in `credit_adjustments`.
- 1 credit = 1 SMS part to 1 recipient. Max 6 parts and 5,000 recipients per send.
- **Resumable sending**: `dispatchCampaign` saves `send_progress`, `sent_count` and a 2-minute `locked_until` lease after every batch of 100, and marks refused batches as -1 in `campaigns.delivery`. Immediate sends hold the lease from creation. `runDueCampaigns` (every minute, 20s budget) claims due `scheduled` SMS sends and resumes `sending` SMS sends whose lease expired, newest-first within 24h. Only rows with a non-null `locked_until` are resumed, so sends from before this existed (lease null) are never touched; when a run runs out of time it sets the lease to the past, never null. Scheduled sends re-check the sender ID when they start and refund in full if it was revoked. Cancelling is a conditional `status = 'scheduled'` update, so it can't race the job.
- **Per-number delivery**: messages go to Moolre with ref `C<campaignId>-<index>`; `/open/sms/status` type 5 returns a status number per ref. Moolre doesn't document the numbers, so admins label them under Delivery reports on /admin/settings; unlabelled numbers show as `sent`, never delivered/failed. Statuses are fetched only when someone views a send's numbers.
- **App sign-in**: `/api/v1/auth/request-code` answers the same whether or not the number is on an account (no enumeration) and texts a code only when exactly one account has that `accounts.phone`. The code is hashed and the auto_messages log stores it masked. `/api/v1/auth/verify` issues an API key named "Phone app (<device>)", retiring the oldest phone-app key if the account is at the 10-key limit, and adds a `security` alert. These routes have no CORS; the Android app calls them with native HTTP.
- Moolre responses always use the `{status, code, message, data}` envelope. Branch on `code` (`POS09` link created, `SS01` status ok, `SMS01` sent), not on the HTTP status.
- Moolre credentials are only read in `*.server.ts` modules via `getMoolreConfig()`, inside server handlers. Admin-saved values (`/admin/settings`) override env vars; names are listed in README.md. Secret values are never sent to the browser, only a masked preview.
- Auth mutations (login/signup/logout) run in the browser. Server functions check `getUser()` with the `requireIdentity` middleware, and every query is scoped to `context.user.id`.
- **CSP** lives in `src/lib/security-headers.ts`. script-src uses a per-request nonce (no 'unsafe-inline'): the middleware in `src/start.ts` creates it and passes it as start context, `getRouter` sets `ssr.nonce` from `getGlobalStartContext()`, and TanStack stamps it on every script it renders. Never add inline `<script>`s or `on*=` handler attributes; render scripts through route `head`/`ScriptOnce` so they get the nonce. Adding any third-party script, iframe, font or fetch origin means adding it to the policy.
- Theme: warm paper background, forest-green primary, kente-gold accent. Variables are in `src/styles.css`, fonts are Bricolage Grotesque (headings) and Instrument Sans. `.kente-band` and `.dot-grid` are decorative utilities.

## Conventions

- Use the `@/` alias for `src`. Server-only helpers use the `.server.ts` suffix and must only be imported inside server function handlers or API routes.
- Validate every server function with `.validator(zod)`.
- After changing `db/schema.ts`, run `npx drizzle-kit generate --name <snake_case_change>`.
