Retention Engine & No-Show Forecasting
How Kagami scores client churn risk, sends rebook and win-back nudges, attributes recovered visits, and predicts appointment no-shows.
17 min read
Overview
This page documents the engine behind the Retention Engine panel on the Retention page, and the forecasting helpers that score appointments for no-show risk. The user-facing retention products (packages, Club and Value Packs, loyalty, gift cards) are covered in Retention Programs. The journeys screen is covered in Marketing.

The engine has four parts:
| Part | What it does | Runs |
|---|---|---|
| Churn scorer | Puts every active client in a tier from days since last visit, plus a risk score | On page load (live) |
| Nudge cron | Enrolls inactive clients in the rebook_nudge or win_back journey |
Daily |
| Journey sender | Sends the due WhatsApp template messages | Every 15 minutes |
| Attribution | Credits a paid invoice to a nudge sent in the previous 30 days | On page load (live) |
Separately, the no-show scorer estimates the chance that an upcoming booking does not turn up. It feeds the "Show-up chance" line in the appointment panel and the No-Show Risk tab under Analytics → AI Forecasting.
Nothing is sent until a manager enables the journeys. Default journeys are created disabled (is_enabled = false). Marketing → Automated Journeys shows which journeys a brand has switched on.
Churn tiers and thresholds
Days since last visit is floor((now - last visit) / 24h). The last visit is the later of clients.last_visit_at and the client's most recent paid invoice in the last 90 days. The invoice check stops walk-in clients with a stale last_visit_at from being offered a win-back right after they paid.
| Tier | Rule | Base score | Recommended action |
|---|---|---|---|
booked |
Has an upcoming appointment (status scheduled, pending_confirmation, confirmed or in_progress, starting now or later) |
5 | None |
never_visited |
No usable last visit date | 0 | None |
healthy |
Under 30 days | 10 | None |
at_risk |
30 to 59 days | 40 | Rebook nudge |
lapsed |
60 to 119 days | 60 | Win-back |
churned |
120 days or more | 80 | Win-back |
The booked check runs first, so a client with an upcoming booking is never at risk, whatever the other signals say.
Risk score modifiers
| Signal | Effect |
|---|---|
3 or more visits, in at_risk or lapsed |
+10 |
3 or more visits, in churned |
+5 |
Low NPS: lowest rating of 3 stars or less in the last 60 days (ai_nps_surveys) |
+25 |
| Wallet with a positive balance that expires within the next 14 days | +15 |
The score is clamped to 0 to 100. A healthy client with a low NPS or an expiring wallet is promoted to at_risk. Clients at 30 days or more keep their time-based tier.
recommendedTrigger is win_back at 60 days or more, rebook_nudge for any at_risk client, and none otherwise. A promoted client under 30 days is therefore recommended a rebook nudge. The daily cron never sends to someone under 30 days. Only a manual send does.
Snapshot and queue
getRetentionEngineSnapshot(brandId, locationId?) loads, for the active clients of one brand:
- Clients with
status = active. - Future open appointments.
- The brand's four engine journeys (
rebook_nudge,win_back,no_show,birthday). - Paid invoices from the last 90 days.
- NPS ratings of 3 or less from the last 60 days.
- Expiring wallets.
- WhatsApp settings.
It returns the tier counts, recovery numbers, per-journey health and the actionable queue.
- Queue shape. The queue keeps the 15 highest-risk clients from each of
at_risk,lapsedandchurned, sorted by score then visit count. A large churned backlog therefore cannot hide at-risk rows. - Store scope. With an active store, clients are filtered by
registration_location_id. Appointments and invoices are filtered bylocation_id. - Last nudge shown. A client's last nudge only shows if it was sent on or after their last visit. A nudge from an earlier lapse cycle is ignored.
- Not shown.
healthy,bookedandnever_visitedclients are counted but are not in the queue.
Rebook nudge and win-back ladder
The nudge decision is the pure function decideRetentionNudge in lib/marketing/retention-nudges.ts.
| Constant | Value |
|---|---|
REBOOK_DAYS |
30 |
WINBACK_STEP_DAYS |
60, 90, 120 |
MAX_INACTIVE_DAYS |
365 |
STEP_COOLDOWN_DAYS |
28 |
Decision rules
- Do nothing if days since last visit is under 30 or over 365.
- A prior enrollment with status
cancelledthat was created less than 28 days ago blocks any new nudge. This covers a failed or rejected send. Without it, the daily cron would re-enroll the client every day. - Only enrollments with status
activeorcompleted, created on or after the client's last visit, count as part of the current lapse cycle. - Under 60 days: send one
rebook_nudge, but only if none was already sent in this cycle. - 60 days or more: send the next
win_backstep. Step N needs at least 60, 90 or 120 days since the last visit. The previous win-back in the cycle must be at least 28 days old. At most 3 win-back steps are sent per cycle.
The day counts are minimums, not exact send days. A client first found at 200 days gets step 1 on that run. Steps 2 and 3 follow at least 28 days apart. A client who visits again starts a new cycle.
What the daily cron does
runRetentionNudges loops over every brand. A brand is skipped unless it has an enabled win_back or rebook_nudge journey. For each brand it does the following:
- Load candidates. Active clients with a phone number, plus paid invoices and open or completed appointments from the last 365 days.
- Find the latest past visit. It comes from
last_visit_at, paid invoices, or completed appointments older than 30 days. - Skip active clients. A client with any visit, paid invoice, or active-status appointment (including future bookings) in the last 30 days is skipped. Appointment statuses that count are
scheduled,pending_confirmation,confirmed,in_progressandcompleted.cancelledandno_showdo not count. - Drop opted-out clients for the
whatsappchannel (see Opt-out handling). - Decide. It loads each remaining client's prior nudge enrollments from the last 365 days and runs
decideRetentionNudge. - Enroll. If the decision's journey is enabled for the brand, it inserts a
journey_enrollmentsrow.send_atis now plus the journey'sdelay_hours. Defaultdelay_hoursis 0 for both nudges.trigger_dataholdslast_visit_at,days_since_visitandwinback_step.
If only one of the two journeys is enabled, clients whose decision points at the disabled one are skipped.
Manual send from the queue
The "Send win-back" or "Send rebook nudge" button calls enrollClientWinbackAction. It enforces the following:
- The caller needs the
marketing.campaignspermission. By default this goes toorg_owner,brand_managerandlocation_manager. - The client must belong to the brand, and the caller must have access to the brand.
- An opted-out client is refused with the error "Client opted out of WhatsApp messages."
- The matching journey must exist and be enabled. Otherwise the error is "Enable this journey in Marketing → Automated Journeys first."
- If the client has any
activeorcompletedrebook or win-back enrollment created in the last 28 days, it is refused. The error names the date: "A recall or win-back was already queued ... Wait 28 days between messages." - The enrollment uses
enrollInJourneywithtrigger_data.source = "retention_engine". It carries nowinback_step, so the queue shows "Nudge sent" rather than "Step N/3". enrollInJourneyadds its own check. A second enrollment in the same journey for the same client within 24 hours returns "duplicate". A database failure returns "failed" and shows "Could not save the message to the send queue". Both messages surface in the row.
Sending
processDueJourneySteps picks up to 50 active enrollments with send_at <= now. It first pushes send_at forward by 10 minutes to claim them. This lease stops overlapping runs from double-sending and frees the row again if a run crashes.
For each enrollment it applies these checks in order:
| Check | Result |
|---|---|
| Journey or client row missing | Enrollment cancelled |
| Client opted out on the journey's channel | cancelled, "Client opted out" |
| Client has no phone | completed, error "No phone number", sent_at set (see Edge cases) |
Journey has no wa_template_name |
cancelled |
| Brand's WhatsApp disabled or not configured | cancelled |
For rebook_nudge, win_back and no_show: the client created any appointment (status scheduled, pending_confirmation, confirmed, in_progress or completed) or had any paid invoice after the enrollment was created |
cancelled, "Client rebooked before send" |
| Template send throws | cancelled, first 500 characters of the real error |
| Success | completed, sent_at set |
The message is a WhatsApp template send. The two nudge templates receive two positional variables: the client's display name and the brand name. The journey's message_template text shown and editable in Marketing → Journeys is not what is sent. The approved Meta template named in wa_template_name is.
Journey templates
| Journey trigger | wa_template_name |
Purpose |
|---|---|---|
rebook_nudge |
salon_rebook_nudge |
"Time for your next visit" reminder to a 30 to 59 day client |
win_back |
salon_win_back |
"We miss you" message to a client at 60 days or more |
no_show |
salon_no_show |
Follow-up after staff mark a started appointment as no-show |
birthday |
salon_birthday |
Birthday greeting (a separate birthdays cron enrolls it) |
The other journeys (welcome, post_visit, review_request) use salon_welcome, salon_post_visit and salon_review_request. A journey whose template is not approved on the brand's WhatsApp account fails every send and the enrollment ends cancelled with the provider error. Template approval status is managed with Meta in the brand's WhatsApp Business account.
The no_show journey is enrolled by updateAppointmentStatusAction when staff set an appointment to no_show and the start time has already passed. Its default delay is 1 hour.
Recovery attribution
computeWinbackAttribution credits returning clients to nudges. The page shows it as "Recovered (90d)".
- Take
journey_enrollmentswith statuscompletedandsent_atin the last 90 days, for journeys with triggerwin_backorrebook_nudge. With an active store, keep only clients in that store's client set. - Reduce to one send per client: the earliest one in the window.
- Take the brand's paid invoices from the last 90 days (store-scoped if a store is active).
- A client is recovered if they have a paid invoice with
sent_at < paid_at <= sent_at + 30 days. Only the earliest qualifying invoice is counted, and itstotal_minoris added to recovered revenue. - The summary shows
sentLast90d(distinct clients),recoveredCount,recoveryRatePct = round(recovered / sent × 100)andrecoveredRevenueMinor.
Each journey tile shows how many completed enrollments of that trigger were sent in the last 30 days. Journeys that are is_enabled = false show as "Paused".
The attribution is time-based. It does not check that the invoice relates to the nudge, only that it was paid in the 30 days after the first send. Invoices of any kind count.
Opt-out handling
Every layer fails closed. optedOutClientIds(clientIds, channel) reads client_consents. A client is opted out when any row for the given channel or all has granted = false for purpose marketing or transactional. A refusal of transactional messages on WhatsApp also blocks promotions. If the consent lookup errors, everyone in the batch is treated as opted out.
The check runs in three places:
- The daily cron, before it creates enrollments (channel hard-coded to
whatsapp). - The manual queue action, before enrolling.
- The sender, just before each message (using the journey's channel).
A client can opt out in two ways:
- STOP reply. In the WhatsApp AI chat, a STOP-type message writes a
whatsapp_opt_outsrow. For known clients it also upserts aclient_consentsrow (marketing, whatsapp,granted = false, sourcewhatsapp_stop). A START-type reply removes only the refusal that STOP recorded. A refusal entered by staff stays. - Staff-recorded consent on the client record.
Cron jobs
All recurring jobs run from Supabase pg_cron. Each job posts to an app endpoint through run_cron_endpoint(), with the secret in the x-cron-secret header. The secret and base URL come from Vault secrets. If the Vault secrets are missing, the function logs a warning and does nothing. Both routes compare the header with CRON_SECRET in constant time and fail closed: an unset secret rejects every request with 401. The process-journeys route also accepts the secret as a Bearer token.
| Job name | Endpoint | Schedule (UTC) | What it does |
|---|---|---|---|
salonos-retention-nudges |
POST /api/cron/retention-nudges |
30 4 * * * (10:00 IST daily) |
Enrolls clients in rebook and win-back journeys. Returns { enrolled, timestamp } |
salonos-process-journeys |
POST /api/cron/process-journeys |
*/15 * * * * |
Sends due journey messages. Returns { ok, processed } |
/api/cron/retention-nudges returns 500 with "Database query failed" when the run throws. The error is captured server-side. /api/cron/reminders/service-recall is a separate per-service recall system with its own window. It does not use the churn tiers.
Brand failures: a query error for one brand throws and stops the whole run, so later brands are not processed that day. A failed enrollment insert for one batch is captured but does not stop the run, and the failed batch is not counted in enrolled.
Where owners configure and view it
| What | Where |
|---|---|
| Churn tier counts, recovery, workflow health, win-back queue | Retention page → Retention Engine panel (/dashboard/retention) |
| Turn journeys on or off, edit delay | Marketing → Automated Journeys (/dashboard/marketing/journeys) |
| WhatsApp credentials | Settings → Messaging (a banner on the panel warns when they are missing) |
| No-show risk list | Analytics → AI Forecasting → "No-Show Risk" tab |
| Show-up chance for one booking | Appointment detail panel on the day and week calendars |
The panel's four KPI tiles are At risk (30 to 59 days or signals), Lapsed (60 to 119 days), Churned (120 days or more) and Recovered (90 days). The queue tabs filter by tier. Each row shows the tier, the risk score, the reasons, the win-back step and the action button. The step column reads "Step N/3" for a win-back, "Nudge sent" for any other nudge, or "Not contacted". A row without a phone number shows "No phone".
If the engine snapshot fails to load, the page shows a red alert with the real error and keeps the rest of the Retention page working.
Data model
| Table / column | Used for |
|---|---|
clients.last_visit_at, visit_count |
Churn tiering. Maintained by a trigger on appointments (migrations 0267 and 0272, also set by Zylu imports) |
appointments (status, starts_at, confirmation_status) |
Future bookings, history for no-show scoring |
invoices (status = paid, paid_at, total_minor) |
Last-visit correction, attribution |
journeys (trigger, is_enabled, delay_hours, wa_template_name, channel) |
One row per brand and trigger (unique). Created disabled by upsertDefaultJourneys |
journey_enrollments (status, send_at, sent_at, error, trigger_data) |
The nudge queue and history. Status is active, completed or cancelled. trigger_data.winback_step holds the ladder step |
client_consents, whatsapp_opt_outs |
Opt-out |
ai_nps_surveys (rating, rated_at) |
Low-NPS signal |
wallets (balance_minor, expires_at, is_active) |
Expiring-wallet signal |
messaging_settings |
WhatsApp readiness flag on the panel |
Permissions
| Action | Who |
|---|---|
| Open the Retention page | ADMIN_ROLES: super_admin, org_owner, brand_manager, location_manager (route access rule) |
| Queue a win-back or rebook nudge manually | marketing.campaigns permission (default org_owner, brand_manager, location_manager) |
| See the show-up chance | Any signed-in user who can see the appointment |
No-show scoring
scoreNoShow in lib/forecasting/index.ts is a pure function. It returns a probability from 0 to 1 that the client does not turn up, a risk level and a list of human-readable factors.
Inputs
- History. The client's past
completedandno_showappointments in the brand (all time). Cancellations are not counted as visits. - Slot. The slot start, read in the location's timezone (default
Asia/Kolkata). - Reminder reply. The appointment's
confirmation_status, set by the 24 hour reminder confirm flow (migration 0238, SALO-2179). It is null when the client was never asked. The reminder only asks for confirmation when the brand hasreminder_confirm_enabledon and a confirm template configured.
Formula
- Base:
(noShows + 0.15 × 2) / (visits + 2). A client with no history scores 0.15. Smoothing stops one missed visit out of one from reading as 100%. - Slot hour: under 09:00 adds 0.10 ("Early morning slot"). 19:00 or later adds 0.05 ("Late evening slot").
- Weekend: Saturday or Sunday subtracts 0.05 ("Weekend — usually reliable"). This is a fixed assumption, not learned from the brand's data.
- Reminder reply:
confirmation_status |
Effect |
|---|---|
confirmed |
multiply by 0.4 |
pending |
add 0.10 |
reschedule_requested |
add 0.25 |
cancelled_by_client or released |
set to 0.95 |
- Clamp to 0.02 to 0.95 and round to 2 decimals.
- A "historical no-show rate" factor is added when the past rate is above 30%. If no factor applies the list reads "Average historical rate".
Risk levels
| Level | Probability |
|---|---|
high |
0.40 or more |
medium |
0.20 to 0.39 |
low |
under 0.20 |
For example, a new client booking at 11:00 on a weekday who has not replied to the reminder scores 0.25 (medium). With a confirmed reply it is 0.06 (low). A new client at 08:00 scores 0.25 (medium).
The "Show-up chance" chip
getShowUpChanceAction(appointmentId) is called by the ShowUpChance component in the appointment detail panel. The panel is part of the day calendar and the week calendar.
- It shows
Show-up chance: N%, where N isround((1 - probability) × 100), followed by the factors separated by dots. - The percentage is green for
lowrisk, amber formediumand red forhigh. - It returns nothing when the appointment is not open (status other than
scheduled,confirmedorpending_confirmation), has no client, or is outside the caller's org. - It re-scores when the appointment status changes while the panel is open.
- If the call fails the chip is not shown.
No-Show Risk tab
predictNoShows(brandId, locationId?) scores open appointments (same three statuses) starting within the next 48 hours. It reads at most 50 appointments, the soonest first, then sorts them by probability. Each card shows the probability, risk level, factors and a recommendation:
- High risk: "Call or WhatsApp the client today"
- Medium risk: "Send a reminder 1h before"
- Low risk: "No action needed"
With an active store the list is limited to that store. If the predictor fails, the page logs the error and shows an empty list, so the demand forecast still loads. The same prediction feeds the custom analytics dashboard.
Demand forecast (same module)
forecastDemand produces the 30-day "Demand" tab:
- It averages appointments and paid revenue per weekday over the last 90 days. Appointment statuses counted are
completedandscheduled. - Confidence per weekday is
highwith 8 or more sample days,mediumwith 4 to 7, otherwiselow. - A day is "peak" above 1.3 times the 30-day average and "low" below 0.7 times.
- The staffing narrative comes from the AI gateway ("summarize" capability). If the AI call fails, a plain computed sentence is used instead and the page still renders.
Edge cases and failure behaviour
- No phone. The engine queue shows such clients, but the action column says "No phone". The nudge cron never enrolls a client without a phone. If an enrollment's client loses their phone before sending, it is marked
completedwith the error "No phone number" and asent_at. It is then counted as a send by attribution and the 30-day tile. - Snapshot load failures. Failed reads of journeys, NPS, wallets or messaging settings throw an explicit error ("Retention engine could not load ...") instead of showing zero counts.
- Expiry of the lookback. The cron ignores clients whose last visit is over 365 days ago. The panel still tiers them as
churned, and a manager can still queue a win-back by hand. - Rebooked clients. A queued nudge is cancelled at send time if the client booked or paid after being enrolled.
- Cooldown is shared by both nudge types for manual sends only. The cron's 28-day spacing applies between win-back steps, and between a failed enrollment and the next try. It does not separate a rebook nudge from the first win-back. If the cron is enabled late, a client can get the rebook nudge on one day and win-back step 1 the next.
- Send throughput. The sender handles 50 enrollments per 15-minute run, so a large first-day backlog takes several hours to drain.
- Journey toggle. Journeys default to disabled. Nothing is sent for a brand until a manager enables the journey and its WhatsApp template is approved.
Source
| Area | File |
|---|---|
| Churn scorer, attribution, snapshot | web/src/lib/retention/churn-engine.ts |
| Nudge decision and cron logic | web/src/lib/marketing/retention-nudges.ts |
| Journey enroll and send, default journeys | web/src/lib/marketing/journeys.ts |
| Opt-out lookup | web/src/lib/marketing/opt-out.ts |
| STOP and START handling | web/src/lib/ai/whatsapp-opt-out.ts |
| Manual queue action | web/src/lib/retention/admin-actions.ts (enrollClientWinbackAction) |
| Cron routes | web/src/app/api/cron/retention-nudges/route.ts, web/src/app/api/cron/process-journeys/route.ts |
| Cron schedule | web/supabase/migrations/0176_pg_cron_recurring_jobs.sql |
no_show journey trigger |
web/supabase/migrations/0222_journey_trigger_no_show.sql |
| Reminder confirmation columns | web/supabase/migrations/0238_ai_quality_and_reminder_confirm.sql |
| Retention page and panel | web/src/app/(tenant)/dashboard/retention/page.tsx, retention-engine-panel.tsx |
| No-show scorer, demand forecast | web/src/lib/forecasting/index.ts |
| Show-up chance action | web/src/lib/scheduling/actions.ts (getShowUpChanceAction) |
| Show-up chip | web/src/app/(tenant)/dashboard/calendar/show-up-chance.tsx |
| Forecasting page | web/src/app/(tenant)/dashboard/analytics/forecasting/ |