Messaging
How a message reaches a guest, what is logged and what never is.
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
- Loads the guest in the given hotel (never across hotels).
- Reads the guest's current consent for the channel (
guest_consents). No consent: nothing is sent and the row isskipped_no_consent. - Renders the message. Email uses the branded hotel templates (see Hotel emails), sent as
"<hotel display name>" <EMAIL_FROM address>with the hotel's reply-to fromhotel_settings, and carriesList-UnsubscribeandList-Unsubscribe-Postheaders (one tap unsubscribe, RFC 8058, answered byPOST /unsubscribe/<token>). The template footer holds the one unsubscribe link, the dispatcher adds none, so an email never shows two. - 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=productionandMESSAGING_LIVE=true. Previews, tests, local and staging only log: the row sayssentwith provider idlog-onlyand keeps the rendered message inpreview. - Updates the row.
The messages table
One row per message, scoped by hotel and removed with the guest (guest and hotel 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 |
preview | only for a message that was not really sent: the email subject and html, or the WhatsApp text with its STOP line. Always empty for a real send |
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 recipient column, and nothing logs the phone, email or name. A real send keeps no body.
preview holds what the guest would have read, so it contains their name and their personal links. It lives as long as the row: deleting the guest removes it. It is not part of the guest export, which does not carry the message log.
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.
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:
- Sender: the phone is
message.from, elseconversation.phone_number. With a WhatsApp username both can be missing and onlyfrom_user_id(the business scoped user id) is sent. Ritorno does not store that id, so such a STOP is matched only when it replies to one of our messages (context.id). Otherwise no consent changes and the api logs[whatsapp-stop] sender not matched, with no id or number: find the message in the Kapso inbox by its time. - 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, plus every hotel that still keeps a scan of the number (a welcome writes no
messagesrow). A number we never wrote to is unsubscribed in every hotel, the safe side. - Consent:
applyStopReplywithdraws WhatsApp consent with a consent event, sourcestop_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.
Scan to WhatsApp
The QR capture page has a Continue on WhatsApp button when WHATSAPP_BUSINESS_NUMBER is set. It opens wa.me on the one shared Ritorno number with a short message in the page's language and a reference code. The guest sees Ritorno as the sender, not the hotel, and the page and the reply both say so.
- Code:
signScanCodeputs the hotel slug, spot and language in the code and signs it. Nothing is stored when the page is opened. A made up or edited code is ignored, so codes can't list hotels, and the reply never repeats the spot or anything else the guest typed. - Reply:
handleWhatsAppScansends one scripted free-form welcome (inside the 24 hour window, no template): hotel name, the welcome offer (or the default gift line), the capture page link when that number has not signed up with the hotel, that requests go to the front desk because the hotel team does not see what is written (only number and spot), and the STOP line. No message balance is charged and nomessagesrow is written. Log-only outside live messaging. - Limits: one reply per hotel and number per 24 hours, 5 codes per number per day, 100 per hotel per hour. A suspended hotel gets no reply and nothing is stored. A failed send is logged (hotel id and status only) and not retried. A redelivery is ignored (same message id within 24 hours, or a message over an hour old), so it can't bring back a removed row.
- Hidden number: a sender with only
from_user_idgets the welcome sent to that id, with a line saying the hotel does not get their number. Nothing is stored and staff are not told, since they could not write back. - Not consent: writing to us creates no guest and no consent, and nothing else is ever sent to that number by Ritorno.
- Staff: every member of the hotel gets an inbox notification (hotel and spot, never the number).
/whatsappin the dashboard lists the last 30 days, and Write on WhatsApp openswa.meto the guest from the staff member's own WhatsApp. Staff see the number and spot, never the guest's message. Ritorno does not see that conversation. This is not a team inbox and there is no AI. - Stored:
whatsapp_scans, one row per hotel and number: phone, spot, language, two timestamps. No name, no message text. Rows go after 30 days (purge-whatsapp-scansjob, hourly), on STOP (from every hotel), when the guest is deleted, with delete all, with the hotel, or with Remove in the list (whatsappScans.remove). - Export: the guest export has that guest's
whatsappScans; the hotel JSON export has all of them, numbers that never signed up included. The CSV has awhatsapp_scanscolumn for signed-up guests only.
Setup: set WHATSAPP_BUSINESS_NUMBER to the number behind WHATSAPP_PHONE_NUMBER_ID, and subscribe the Kapso webhook to whatsapp.message.received.
Dashboard
/messages in the dashboard lists the hotel's messages in en, fr and ar, newest first, loading more as you scroll. 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 cursor and returns a total and a nextCursor). 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 recipient: the log does not hold it. Dates use the hotel's timezone.
Messages that were not sent
Where providers are log-only, a row that has a preview shows Development: not sent (en, fr, ar) instead of its status, with a Preview button: the rendered email (in an iframe with an empty sandbox, so no scripts, forms or popups) or the WhatsApp text. messages.list flags those rows with notSent, and messages.preview (GET /messages/{id}/preview) returns the text, only for the active hotel. Real sends never get the tag. Messages skipped for consent or balance were never rendered, so there is nothing to preview. Test emails and manager alerts are not guest messages and do not show here.
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.
A scheduled campaign that has not started can go "back to draft" (POST /campaigns/{id}/unschedule), then be edited and scheduled again. It cannot once it is sending: the job moves the campaign to sending in one conditional update before it sends anything, and "back to draft" only matches scheduled, so exactly one of the two wins and a reschedule can never send twice. The job re-reads each campaign at that point, so an edit or a new time made while it was working is respected.
"Duplicate" (POST /campaigns/{id}/duplicate) copies the message, audience, channel and offer of any campaign into a new draft with no results. The copy is a separate campaign: sending it reaches guests who already got the original.
Manager alerts
Manager alerts go by email only. notifyManager(context, hotelId, text, email?) (packages/orpc/src/lib/manager-alerts.ts) emails the hotel reply-to, else the first owner, and returns false when there is neither. 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 in Hotel settings calls hotel.alerts.test.
Weekly owner digest
The owner-digest job runs every hour. On Monday, from 09:00 until quiet hours in the hotel's timezone, every member with the owner role (not the reply-to address) gets one email about the Monday to Sunday that just ended, next to the week before: new and returning guests, messages sent, offers redeemed, survey answers, the average score and the low score cases still open. A week without activity says so and suggests placing the QR codes. It holds counts only, never a guest's name, contact details or comment.
It is written in the hotel's guest language (en, fr or ar), sent by email only with the ownerDigest template, and only logged outside live messaging.
- Suspended hotels and hotels without an owner get nothing.
hotel_settings.weekly_digestis on by default. The footer link and theList-Unsubscribeheader open Hotel settings, Weekly summary (/hotel?hotel=<id>#weekly-digest), where an owner or manager turns it off. When that is not the hotel on screen, the page shows no settings: a member gets a button to switch to it, anyone else is told the link is for another hotel. The switch is per hotel, so it applies to all its owners.hotel_settings.last_digest_weekis claimed once the email is built and before sending, so a failure while building is tried again the next hour and a rerun or a second worker never sends a week twice. A retryable provider error (see below the automatic messages) releases the claim for the next hour, with the same ResendIdempotency-Keyper owner. A week missed for the whole Monday is not sent later.
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, whether the send call fails or a whatsapp.message.failed webhook arrives later (a Meta payment error, for example). The refund is the debited amount and happens once, redeliveries included. 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.