Skip to content

AI Upsell & Offers

How the Kagami AI suggests add-ons in WhatsApp chats, nudges clients before their visit, powers the checkout co-pilot, and sends flash promos for quiet weekday slots.

12 min read

Overview

Four revenue touchpoints share one recommendation engine and one per-brand rules row:

Kagami AI upsell recommendation engine displaying intelligent service additions and retail promotions

Touchpoint Channel value Trigger Client sees
In-chat booking upsell whatsapp_booking AI agent calls get_upsell_recommendations after a service is picked One add-on offered once, with price and extra minutes
Pre-arrival nudge whatsapp_nudge Cron ai-pre-arrival-nudge Teaser template or interactive "Add ..." button
Checkout co-pilot pos_checkout Front-desk POS billing screen Side card with 1-click add (staff-facing, not the client)
Flash promo for empty slots none (ai_yield_campaigns, not ai_upsell_events) Cron ai-whitespace-analyzer WhatsApp message to lapsed clients

Prices always come from the catalog, never from the model or the owner's free text. Intent is in prd-ai-revenue-agents.md; this page describes what the code does. The chat agent itself is covered in ai.md and ai-whatsapp-agent.md.

Source: web/src/lib/ai/upsell-engine.ts, upsell-rules.ts, upsell-events.ts, upsell-actions.ts, pre-arrival-nudge.ts, whitespace-analyzer.ts.

Recommendation engine

getUpsellRecommendations() (upsell-engine.ts) builds candidates, then rankUpsellRecommendations() filters and scores them.

Candidate sources (in order)

Source Item type Channels Base score
Owner "affinity pairs" (service_affinities, active rows for the booked services) service or product all the pair's co_occurrence_score (UI label "Strength", default 1.0)
Service add-ons linked to the booked service (service_add_on_links to service_add_ons, same brand, active) add_on whatsapp_booking only 3.0
Fallback: active, online_bookable services of at most FALLBACK_MAX_MINUTES (45) from categories in the same "family" as the booked service (wax/thread, nails, makeup, skin, hair, matched by category-name regex) service all 1.5 if 0 min, else 1.0
Fallback: first 4 active products product POS, or when still under the max 0.9

The fallback runs only when rules.useFallback is on and candidates are fewer than the channel maximum. Surcharge lines ("extra", "charge", "(per ...)") are never suggested. No related category means no fallback offer (SALO-2124).

An add_on is a row the owner created under Services > Add-ons (/dashboard/services/add-ons, see catalog.md). It is attached to a booking through add_on_ids; it cannot be added to a POS cart, so POS never sees add-ons.

Filters and scoring

Dropped before scoring: services already in the booking, items the client bought within repeatSuppressionDays, owner exclusions (service, category, product), includeProducts / includePackages off, outside minPriceMinor..maxPriceMinor, and (when buffer_minutes is passed) items longer than the buffer.

Score = base + bonuses. Defaults:

Weight (rules.weights) Default Applies to
zeroDurationBonus 1.5 service with 0 duration
expressBonus 0.75 duration 1..expressThresholdMinutes (15)
bookingExpressBonus 0.5 booking chat, duration at or under express threshold
nudgeServiceBonus 0.75 nudge: services and packages
posProductBonus / posPackageBonus 0.75 / 0.5 POS: products / packages
priceBandBonus 0.25 price above 0 and at or under priceBandCeilingMinor (150000 = Rs 1,500)

Each weight clamps to 0..5. Ties break on shorter duration, then name. Defaults reproduce the pre-SALO-2076 hard-coded behaviour, so a brand with no saved rules sees no change.

The package type exists in rules and filters, but no code path creates package candidates, so includePackages has no visible effect today.

Per-brand rules

Stored in ai_upsell_rules (migration 0216): one row per brand, is_enabled boolean plus a rules jsonb. normalizeRules() clamps every value and falls back to defaults, so a stale or partial row cannot break the engine. No row means defaults; "Reset" deletes the row.

