Referral Program
Refer-a-friend program with shareable links, a referral tree, flat-rupee service vouchers, qualification rules, caps, expiry, and the public /r/[code] landing page.
16 min read
Overview
The referral program lets an existing client bring in a friend and rewards both sides. Each brand has at most one program (configured at /dashboard/referrals). Every client gets a personal link (/r/<code>). A friend who leaves their details through that link becomes a referral event; the event moves through a status lifecycle and, when it qualifies, rewards are issued to the referrer and (optionally) the friend.

Rewards can be loyalty points, store credit, a one-use percent code, or a flat-rupee voucher (discount_flat). Flat vouchers are personal to one client, can be restricted to services only, can be pinned to one location, and expire with the referral.
Referrals form a tree: if the referrer was themselves brought in by a live referral, the new event is stored as its child. The tree is for visibility only. Rewards go to the direct referrer and the friend, never further up the chain.
The program is gated by the loyalty feature (premium tier, "Loyalty & Retention"). Retention instruments around it (points, wallet, memberships) are described in Retention Programs.
How it works
1. Program setup
An owner saves a program in Program Settings. Until a program exists and Program active is on, nothing is captured:
- The
/r/<code>page shows "This link isn't active". - Staff cannot record referrals (the "Record Referral" button is disabled; the server rejects with "Referral program is not active").
- The portal "Refer" tab says rewards are not running.
If a client's link is requested before any program exists (staff Links tab or the client portal), an inactive default program is created automatically: referrer gets 100 loyalty points, friend gets nothing, trigger first_visit. Nothing pays out until an owner switches it on.
2. A referral is created
Two entry points feed the same write path (insertReferralEvent):
| Source | source value |
How |
|---|---|---|
| Public link | public_link |
Friend submits the form on /r/<code> |
| Staff | staff |
"Record Referral" on the dashboard (referrer picked from clients; friend is an existing client or just a name and phone) |
Rules applied on every creation:
- Phone normalisation: any input with 10+ digits becomes
+91plus the last 10 digits. Fewer than 10 digits is rejected ("Enter a valid 10-digit mobile number."). Referral phones are India-format only. - Self-referral is rejected ("You can't refer yourself."). The public path also compares phone suffixes with the referrer's phone.
- Per-client cap (
max_referrals_per_client, blank = unlimited): counts the referrer's events in this program whose status is notcancelledorexpired. Over the cap: "This client has reached the maximum number of referrals." Note thatclosedandreward_failedevents still count. - One live referral per friend phone per brand: a unique index on
(brand_id, referee_phone)applies while the status is notcancelled,expiredorclosed. A duplicate returns "This friend has already been referred." - Expiry stamp:
expires_at = now + expiry_daysdays (null whenexpiry_daysis blank). - Tree position is resolved (see the Referral tree section).
- Initial status:
qualifiedwhen the trigger issignup, otherwisepending. - If the friend's reward is
discount_flat, the friend's voucher is issued immediately (so it can be spent on their very first bill). If voucher creation fails, the event is deleted and the error is returned. - If the trigger is
signupand Auto-issue rewards is on, rewards are issued right away.
Public-link extras (submitReferralCapture):
| Check | Behaviour |
|---|---|
Honeypot field website filled |
Fake success, nothing written |
| Name | 2 to 80 characters, else "Please enter your name." |
| Consent checkbox | Required ("Please tick the box so the salon can contact you.") |
| Rate limit | 10 submissions per hour per IP, 30 per hour per code |
| Existing client with a paid invoice | Rejected ("Looks like you're already one of our clients..."). Phone is matched across the org by last 10 digits |
| Existing client with no paid invoice | Re-used as the friend |
| Unknown phone | A new clients row is created (brand, name, phone) |
| After success | referral_codes.uses is incremented and the referrer gets a "friend signed up" notification |
The staff path does not apply the "already a paying client" check.
3. Qualification (the friend's first bill)
After every non-complimentary paid invoice, qualifyReferralForInvoice runs (fire-and-forget from checkout). It looks for the newest pending event whose friend is the paying client; if none, it looks for a pending event with no linked client whose referee_phone matches the client's phone (last 10 digits) and links the client to it.
It then applies, in order:
- Program must be active; the paying client must not be the referrer; the event must not be past
expires_at. Otherwise it silently does nothing (an expired pending event is cleaned up by the nightly job). - For triggers
first_visitandfirst_paid_visit, the client must have exactly one paid invoice (this one). Otherwise nothing happens. The two triggers behave identically in code. - The basis amount is the invoice total, or, when the program is Services only, the pre-discount subtotal of the service lines only (unit price times quantity, before line or invoice discounts).
- If basis is below
min_visit_value_minor:- Services-only program ("strict first bill"): the event becomes
closed(withtrigger_invoice_id) and all unspent vouchers for the event are voided. Nobody earns a reward. - Non-strict program: nothing happens and the referral keeps waiting for a big enough first visit (it can then never qualify if the "exactly one paid invoice" rule has already failed).
- Services-only program ("strict first bill"): the event becomes
- At or above the minimum: the event is atomically claimed
pendingtoqualified, the friend's own voucher is voided (their first bill is done), and if Auto-issue rewards is on, rewards are issued.
Manual alternatives on the dashboard: Qualify (pending to qualified, then pays out if auto-issue is on; skips the minimum-spend check) and Issue Reward (qualified to rewarded, after a confirmation dialog). Choosing "rewarded" from pending first moves the event to qualified.
4. Reward issue
issueReward claims the event atomically (qualified to rewarded) so a payment hook and a manual click cannot double-pay. Then each side is issued:
| Reward type | Referrer | Friend | What is created |
|---|---|---|---|
store_credit |
yes | yes | Wallet credit of value rupees (ledger row, reference = event id) |
loyalty_points |
yes | no | value points ("Referral reward") |
discount_pct |
yes | yes | A generic one-use percent code (max_uses 1, not client-bound), expiry = issue date + expiry_days |
discount_flat |
yes | yes | A personal flat-rupee voucher (below) |
none |
no | yes | Nothing |
The friend is only rewarded if the event has a linked client. A friend with a flat voucher is not re-issued at this step (it was created at referral time).
If any side fails, the event ends in reward_failed (the successful side's reference is still saved), the error is logged, and the dashboard shows "A reward didn't go through. Check the client's balance and credit anything missing by hand." There is no automatic retry and no UI path out of reward_failed.
When rewards succeed, the "reward ready" notification is sent to whichever sides received one.
5. Flat-rupee vouchers
A discount_flat reward is a row in discount_codes linked to the event (referral_event_id, referral_role of referrer or referee). One voucher per side per event is enforced by a unique index, so reissue calls are idempotent.
| Property | Value |
|---|---|
| Code | REF + first 4 letters of the brand slug (uppercased) + 6 random digits |
| Amount | Program reward value in rupees, stored in paise (value times 100) |
| Uses | max_uses 1 |
| Minimum spend | Program min_visit_value_minor (paise) |
| Services only | Copied from the program flag |
| Expiry | The event's expires_at (referral date + expiry_days), not the date the reward was earned. Never expires if expiry_days is blank |
| Location | Pinned to the referrer's registration_location_id when Allow redeeming at any location is off; otherwise unrestricted |
| Owner | The referrer, or the friend (client-bound, or matched by phone if the friend had no client record yet) |
Redemption rules at checkout (validateCode):
- The voucher is personal: the bill's client must be the owner ("This voucher belongs to a different client"). A client must be selected first.
- The referrer's voucher only works once the event is
rewarded. The friend's voucher works while the event ispending,qualifiedorrewarded. Any other status gives "This referral reward is no longer available". - If the voucher is pinned to a location, the bill's location must match ("This voucher can only be used at the location it was earned at").
- Services-only vouchers are measured on the pre-discount service subtotal; with no service on the bill they fail ("This voucher applies to services only"). The minimum-spend check uses the same basis ("Minimum services ₹N required").
- Discount = the smaller of the voucher value and the basis.
- One per bill: a referral voucher cannot be combined with a manual discount or a spin-wheel prize ("A referral reward can't be combined with another discount on the same bill").
On use, the usage is recorded and the owner is sent a "reward applied" message. Unspent vouchers are shown as one-tap chips in the checkout promo section.
Referral tree
Each event stores parent_event_id, depth and path:
- Parent: the newest live (not
cancelled,expiredorclosed) event in the same brand whose friend is the referrer. The walk goes up at most 50 hops. - Depth: parent depth plus 1 (a top-level referral is depth 1).
- Path: event ids from the root down to this event, joined by
/. - Cycle guard: if the friend already sits above the referrer in the chain, creation is rejected ("That client already sits above the referrer in the referral tree.").
The Referral Tree tab groups events by referrer client: roots are referrers who were not themselves referred through a live referral, with the expandable downline below (first two levels open, 30 levels maximum). It shows name, phone, status badge, level and date, plus "N referred in total, M rewarded" per root. The UI builds the tree from client ids; it displays depth but does not read path or parent_event_id.
Statuses
| Status | Meaning | Who sets it |
|---|---|---|
pending |
Friend captured, waiting for their qualifying first bill | Creation |
qualified |
Trigger met; reward owed (waits here if auto-issue is off) | Invoice hook, "Qualify", or creation for signup trigger |
rewarded |
Rewards issued | issueReward |
reward_failed |
A reward write failed after the claim; fix by hand | issueReward |
closed |
Services-only program: first bill was below the minimum. No reward | Invoice hook |
expired |
Pending past expires_at |
Nightly job or manual |
cancelled |
Cancelled by staff | Dashboard "Cancel" |
Manual status changes are only accepted from pending or qualified; a rewarded, reward_failed, closed, expired or cancelled event cannot be moved by hand. Cancelling, expiring or closing by hand voids the event's unspent vouchers. A qualified event never expires (the reward is owed).
Where owners configure it
Dashboard: Referrals (/dashboard/referrals, nav entry under the loyalty group, requires the loyalty feature).
KPI strip: Total, Pending, Qualified, Rewarded. Tabs:
| Tab | Purpose |
|---|---|
| Referrals | List with status filter chips (all, pending, qualified, rewarded), "Log follow-up", Qualify, Issue Reward, Cancel, and "Record Referral" (manual) |
| Referral Tree | Downline view per top-level referrer |
| Referral Links | Pick a client, get their code, share URL, QR code (320px), copy button, and a "friends referred" count |
| Program Settings | All program fields (below) |
Program Settings fields
| Field | Default in form | Notes |
|---|---|---|
| Program name | "Refer a Friend" | Required |
| Referrer reward type and value | store credit, 0 | store credit (₹), discount (%), loyalty points, flat discount voucher (₹) |
| Referee reward type and value | discount %, 0 | discount (%), store credit (₹), flat discount voucher (₹), no reward |
| Reward trigger | first visit | signup, first_visit, first_paid_visit |
| Min visit value | 0 | Entered in paise (₹1 = 100). 0 = any amount |
| Reward expiry (days) | blank = never | Sets expires_at on each referral and on its vouchers |
| Max referrals per client | blank = unlimited | See cap rules above |
| Terms and conditions | blank | Stored on the program; no client-facing screen renders it yet |
| Services only, first bill decides | off | Strict mode: qualifies on the pre-discount service subtotal, closes the referral below the minimum, restricts vouchers to services |
| Allow redeeming at any location | on | Off pins vouchers to the referrer's home location |
| Program active | on | Master switch |
| Auto-issue rewards | on | Off leaves qualified referrals waiting for "Issue Reward" |
A "Use ₹750 services voucher preset" button fills: flat ₹750 for both sides, ₹1,500 minimum (150000 paise), first_paid_visit, 60-day expiry, unlimited referrals, services only.
Onboarding can seed a program: active, auto-issue on, flat voucher for both sides at one chosen amount, minimum spend and validity days from the wizard, first_paid_visit, services only, any location.
Follow-up calls: staff can log a call outcome on a pending or qualified referral (Reached and booked, Reached and call later, No answer, Not interested) with notes; this stores callback_done_at, callback_by (the caller's staff record), callback_outcome, callback_notes.
Messaging: Settings, Messaging has a Referral notifications toggle (send_referral_notifications, default on).
What clients see
Friend: /r/<code> (public, no login, always rendered fresh)
- Header with the brand logo (from the brand theme), "
<Referrer first name>thinks you'll love it here", and the headline "Get<reward>at<brand>" when the friend has a reward, otherwise "Meet<brand>". Reward text examples: "₹750 off services on a ₹1500+ bill", "10% off", "100 loyalty points". - Form: name, mobile number, consent checkbox ("I agree to be contacted by
<brand>about my first visit."), and a hidden honeypot. Button: "Claim my invite". - On success: "You're on the list" with a "Book an appointment" link to
/book/<brand slug>. The salon follows up by phone. - Unknown or inactive link: "This link isn't active" with a hint to contact the salon.
- Codes are matched case-insensitively and must be 4 to 16 letters or digits.
Referrer: portal "Refer" tab (client portal, after OTP sign-in). Shows the code, share URL, copy button, and "When your friend visits for the first time, you earn <your reward> and they get <friend reward>". The code is created the first time the tab is requested. If the program is inactive it says rewards aren't running right now.
Referrer and friend: notifications (WhatsApp templates, email fallback):
| Event | Template | Sent to |
|---|---|---|
| Friend signed up via link | referral_captured |
Referrer |
| Reward issued | referral_reward_ready |
Each rewarded side (includes the voucher code for code-type rewards) |
| Voucher applied on a bill | referral_reward_used |
Voucher owner |
| Voucher expires within 7 days | referral_reward_expiring |
Voucher owner (once) |
| Voucher lapsed unused | referral_reward_expired |
Voucher owner (once) |
Delivery rules: skipped when the brand's referral notifications toggle is off, or the client's promotional preference is false. WhatsApp is used when it is enabled and the template sends; if it fails (most often a template not yet approved by Meta) it falls back to email, provided the client has an email and email_reminders is not false. Each message has an idempotency key so retries do not double-send. Notification code never throws into the checkout path.
At checkout (front desk): the client's unspent, unexpired referral vouchers appear as chips ("Referral reward, ₹N off services").
Cron and background jobs
| Job | Schedule | Auth | What it does |
|---|---|---|---|
salonos-referral-maintenance (pg_cron, migration 0176) calling POST /api/cron/referral-maintenance |
Daily 04:30 UTC (10:00 IST) | pg_cron's run_cron_endpoint sends the x-cron-secret header from Vault; the route checks it against CRON_SECRET and fails closed (401) if unset or wrong |
See below |
| Invoice hook (not a cron) | On every paid, non-complimentary invoice | In-process | qualifyReferralForInvoice |
runReferralMaintenance does, in order:
- Sets
pendingreferrals pastexpires_attoexpired. - Follow-up nudge: per brand, if any
pendingreferral on an active program is older than 48 hours with no logged call, sends thereferral_followupalert ("N referrals waiting for a follow-up call", severity warning, link to the dashboard). At most one per brand per roughly 20 hours. - Failed rewards: per brand, if any event is
reward_failed, sends thereferral_reward_failedalert (severity critical; can also go out on all four channels). Same de-duplication window. - Voucher lifecycle: unused active referral vouchers past their
expires_atget a "reward expired" notice and are switched off (is_activefalse); unused active vouchers expiring within 7 days get a one-time "expiring" notice.
The route returns counts: expired, followUpBrands, failedBrands, warned, lapsed. A thrown error is captured and the route returns 500 "Referral maintenance failed".
Data model
| Table | Key columns |
|---|---|
referral_programs |
brand_id, name, is_active, referrer_reward_type/value, referee_reward_type/value, min_visit_value_minor, reward_trigger, expiry_days, max_referrals_per_client, terms_text, auto_issue_reward, services_only, allow_cross_location |
referral_events |
program_id, referrer_client_id, referee_client_id, referee_name, referee_phone, status, source, referral_code_id, expires_at, parent_event_id, depth, path, trigger_invoice_id, referrer/referee_reward_ref_type/ref_id/issued_at, callback_*, notes |
referral_codes |
brand_id, client_id, program_id, code (globally unique case-insensitively), uses |
discount_codes (referral columns) |
client_id, services_only, referral_event_id, referral_role, location_id; unique on (referral_event_id, referral_role) |
messaging_settings |
send_referral_notifications |
Code format: up to 4 letters or digits from the brand slug, then 5 characters from an alphabet without 0, O, 1, I (so codes survive being read aloud). Up to 5 attempts on a collision.
Migrations: 0030 (original program/events), 0130 (original codes), 0172 (v2 schema: program_id, capture source, callback tracking, reward audit refs, live-phone unique index), 0173 (dropped the legacy referral_redemptions table), 0174 (global code uniqueness), 0175 (notification toggle), 0176 (daily cron), 0266_referral_tree_and_service_vouchers (tree columns, closed status, flat reward type, services_only, allow_cross_location, voucher columns).
Reward reference types stored on the event: loyalty_transaction, store_credit_ledger, discount_code.
Permissions and roles
- The Referrals nav item is shown to
super_admin,org_owner,brand_managerandlocation_manager(the shared admin set), and only when theloyaltyfeature is on. Front desk and stylists do not see it. - Checkout voucher chips and validation are available to anyone with access to the brand at the POS.
- Program settings, status changes, link generation and follow-up logging are intended for owners and managers, the only roles shown the page in navigation.
- The public page and capture action are unauthenticated by design and protected by the honeypot, consent, and rate limits above.
Edge cases and failure behaviour
- Friend already a paying client (public link): rejected with a clear message. On the staff path, a friend who already has paid invoices will never match the "exactly one paid invoice" rule and stays
pendinguntil it expires. - Friend reward other than a flat voucher (store credit, percent): issued only at reward time, after the qualifying bill, so it cannot discount that first bill even though the landing page advertises it.
- Referrer voucher expiry runs from the referral date, not the reward date, so a late-qualifying referral can hand over a voucher with little time left.
- Expired referral: if the friend pays after
expires_at, qualification is skipped silently; the nightly job then marks itexpiredand lapses its vouchers. - Duplicate friend phone: blocked while the earlier referral is live; allowed again once it is
cancelled,expiredorclosed. - Voucher creation failure at referral time: the referral row is deleted and the error shown, so a friend is never left without the promised voucher.
- Race between payment hook and manual click: only one wins the atomic status claim; the other is a no-op, not an error.
- Reward write failure:
reward_failedplus a critical daily alert; resolve by crediting by hand (no retry control). - Rejected referral on the public link: the friend's client record is created before the referral is saved, so a rejected referral (for example a duplicate) can still leave a new client record behind. The link's "friends referred" count is approximate.
- Notification failures are captured server-side and never block checkout or capture.
- Large programs: the referral list and KPI counts are not paginated, so very large programs may show partial lists.
Source
web/src/lib/referrals/index.ts(types, program and event queries, status transitions)web/src/lib/referrals/events.ts(creation, tree position, caps, expiry stamp)web/src/lib/referrals/qualify.ts(invoice-time qualification andclosed)web/src/lib/referrals/rewards.ts(reward issue, flat vouchers,reward_failed)web/src/lib/referrals/codes.ts,phone.ts,reward-text.ts(links, QR, phone normalisation, reward wording)web/src/lib/referrals/public-actions.ts(public landing data and capture)web/src/lib/referrals/admin-actions.ts(dashboard server actions)web/src/lib/referrals/maintenance.tsandweb/src/app/api/cron/referral-maintenance/route.ts(nightly job)web/src/lib/referrals/notify.tsandweb/src/lib/messaging/templates.ts(notifications and templates)web/src/lib/discount-codes/index.tsandcheckout-actions.ts(voucher validation, listing, voiding)web/src/lib/billing/actions.ts(checkout hooks: voucher validation, redemption, qualification)web/src/app/(tenant)/dashboard/referrals/(page, panel, tree)web/src/app/(client)/r/[code]/(public landing and form)web/src/lib/portal/otp-actions.ts(getReferralCodefor the portal)web/src/lib/onboarding/actions.ts(onboarding program seed)web/supabase/migrations/0030,0172-0176,0266_referral_tree_and_service_vouchers.sql