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-only. - 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.
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:
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.
Dashboard
/messages in the dashboard lists the hotel's latest messages in en, fr and ar. Owners, managers and staff can read it.
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).
| Job | When | Who |
|---|---|---|
welcome-guest | queued right after a guest is saved from the QR page, staff quick add or csv import | the channels the guest agreed to, once per guest and channel |
birthday-guests | every hour, which handles each 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 hour, 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 hourly and each hotel is handled on its first run after 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: @le-hoetel/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.
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) (@le-hoetel/orpc/manager-alerts) sends 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. Like every provider it only logs outside live messaging. The low-score alert will call it. 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.