Setting (rules.*) Default Limits
enabled (column is_enabled) true master switch
channels.<channel>.enabled true per channel
channels.whatsapp_booking.maxRecommendations 3 1..5
channels.whatsapp_nudge.maxRecommendations 1 1..5
channels.pos_checkout.maxRecommendations 3 1..5
repeatSuppressionDays 30 0..365 (0 = off)
expressThresholdMinutes 15 0..60
excludedServiceIds / excludedServiceCategoryIds / excludedProductIds empty max 500 each, UUIDs of this brand only
includeProducts / includePackages / useFallback true
nudge.windowFromHours / windowToHours 20 / 28 from 1..72; to at least from+2, max 96
nudge.quietHoursStart / quietHoursEnd null HH:MM IST, may cross midnight; both or neither
nudge.maxNudgesPerClient / frequencyDays null / 7 1..10 / 1..90
nudge.messageTemplate null (built-in copy) max 700 chars

The rules loader fails closed: if the row cannot be read, loadUpsellRules() returns rules with enabled: false and logs upsell.load_rules, so upsells switch off for that call rather than ignoring the owner's exclusions.

Custom nudge copy must use only {client} {service} {addon} {price} {stylist} {time} {salon}, must include {addon}, and may not contain a typed amount (Rs / INR figure). The line Reply "ADD" or tap the button below to include it in your visit! is always appended. Quiet hours are rejected on save if they would leave appointments starting 07:00-23:00 IST with no possible send time (validateQuietWindow).

Once-per-chat offer rule

The in-chat offer is limited by three layers (gateway.ts, history.ts, tools.ts):

  1. Prompt: "call get_upsell_recommendations and offer its first item once, with its price ... A no never delays the booking."
  2. Gateway: once any get_upsell_recommendations result with items exists in the conversation (upsellOffered()), later calls return UPSELL_ALREADY_OFFERED (empty list, "do not offer any add-on again"). The history summary also gets the line "add-on already offered: do not offer another".
  3. Database: unique index uq_ai_upsell_events_one_offer_per_conversation_item on (conversation_id, recommended_item_id) for whatsapp_booking. It is per item, not per chat; the one-offer-per-chat guarantee comes from layers 1-2.

The tool's note also tells the model to offer ONE item, never add it without a clear yes, and never re-offer after a decline (dark-pattern rule). Accepted items go into create_booking / propose_booking as add_on_ids (type add_on) or additional_service_ids (type service). For an existing appointment the agent calls add_services_to_appointment (workflows/appointments.ts, SALO-2516): it needs a stylist on the appointment, attaches services right after the current visit, and fails honestly if the stylist's next booking is too close.

ai_upsell_events

One row per offer. Migrations 0210, 0216, 0231.

Column Notes
org_id, brand_id, client_id, appointment_id tenant and links; client/appointment nullable
channel whatsapp_booking, whatsapp_nudge, pos_checkout
recommended_item_type CHECK allows service, product, package only (not add_on)
recommended_item_id UUID of the service/product
status offered, accepted, rejected, expired
revenue_impact_minor catalog price at acceptance; 0 until accepted
conversation_id booking-chat offers only (0216)
nudge_stage booking or pre_arrival (0231, default pre_arrival)

Unique indexes: one nudge row per (appointment_id, nudge_stage); one booking-chat row per (conversation_id, item). Org members can read; only service_role writes (the server writes with the admin client after tenant checks). recordUpsellEvent() treats Postgres error 23505 as duplicate, which is how crons and repeat tool calls stay idempotent.

Attribution

Channel Offered row written Moves to accepted when
whatsapp_booking get_upsell_recommendations logs only the lead item (recs[0]), and only if it is not an add_on markBookingOfferAccepted() finds an offered row for the same conversation + service; revenue = service catalog price; row gets appointment_id
whatsapp_nudge cron inserts the row as the send claim client taps the button or types ADD; markNudgeAccepted() flips it in place (one row per nudge)
pos_checkout none staff click add; recordCheckoutUpsellAcceptanceAction inserts an accepted row directly, price read server-side

Attribution is by conversation or appointment id, with no time window. rejected is allowed by the CHECK but nothing in the code writes it. expired is written when a newer pre-arrival send supersedes an open booking-stage nudge.

Reporting

