---
title: "Messaging"
description: "How a message reaches a guest, what is logged and what never is."
url: https://docs-staging-ritorno.findmalek.engineer/docs/messaging
markdown: https://docs-staging-ritorno.findmalek.engineer/docs/messaging.md
---

# Messaging

Every message to a guest goes through one function, `sendToGuest` in `packages/orpc/src/lib/messages.ts`. Nothing else talks to a provider about a guest.

## What it does

1. Loads the guest in the given hotel (never across hotels).
2. Reads the guest's **current** consent for the channel (`guest_consents`). No consent: nothing is sent and the row is `skipped_no_consent`.
3. Renders the message. Email uses the branded hotel templates (see [Hotel emails](https://docs-staging-ritorno.findmalek.engineer/docs/hotel-emails.md)), sent as `"<hotel display name>" <EMAIL_FROM address>` with the hotel's reply-to from `hotel_settings`, and carries `List-Unsubscribe` and `List-Unsubscribe-Post` headers (one tap unsubscribe, RFC 8058, answered by `POST /unsubscribe/<token>`). The template footer holds the one unsubscribe link, the dispatcher adds none, so an email never shows two.
4. Sends through the notification package (WhatsApp: the template named for the message type, in the guest's language, with named variables; the STOP line is the template footer). Providers only send for real when `NODE_ENV=production` and `MESSAGING_LIVE=true`. Previews, tests, local and staging only log: the row says `sent` with provider id `log-only`.
5. Updates the row.

## The `messages` table

One row per message, scoped by hotel and removed with the guest (export and delete cover it).

| Column | Meaning |
| --- | --- |
| `hotel_id`, `guest_id` | whose message it is |
| `channel` | `email` or `whatsapp` |
| `template_key`, `language` | which template, in which language |
| `status` | `queued`, `sent`, `delivered`, `failed`, `skipped_no_consent`, `skipped_no_balance` |
| `provider_id` | the provider's message id, used to match status webhooks |
| `error_code` | a short code (`no_recipient`, `channel_not_configured`, `send_failed` or the provider's code), never the provider's text |
| `created_at`, `sent_at`, `delivered_at`, `failed_at` | timestamps |

There is no body and no recipient column, and nothing logs the phone, email or name.

## Status webhooks

`applyDeliveryUpdate` moves a row forward by provider id: `queued → sent → delivered`. A late `sent` never undoes `delivered`. `failed` is accepted from any earlier state.

### Resend events

`POST /resend/webhook` takes Resend's events, verified with the Svix signature (`RESEND_WEBHOOK_SECRET`, answers 404 without it). `email.delivered` and `email.bounced` / `email.failed` go through `applyDeliveryUpdate` (a bounce stores `error_code = bounced`). `email.complained` (the guest hit "spam") withdraws their email consent with a consent event, source `guest_request`, so nothing more goes out. Set the webhook in Resend to the api's `/resend/webhook` with those events.

### Kapso events

`POST /whatsapp/webhook` takes Kapso's message events, checked with the `X-Webhook-Signature` header (hex HMAC sha256 of the raw body with `KAPSO_WEBHOOK_SECRET`, answers 404 without it). `whatsapp.message.sent`, `delivered` and `failed` go through `applyDeliveryUpdate`; a failure stores Meta's numeric code in `error_code`. WhatsApp messages use named, approved templates, one per message type and language: see [WhatsApp templates](https://docs-staging-ritorno.findmalek.engineer/docs/whatsapp-templates.md).

### Inbound STOP

The same webhook gets `whatsapp.message.received` (single or batched). `handleInboundWhatsApp` ignores everything except a text that is, as a whole, a stop word: `stop`, `arrêt`, `إيقاف`, `توقف` and the usual variants (case, accents and punctuation do not matter, "don't stop" does nothing). Then:

- **Hotel:** one business number serves every hotel, so the number alone does not say which hotel. The hotel is the one whose WhatsApp message that guest number got last. A number we never wrote to is unsubscribed in every hotel, the safe side.
- **Consent:** `applyStopReply` withdraws WhatsApp consent with a consent event, source `stop_reply`. Email consent is untouched.
- **Reply:** when a consent really changed, one free-form confirmation goes back in the guest's language (allowed inside the 24 hour window the guest just opened). A repeated delivery changes nothing and sends nothing. Log-only outside live messaging.

## Dashboard

`/messages` in the dashboard lists the hotel's messages in en, fr and ar, 25 a page, newest first. Owners, managers and staff can read it. Filters live in the url: channel, status, template and the last 7, 30 or 90 days (`messages.list` takes `channel`, `status`, `template`, `days`, `limit` and `offset` and returns a `total`). Each row shows the guest, the channel, the template by its readable name, the language and the status, plus the provider error code on a failure. Never the body or the recipient: the log does not hold them. Dates use the hotel's timezone.

## Automatic messages

Automations are pg-boss jobs built by `createMessageJobs` (`packages/orpc/src/jobs`). The api hands the dispatcher's services to them, so they only ever send through `sendToGuest`.

Every automatic send first claims a row in `automation_sends` (unique per guest, `kind`, `period` and channel). A retry, a second enqueue or a second worker finds the row and sends nothing. `kind` is the automation, `period` repeats it (empty for once, the year for yearly).

`claimAndSend` in `packages/orpc/src/lib/automations.ts` does the claim and the send for every automation. A failure that cannot have sent anything (429, or a connect error such as `ECONNREFUSED`) is retried up to three times in all, 2 then 4 seconds apart, while the claim is held, so no other worker sends it too. A 5xx or a timeout may mean the provider accepted the message, so it is only retried for email: every try carries the same Resend `Idempotency-Key` (`automation-send:<claim id>`) and Resend drops a repeat. Kapso has no such key, so on WhatsApp those stay failed. Any other failure (a 4xx, a bad template, no recipient) is not retried, and a send still failing after the third try stays failed. Each try is its own row in `messages`. The retries live here and not in pg-boss: a job rerun finds the claim and sends nothing. Sends are paced 250 ms apart in the welcome, birthday, holiday, survey and campaign jobs, so a provider never sees a burst. Like campaigns, the birthday and holiday jobs run every minute and send at most 20 messages per hotel per run to guests without a claim yet, so a run stays short and the next minute picks up the rest; pg-boss fails a run still active after 10 minutes (`expireInSeconds`).

| Job | When | Who |
| --- | --- | --- |
| `welcome-guest` | queued right after a guest is saved from the QR page or staff quick add, never for a csv import (an old list would get a burst of welcomes) | the channels the guest agreed to, once per guest and channel. From the QR page also at most once per guest every 30 days and 60 per hotel per hour |
| `birthday-guests` | every minute, one batch per hotel from 09:00 to 20:59 in its own timezone | guests whose birthday is today and who agreed to a channel, once per year |
| `holiday-guests` | every minute, same window | guests who agreed to a channel the hotel picked for a holiday it switched on, one holiday message per channel and day |

The welcome carries the hotel's newest active offer with the `welcome` trigger that can be redeemed right now, with the guest's own code and the page link (`triggerOffer` in `packages/orpc/src/lib/automations.ts`). Without one it goes out without an offer. A failed queue never fails the sign-up.

### Birthday

pg-boss cron runs in UTC, hotels do not, so the job runs every minute and sends each hotel's batch from 09:00 local time (never in quiet hours, 21:00 to 08:00). A worker that was down at 09:00 still sends the same day. The claim (`kind` `birthday`, `period` the hotel's local year) keeps it to one message a year per guest and channel. Someone born on 29 February is celebrated on 28 February in a year without one. The message carries the hotel's newest redeemable `birthday` offer; a hotel without one sends nothing. Local time helpers: `@ritorno/common/hotel-time`.

### Holidays

The list lives in `packages/common/src/holidays.ts`: Ramadan start, Eid al-Fitr, Eid al-Adha, Mawlid, Independence Day (20 March), Republic Day (25 July) and New Year, each with its name and greeting in en, fr and ar. Fixed dates are `MM-DD`; the Islamic ones come from a static table (Umm al-Qura calendar, 2026 to 2035), no network. Tunisia sights the moon locally, so a date can be a day off. A test fails when the table no longer covers the next five years.

A hotel switches each holiday on or off and picks the channel (both, email, WhatsApp) in the dashboard under Holidays (owners and managers). Everything is off by default: no row means no message. The greeting is sent with the `message` hotel email template, a text the hotel or the product wrote, already in the guest's language, with the unsubscribe or STOP line like every other message.

In the dashboard campaign list, "failed" is a display state, not a campaign status: the campaign is `sent` but every message to it failed.

## Manager alerts

A hotel manager links a Telegram chat in **Hotel** settings: the dashboard shows a one-time code (valid 15 minutes) and the bot link `https://t.me/<TELEGRAM_BOT_USERNAME>?start=<code>`. When the bot receives `/start <code>` on `/telegram/webhook` (secret header `TELEGRAM_WEBHOOK_SECRET` checked), the chat id is stored in `hotel_settings.telegram_chat_id` and the code is cleared, so it works once and only for the hotel that issued it. Without a code, `/start` still answers with the chat id, for the operator's own `TELEGRAM_CHAT_ID`.

`notifyManager(context, hotelId, text, email?)` (`@ritorno/orpc/manager-alerts`) sends `text` to the hotel's linked chat and falls back to email (the hotel reply-to, else the owners) when there is no chat or Telegram fails. The email is the `alert` template in the hotel's language; the low score alert fills it with the hotel, the score, the comment and the guest's first name, never contact details. Like every provider it only logs outside live messaging. The **Send a test alert** button calls `hotel.alerts.test`.

## Prepaid WhatsApp balance

WhatsApp is paid per message, so each hotel has a prepaid balance in TND millimes (integers, 1 TND = 1000). `hotel_balance` holds the balance, `balance_ledger` is the append-only history (`top_up` and `refund` positive, `usage` negative, so the balance always equals the ledger sum). The super admin tops a hotel up on the admin hotel page (`admin.hotels.balance.topUp`, audited). The hotel sees balance, this month's usage and the latest movements on **Usage** (`/usage`, owners and managers), and a warning at the top of **Messages** under 5 TND.

The dispatcher prices every WhatsApp message with `whatsappPriceMillimes` (`packages/common/src/pricing.ts`): provider cost per message type plus a 25 percent margin, rounded up. It takes the price off the balance atomically before sending. Not enough balance: the message is not sent and the row says `skipped_no_balance`. A message the provider refuses is refunded. Email is free and never touches the balance. Log-only sends (previews, tests, local) are priced too, so the flow behaves the same everywhere.

The cost values (utility 25 millimes, marketing 95 millimes) are **untested guesses** from Meta's public rates. Check them against the first real Meta and Kapso invoice before charging a hotel.
