Messaging Delivery
How Kagami sends WhatsApp, SMS, email and push messages - provider selection, template builders, idempotent sends, phone health, reminder crons and Confirm/Reschedule/Cancel replies.
13 min read
Overview
This page documents the outbound delivery pipeline as implemented in code (web/src/lib/messaging, web/src/lib/push, web/src/lib/reminders, web/src/app/api/cron/*). For the product view of messaging (inbox, consent, birthdays) see communications.md. For the inbound AI agent turn see ai-whatsapp-agent.md. For Instagram/Messenger DMs see social-dms.md.

Channel summary:
| Channel | Used for | Provider in code |
|---|---|---|
| Client confirmations, reminders, cancel/reschedule notices, recall, wallet/loyalty expiry, journeys, staff alerts, portal OTP | Meta WhatsApp Cloud API (Graph v25.0) |
|
| SMS | Portal/signup/password-reset OTP only | Self-hosted android-sms-gateway, TextBee, httpSMS |
| OTPs, invitations, invoice receipts, digests, alerts, one legacy reminder path | Resend | |
| Push | Staff/owner alerts (inbox messages, AI holds, playbook tasks) | Browser Web Push (VAPID) + Firebase Cloud Messaging |
There is no SMS channel for client reminders or marketing in the code.
Provider selection
- The only WhatsApp provider implementation is
WhatsAppCloudProvider(providers/whatsapp-cloud.ts), implementingMessagingProvider.sendTemplate(to, name, vars, language)(types.ts). Each brand has its own Meta credentials inmessaging_settings(wa_phone_number_id,wa_access_token,waba_id,wa_verification_pin). - Selection is per brand and purely by credentials: if both
wa_phone_number_idandwa_access_tokenexist the Cloud provider is used, otherwiseStubMessagingProvider(providers/stub.ts). Themessaging_settings.providercolumn (defaultwhatsapp_cloud) is written on connect and bysaveMessagingSettingsActionbut no sender reads it to choose a provider. - The stub only logs to the server console and returns an id like
stub_<timestamp>. Callers then mark theoutbound_messagesrowsent.wallet-expiryand the alert sender refuse to send without credentials instead. - No BSP adapter exists in code. Tenants connect their own WABA directly via Meta Embedded Signup (
connectWhatsAppAction) or, for a number already verified in the owner's WABA (e.g. migrated from another provider),connectExistingWhatsAppNumberAction(owner supplies WABA id, phone number id, system-user token, 6-digit PIN). Both register the number (POST /{phone_number_id}/register), store credentials, setis_whatsapp_enabled = true, subscribe the app to the WABA webhook, and fire-and-forgetregisterWhatsAppTemplates. - Reconnecting through a different Meta app swaps the webhook subscription (new app first, then unsubscribes the old app with the old token) -
swapWabaSubscription. - The recipient id is built by
toWaId: a bare 10-digit number starting 6-9 gets91; anything else is sent as-is (SALO-2553). Free-text/interactive replies use thewa_idexactly as Meta delivered it.
Env var names (values never documented): NEXT_PUBLIC_META_APP_ID, META_APP_SECRET, WHATSAPP_WEBHOOK_VERIFY_TOKEN, META_WEBHOOK_VERIFY_TOKEN (DM webhook), NEXT_PUBLIC_APP_URL, NEXT_PUBLIC_SITE_URL.
Where owners configure it
| Setting | Location in app | Stored in |
|---|---|---|
| Connect WhatsApp, template names, send toggles, reminder lead time, reminder language | Settings > Messaging (settings/messaging) |
messaging_settings |
| Per-store WhatsApp on/off | Location settings (toggleLocationWhatsAppAction) |
location_messaging_settings (absent row = enabled) |
| Meta template list, sync, custom builder | Settings > WhatsApp templates (settings/whatsapp-templates) |
whatsapp_templates |
| Confirm/Reschedule/Cancel requests and auto-release | Settings > Reminders (settings/reminders, confirm-release-panel.tsx) |
messaging_settings.reminder_confirm_*, location_reminder_settings |
| Alert channels (bell/push/WhatsApp/email) | Alerts settings (lib/alerts/registry.ts) |
org alert config rows |
messaging_settings toggles: is_whatsapp_enabled, send_confirmations (default true), send_reminders (default false), send_cancellations and send_reschedules (default false), send_referral_notifications, reminder_hours_before (DB default 2; the cron falls back to 24 only if the value is null), reminder_template (default appointment_reminder), reminder_template_language (default en_US, validated ^[a-z]{2,3}(_[A-Z]{2})?$).
Template registry and approval sync
WHATSAPP_TEMPLATES in lib/messaging/templates.ts is the central code registry (name, category, language, body, sample values, optional quickReplies, optional one urlButton). On connect, or via the "Sync" button (syncWhatsAppTemplatesAction), every entry is POSTed to /{waba_id}/message_templates (postMetaTemplate, 15 s timeout) and the result upserted into whatsapp_templates (unique brand_id,name,language).
- An "already exists" error is treated as success (
ALREADY_EXISTS); the existing tracked status is left alone. - Categories in the registry:
UTILITY,MARKETING.AUTHENTICATIONexists in the type, but the OTP templateotp_verification(OTP_TEMPLATE_NAME) is not in the registry and must exist in the WABA separately. - Registry template names (grouped): booking
booking_confirmation,appointment_reminder,appointment_cancelled,appointment_rescheduled; referralreferral_captured,referral_reward_ready,referral_reward_used,referral_reward_expiring,referral_reward_expired; staffstaff_welcome,staff_invite,staff_alert,eod_report,ai_chat_anomaly_alert; clientinvoice_receipt,pre_arrival_addon,salon_feedback_request,salon_feedback_link,raffle_entry_code_v2,raffle_winner; playbookplaybook_*in en_US plus_taand_hivariants (see playbook.md). - Templates referenced by senders but not in the registry (must be created by hand or in the builder):
booking_upgrade,service_recall_reminder,wallet_expiry_reminder, journey templates (salon_welcome,salon_post_visit,salon_review_request,salon_win_back,salon_rebook_nudge,salon_birthday,salon_no_show),otp_verification, and the brand's own Confirm/Reschedule/Cancel buttons template. Some names are seeded as journey defaults inlib/marketing/journeys.ts. - Status values stored:
DRAFT(custom, unsubmitted),PENDING,APPROVED,REJECTED,PAUSED,DISABLED,IN_APPEAL, plus UI-onlyALREADY_EXISTSandNOT_SUBMITTED.
Approval sync has three paths:
- Webhook
message_template_status_update(handled inwebhooks/whatsapp/route.tsbyhandleTemplateStatusUpdate): maps the WABA id tomessaging_settings.waba_idand upsertsstatus(the Metaevent) andrejected_reason. If no brand has that WABA the event is ignored. - "Check status" (
refreshWhatsAppTemplateStatusAction): liveGET /{waba_id}/message_templates?fields=name,status,category,language,rejected_reason, upserts every returned template. - The settings page polls
getWhatsAppTemplateRowsAction(DB only, no Meta call) every 15 s and on tab focus.
Consumers check approval: ai-pre-arrival-nudge only scans brands whose pre_arrival_addon row is APPROVED; invoice sharing requires invoice_receipt (or messaging_settings.invoice_template) APPROVED; playbook picks the localized variant only when approved, else falls back to English (resolvePlaybookWhatsAppTemplate, approval map DEFAULT_PLAYBOOK_TEMPLATE_APPROVALS is a hard-coded constant, not read from the DB).
Custom and carousel template builder
UI: custom-template-manager.tsx (tab "WABA Templates" in templates-hub-client.tsx; the second tab "Message Copy Templates" is a separate SMS/WhatsApp/email snippet store, lib/message-templates, not sent through Meta). Server actions in lib/messaging/admin-actions.ts:
| Action | Behaviour |
|---|---|
saveCustomTemplateAction |
Creates/updates a whatsapp_templates row with is_custom = true, status DRAFT on create. Requires name + body; carousel needs 2-10 cards, each with uploaded media and body. |
submitCustomTemplateAction |
Builds the Meta payload with buildMetaTemplatePayload and POSTs it; stores returned status, meta_template_id, submitted_at. The UI saves first, then submits. |
uploadTemplateHeaderMediaAction |
Meta resumable upload using the app token (the app id and app secret joined into one token); returns a header handle used as the sample media. |
deleteCustomTemplateAction |
Best-effort DELETE /{waba_id}/message_templates?name= at Meta, then deletes the row. |
Builder rules (custom-template-builder.ts):
- Body uses named merge fields
{{client_name}}etc. fromSALON_TEMPLATE_VARIABLES(variables.ts:client_name,staff_name,service_name,appointment_date,appointment_time,location_name,location_address,salon_name,invite_link,portal_link,role_label,inviter_name,revenue,appointments_count,new_clients_count). They are renumbered{{1}}..{{n}}in first-appearance order; the same order must be used at send time. Unknown keys get the sample valueexample. - Header types:
none,text,image,video,document,carousel. Buttons:QUICK_REPLY,URL,PHONE_NUMBER(UI allows up to 10). - Carousel: each card gets HEADER (image/video) + BODY + optional BUTTONS, variables numbered from
{{1}}per card. purpose(automation/campaign) andcustom_categoryare organisational labels only and are never sent to Meta (migration0141).
Idempotent outbound and the message log
Every WhatsApp send that is tied to a client or appointment writes an outbound_messages row first (status = pending), then updates it. Columns: message_type (confirmation, reminder, cancellation, reschedule, marketing, custom, portal_otp, invoice_receipt, ...), channel, template_name, template_variables, provider_message_id, status, idempotency_key (UNIQUE, migration 0014), sent_at, delivered_at, read_at, failed_at, error_detail.
Statuses: pending, sent, delivered, read, failed, and skipped (booking confirmation suppressed because the start time already passed, SALO-2368).
| Sender | Idempotency key | Retry on failure |
|---|---|---|
Booking confirmation (send.ts) |
confirmation:<appointmentId> |
No: any existing row (even failed) blocks a resend |
| Cancel / reschedule notice | cancellation:<id> / reschedule:<id> |
No (same check) |
| Upgrade notice | upgrade:<id> |
No |
| Reminder (24h or brand window) | reminder:<appointmentId> |
No (any existing row skips) |
| Reminder 1h | reminder-1h:<appointmentId> |
No |
| Service recall | recall:<appointmentId>:<serviceId> |
Yes, via claimOutboundMessageSlot |
| Wallet expiry | wallet_expiry:<walletId> |
Yes, via claimOutboundMessageSlot |
| Loyalty points expiry, raffles | claimed with claimOutboundMessageSlot |
Yes |
claimOutboundMessageSlot (idempotent-outbound.ts): returns null if a row for the key is sent or pending (skip); a failed row is reset to pending and re-used; no row inserts a new one. Because pending blocks, a process crash between insert and send leaves the key stuck forever.
The sender call sites catch errors and write failed + error_detail (first 500 chars). They never throw to the booking flow (fire-and-forget).
Delivery receipts: the WhatsApp webhook statuses[] loop (processStatusUpdate) updates outbound_messages by provider_message_id (delivered_at, read_at, failed_at) and mirrors status onto task_events for playbook messages. For a failed status on an AI reply (message_type = custom, no sent_by) it raises a staff alert via flagAiDeliveryFailure; failed reminders and other templates are only updated in the table (nothing alerts). Meta returns 200 + an id on acceptance, so sent does not prove delivery (noted in SALO-580/597).
Template language fallback (WhatsAppCloudProvider.sendTemplate): on Meta error 132001 (translation missing) it retries once swapping en_US and en.
Phone health
getWhatsAppPhoneHealthreadscode_verification_status,quality_ratingfor the phone number.healthy= statusVERIFIEDand rating notRED.refreshWhatsAppPhoneHealth(phone-health.ts) persistswa_phone_verification_status,wa_phone_quality_rating,wa_phone_health_checked_atonmessaging_settings(migration0159). Staff trigger it from Settings viacheckWhatsAppPhoneHealthAction; a separate token check ischeckWhatsAppTokenHealthAction(GET /{waba_id}?fields=id).- Only the client portal OTP path acts on it:
sendPortalOTP(WhatsApp channel) re-checks live if the cache is older than 7 days and blocks only when the rating isRED(anEXPIREDverification no longer blocks since SALO-2507).isPortalWhatsAppAvailablehides the WhatsApp tab only on positive evidence ofREDwithin the 7-day window. - Reminder/confirmation crons do not consult phone health. The messaging limit tier is not read anywhere.
SMS and OTP delivery
deliverOtpText (lib/otp/deliver.ts) is the only SMS user. Default cascade, each channel only if its env vars exist: android-sms-gateway (ANDROID_SMS_GATEWAY_URL, _USERNAME, _PASSWORD), TextBee (TEXTBEE_API_KEY, TEXTBEE_DEVICE_ID, optional TEXTBEE_API_BASE), httpSMS (HTTPSMS_API_KEY, HTTPSMS_FROM_NUMBER), then WhatsApp if the caller passed org credentials and no preferred channel. An explicit preferredChannel of sms or whatsapp disables cross-channel fallback.
- The android-sms-gateway adapter polls the message status (0.5, 1, 1.5, 2.5 s) and throws if it is still
PendingorFailed, so the cascade moves on (SALO-749). The ECG watchdog (scripts-vm/ecg-watchdog.mjs, every 2 minutes on the VM) probes it. - WhatsApp OTP uses the approved authentication template
otp_verificationwith a copy-code URL button (sendWhatsAppAuthCode); free-text OTPs were accepted by Meta but never delivered (SALO-2507). - Portal OTP limits (
portal/otp-actions.ts): code valid 10 minutes, 3 sends per 10 min per identifier, 10 sends and 30 verifications per 10 min per IP, 5 wrong guesses burn the code and lock the identifier until it would have expired. A successful WhatsApp OTP inserts anoutbound_messagesrow (portal_otp) so a laterfailedreceipt is recorded. - In
NODE_ENV=developmentan undelivered OTP is logged to the server console and treated as success.
Resend (lib/email/index.ts), sender from EMAIL_FROM (default Kagami noreply address), key RESEND_API_KEY. Without the key every function returns Email not configured; there is no fallback provider. Each send is logged to email_log (status sent/failed, resend_id) when an orgId is supplied. Types: portal/signup/password-reset OTP, booking confirmation, invoice receipt, invitation, shift swap, referral, handoff escalation, exceptions digest, alerts, and sendAppointmentReminder (used only by the legacy reminder route below). Client portal email OTP is a separate path (sendPortalOTPByEmail).
Push notifications
- Tokens: browser subscriptions in
push_subscriptions(endpoint,p256dh,auth); native devices indevice_push_tokens(tokenUNIQUE,platformandroid/ios/web,app_id,last_seen_at; migration0217).registerDeviceTokenActionupserts by token, so a shared device is re-assigned to the latest signed-in user; the caller's org and user come from the session, never the client payload.unregisterDeviceTokenActiondeletes only the caller's own row. notifyUsers(push/notify.ts) fans out to Web Push (ifNEXT_PUBLIC_VAPID_PUBLIC_KEYandVAPID_PRIVATE_KEYexist) and FCM (ifFIREBASE_PROJECT_ID,FIREBASE_CLIENT_EMAIL,FIREBASE_PRIVATE_KEYexist) in parallel, scoped toorgIdand optionallyuserIds. Missing config is a silent no-op; it never throws.- Platform filtering: tokens whose
app_idstarts within.salonos.are skipped (old apps registered under a different Firebase project, SALO-2555).platformis stored but not used to filter. FCM sends in batches of 500 with Android channelsalonos_default, title cut to 100 and body to 240 chars. - Cleanup: Web Push 404/410 deletes the subscription; FCM
registration-token-not-registered/invalid-registration-tokendeletes the token.invalid-argumentis deliberately not treated as dead. - Who gets what:
sendAlert(lib/alerts/send.ts) resolves recipients from owner-configured alert rules (registry.ts: channelsbell,push,whatsapp,email; defaultinbound_messageis push toOPS_ROLES, so stylists never see customer previews, SALO-2078). Staff WhatsApp alerts are a free-form text when the staff member messaged the number in the last 24 h, else templatestaff_alert; opted-out numbers are skipped; email respectsnotification_prefs. DirectnotifyUserscallers:lib/ai/reply-alerts.ts(AI reply held) andlib/playbook/dispatcher.ts.
Reminder crons
Scheduling: recurring jobs run in Supabase pg_cron + pg_net, which POST /api/cron/<name> with x-cron-secret (public.run_cron_endpoint, migration 0176; secrets cron_secret and cron_base_url in Vault; no-op if they are missing). The VM crontab (scripts-vm/crontab) now only runs the ECG watchdog, the AI anomaly job and the playbook scheduler. Auth is cronSecretMatches against CRON_SECRET (fails closed).
| Job (pg_cron name) | Endpoint | Schedule (UTC) |
|---|---|---|
salonos-reminders |
/api/cron/reminders |
*/15 * * * * |
salonos-reminder-auto-release |
/api/cron/reminders/auto-release |
every 15 min (migration 0238) |
salonos-service-recall |
/api/cron/reminders/service-recall |
30 4 * * * (10:00 IST) |
salonos-wallet-expiry |
/api/cron/reminders/wallet-expiry |
30 4 * * * |
salonos-loyalty-points-expiry, -birthdays, -retention-nudges |
see retention.md | 30 4 * * * |
/api/cron/reminders (the live reminder sender), per brand with send_reminders and is_whatsapp_enabled both true:
- Pass 1 at
reminder_hours_before(key prefixreminder), pass 2 fixed at 1 h (reminder-1h, skipped when pass 1 is already 1 h). - Window is
now + (h-1)tonow + (h+1)hours,status = scheduled,starts_at > now; with a 15-minute cadence each appointment is seen in several runs and the idempotency key prevents duplicates. - Skips clients without phone and appointments at stores with
location_messaging_settings.is_whatsapp_enabled = false. - Variables:
appointment_remindertakes 2 ({{1}}name,{{2}}time); a brand buttons template takes 3 (name, service, time). The time is formatted inAsia/Kolkata. - Language comes from
reminder_template_language.
The older reminder_configs / reminder_logs reminder sender (POST /api/reminders/process, with its own email copy) was never scheduled and was removed in SALO-3036. scheduleReminderForAppointment still writes reminder_logs rows on booking, but nothing reads them.
Confirm / Reschedule / Cancel quick replies
Enabled per brand by messaging_settings.reminder_confirm_enabled (default off) and optionally reminder_confirm_template (an approved Meta template with Confirm/Reschedule/Cancel quick-reply buttons, name ^[a-z0-9_]{1,512}$). Only the primary-window reminder asks (never the 1 h nudge).
Sending (cron/reminders/route.ts): if the client wrote to the number in the last 23 h (isInServiceWindow on inbound_messages), an interactive button message is sent with ids appt_confirm:<confirm|reschedule|cancel>:<appointmentId>; if Meta rejects it, or the client is outside the window, the brand's buttons template is sent. Only when one of those was actually sent is appointments.confirmation_status set to pending (only from NULL).
Reply handling is implemented in lib/reminders/confirm-reply.ts (handleReminderReply):
| Reply | Parse | Effect |
|---|---|---|
Interactive button appt_confirm:... |
action + appointment id; id must belong to the sender's phone (last 10 digits) | per action below |
Template quick-reply (type: button) |
payload then text matched to keywords |
appointment = sender's soonest pending upcoming appointment |
| Typed text | exact keyword only (confirm, confirmed, yes confirm, reschedule, re-schedule, change time, cancel, cancel it, cancel appointment), and only if the last outbound to that number in 48 h was a reminder |
as above |
| Confirm | confirmation_status = confirmed, thank-you text, event logged |
|
| Cancel (button) | status = cancelled, confirmation_status = cancelled_by_client, waitlist matcher runs (handleAppointmentCancellation), reply text |
|
| Cancel (typed) | not cancelled directly; handed to the AI agent, which asks first | |
| Reschedule | confirmation_status = reschedule_requested; text "I'd like to reschedule my ... (appointment id: ...)" goes to the AI agent |
Every action is logged in appointment_confirmation_events (action confirm/reschedule/cancel/auto_release, source button/text/cron, from_phone). If the appointment is no longer scheduled or has already started, the client gets a "no longer active" text.
Auto-release (cron/reminders/auto-release): per location with auto_release_enabled (default off, auto_release_hours_before 1-23, default 3; requires confirmation requests on), cancels scheduled appointments still pending that start within the cut-off, sets confirmation_status = released, runs the waitlist matcher, logs auto_release, and raises alert appointment_auto_released. Managers (MANAGER_ROLES) edit these settings.
Current behaviour: handleReminderReply is not called from webhooks/whatsapp/route.ts (the file header in confirm-reply.ts says the hook is "still NOT wired"; a repo-wide search finds no other caller).
Troubleshooting / where to look
| Symptom | Check |
|---|---|
| No confirmation/reminder sent | messaging_settings flags (is_whatsapp_enabled, send_*), store toggle in location_messaging_settings, client has a phone, outbound_messages row for the key (a skipped row means start time already passed) |
Row sent but client got nothing |
Status webhook may not have arrived; check delivered_at/failed_at, phone quality_rating, template status in whatsapp_templates; a stub send also reads sent |
Row failed, error_detail WhatsApp API 400 ... 132000/132001 |
Wrong variable count or template/language not approved; check the template body and reminder_template_language |
Reminder failed and never retried |
Expected for reminder:* keys (no reclaim); delete the row to resend |
Template stuck PENDING |
Settings > WhatsApp templates > Check status; confirm message_template_status_update is subscribed on the Meta app |
| Cron did nothing | cron.job_run_details in Supabase, Vault secrets cron_secret/cron_base_url, CRON_SECRET on the app, endpoint HTTP 401 |
| OTP not arriving | Which channel won (server log lines ... failed, trying next channel), gateway reachability (ECG logs/ecg-status.json, GET /api/health), otp_verification approved |
| Push not arriving | VAPID/Firebase env vars set, device_push_tokens row exists, app_id not in.salonos.*, alert rule includes push |
| Webhook rejected | server log [whatsapp_webhook] rejected: (missing or mismatched META_APP_SECRET/signature) or verify rejected |