getUpsellConversionStats(brandId, days = 30) (upsell-actions.ts, manager roles) counts every non-expired row as offered, accepted rows as converted, round(accepted / offered * 100) as the rate, and sums revenue_impact_minor of accepted rows, overall and per channel. The view ai_quality_weekly (migration 0238) adds weekly upsells_offered / upsells_accepted for whatsapp_booking; see ai-quality-and-eval.md.

Pre-arrival nudge

Cron GET|POST /api/cron/ai-pre-arrival-nudge (route.ts, logic in pre-arrival-nudge.ts). Auth is the x-cron-secret header compared with env CRON_SECRET. The route returns { considered, sent, skipped{reason: n}, failed }.

Two sends per appointment

Stage Who is a candidate Extra gates
booking appointments confirmed/scheduled, created in the last 12 h (BOOKING_LOOKBACK_HOURS), starting at least 1 h out, no booking-stage row yet brand rules only (no window)
pre_arrival confirmed/scheduled appointments starting inside the brand's send window (default 20-28 h out), paged 100 rows x 10 pages per window window; skipped if an offer was already accepted or the booking-stage offer went out in the last 12 h

Booking candidates are processed first, so a booking made about 24 h out gets only the booking send. When a pre-arrival send is delivered, any open booking-stage row for that appointment is set to expired, so one ADD converts one row.

Per-appointment checks, in order

Brand rules (upsell_disabled when the master switch or the nudge channel is off, quiet_hours, frequency_cap), client phone present, brand ready, services on the appointment, a recommendation exists (no_recommendation_matched), claim insert (already_nudged on duplicate).

  • "Brand ready" means ai_agent_settings.is_enabled = true and a messaging_settings row with WhatsApp credentials and is_whatsapp_enabled not false (skip reason brand_ai_disabled).
  • Only brands with an APPROVED row for template pre_arrival_addon in whatsapp_templates are scanned at all. If none exist the run returns skipped.template_not_approved.
  • The per-client cap counts whatsapp_nudge rows (both stages) in the last frequencyDays, per brand.
  • The engine is asked for exactly 1 recommendation on channel whatsapp_nudge.

Sending

  1. The cron claims the slot by inserting the offered event; a concurrent run gets 23505 and skips.
  2. If the client messaged the brand in the last 23 h (inbound_messages, last 10 digits), it sends the interactive button message (copy with price and duration, or the brand's custom template). If that call throws, it falls back to the template.
  3. Otherwise it sends template pre_arrival_addon (MARKETING category, vars: client, service, "tomorrow at 4:30 pm", salon). This is a teaser with no price; the client replies MORE INFO.
  4. A failed send deletes the claim row (releaseNudgeClaim) so the next run retries.

Client replies (WhatsApp webhook)

Reply Handler Result
Tap button add_upsell:<appointmentId>:<serviceId> replyToUpsellTap -> applyUpsellToAppointment Adds the service
Text ADD (exact, case-insensitive) same, for the sender's newest open offer with a future appointment Adds the service
Text MORE INFO AI agent receives a context block with the offer Agent explains in 2-3 lines and says to reply ADD; it must not create a new booking

applyUpsellToAppointment checks the sender's phone suffix against the appointment's client, status booked/scheduled/confirmed and start in the future, service active in the appointment's brand, then wins the atomic offered -> accepted flip. For a timed add-on it checks the stylist is free for the extra minutes, inserts an appointment_services line, and extends appointments.ends_at. On any failure it reverts the event to offered. A repeat tap answers "already added".

Whitespace analyzer and flash promos

Cron GET|POST /api/cron/ai-whitespace-analyzer (same x-cron-secret auth). It is separate from the upsell rules: there is no owner setting, dashboard page or toggle for it, and nothing in the dashboard reads ai_yield_campaigns.

Flow (whitespace-analyzer.ts):

  1. Target dates: today+1 and today+2 (UTC date), weekdays Mon-Fri only.
  2. For every active locations row whose brand does not have ai_agent_settings.is_enabled = false (a brand with no settings row is not skipped), it measures window 12:00-16:00.
  3. calculateOccupancy: capacity = staff count x window minutes (staff count = staff_locations rows for the location, minimum 1); booked = overlap minutes of confirmed/scheduled appointments; whitespace when occupancy is below DEFAULT_OCCUPANCY_THRESHOLD_PCT (50). Open slots = available minutes / 45.
  4. If whitespace and no active campaign exists for the same location, date, start time and trigger_reason = 'whitespace_detected', it inserts an ai_yield_campaigns row (status active, occupancy_pct, slots_opened, promo_code = FLASH + MMDD).
  5. dispatchFlashCampaign messages up to DEFAULT_MAX_FLASH_RECIPIENTS (20) clients. Candidates are active clients with a phone, not opted out of WhatsApp marketing/transactional consent (a consent read error opts everyone out), with no non-cancelled, non-no-show appointment since DEFAULT_MIN_LAPSED_DAYS (45) days ago.
  6. Message: "Flash Perk from <brand>" with the open-slot count, the time window, a perk line (default "a complimentary Hair Spa or Scalp Treatment (worth Rs 1,200)") and the code. It goes as an interactive button message, falling back to plain text.
  7. Tap claim_flash:<campaignId>:<code> makes the webhook touch the campaign's updated_at and reply that the code is reserved and ask what to book.

The same ai_yield_campaigns table also holds cancellation_fill campaigns from cancellation-matcher.ts (waitlist backfill). That flow is not covered here.

Scheduling

Both crons are pg_cron jobs that call public.run_cron_endpoint(path), which POSTs the app route with the x-cron-secret header using the cron_secret and cron_base_url Vault secrets (migration 0176_pg_cron_recurring_jobs.sql). No Vercel cron config is involved (Vercel is retired).

Job name Schedule Migration
salonos-ai-pre-arrival-nudge */15 * * * * (every 15 min) 0231_ai_pre_arrival_nudge_cron.sql
salonos-ai-whitespace-analyzer 0 5 * * 1-5 (05:00 UTC = 10:30 IST, Mon-Fri) 0287_retention_crons.sql

Both migrations skip silently when pg_cron is unavailable (local clones). To confirm the jobs are registered on a database, check cron.job.

Owner settings

What Where Who
Rules, exclusions, nudge window/quiet hours/copy, affinity pairs Dashboard > Settings > AI upsell rules (/dashboard/settings/ai-upsell); per-brand picker at the top Owners edit (saveUpsellRulesAction, resetUpsellRulesAction, upsertServiceAffinity); managers see it read-only; nav item needs the ai_agent feature
Performance card (last 30 days: offered, accepted, rate, revenue, per channel) same page managers and owners
Add-on catalog and links to services Dashboard > Services > Add-ons admin roles (see catalog.md)
AI agent on/off, WhatsApp credentials AI agent settings and messaging settings (ai_agent_settings.is_enabled, messaging_settings.is_whatsapp_enabled) see settings.md
pre_arrival_addon template approval WhatsApp templates (whatsapp_templates.status) see communications.md

Server actions re-verify that brandId belongs to the caller's org, re-clamp all input, and drop excluded ids that belong to another brand. Role rules are in roles-permissions.md. The POS co-pilot is covered in checkout.md.

Troubleshooting / where to look

Symptom Check
No nudges going out whatsapp_templates has pre_arrival_addon with status APPROVED for the brand; ai_agent_settings.is_enabled; cron JSON skipped counts; cron.job row exists and Vault secrets are set
Client says nudge never arrived ai_upsell_events row for the appointment (channel = 'whatsapp_nudge'); a deleted claim means the send failed; quiet hours and the window are re-evaluated every 15 min
"Upsells switched off" for one brand ai_upsell_rules.is_enabled, channel switch, or a rules read error (Sentry tag upsell.load_rules)
AI never offers an add-on no affinity, add-on link or complementary-family fallback; a decline or earlier offer in the same chat; client bought it within repeatSuppressionDays (nudge/POS only)
Conversion looks wrong POS rows exist only as accepted; add-on leads are not logged, so POS conversion reads 100%
Flash promo not sent AI explicitly disabled for the brand; occupancy at or above 50%; campaign already active for that window; no lapsed clients; no WhatsApp credentials