Skip to content

Loyalty Gamification

Raffles, the spin wheel, the digital loyalty card (Apple/Google Wallet and PWA), points expiry, and reward tiers.

15 min read

Overview

These features sit on top of the loyalty points ledger (loyalty_transactions) and turn repeat visits into something clients can see and win.

Kagami gamified salon loyalty rewards, tier milestones, and interactive client incentives

Feature What it does Owner screen
Raffles One entry per qualifying paid bill; a seeded, auditable draw picks winners; prizes are issued automatically Dashboard, Loyalty, Raffles
Spin wheel Clients spin for a prize at points milestones, or burn points for an extra spin Settings, Spin wheel
Loyalty card Digital card from a QR code; Apple/Google Wallet pass; installable web page with a near-store check Settings, Loyalty card
Points expiry Daily job warns, then zeroes, balances that have been inactive too long Retention, Loyalty Points
Reward tiers Named levels derived from a client's points balance Settings, Reward tiers

All five are behind the loyalty plan feature. Without it the pages show an upgrade prompt.

Raffles

How a raffle works

  1. A manager creates a raffle as a draft and activates it. Only drafts can be edited; to change an active raffle, cancel it and create a new one.
  2. When a bill is paid, checkout calls the entry hook (fire-and-forget, never blocks or fails the bill). Every active raffle of that brand whose window and scope match gets one entry per invoice.
  3. An invoice qualifies when all of these hold:
    • raffle status is active and the brand matches
    • the raffle is brand-wide, or its location equals the invoice's location
    • the bill total is above zero and at least the raffle's minimum bill
    • the payment time is inside starts_at to ends_at (inclusive)
  4. Checkout skips the hook entirely for: bills with no client, complimentary bills, bills paid (fully or partly) with loyalty points, and membership sales.
  5. Each entry gets a code like RF-XXXXXX (6 characters from an alphabet without 0, O, 1, I, L). The entry is idempotent per raffle and invoice, so a retry never creates a second entry. The client gets the entry code on WhatsApp (raffle_entry_code_v2).
  6. The draw runs either when the owner presses Draw, or automatically after the end date if auto_draw is on (see Cron).
  7. After the draw, each winner gets their prize issued and a WhatsApp announcement (raffle_winner) with a link to the public results page.

Draw rules

  • Entries on voided invoices are ignored at draw time.
  • Weight is calculated per customer, not per entry. Winners are picked without replacement, so one customer can win at most once per raffle. If fewer customers entered than winner_count, fewer winners are drawn.
  • If nobody has entered, the draw returns "No eligible customers have entered this raffle yet" and nothing changes.
  • A manual draw is allowed before the end date. The owner screen warns that later bills will not get entries after the raffle is drawn.
Draw mode Weight per customer
random 1 for everyone
loyalty (entries ? entry count : 1) + (visit streak ? streak - 1 : 0) + (spend ? total spend / unit : 0), then multiplied by the tier multiplier when the tier option is on
  • Visit streak: consecutive calendar months (IST) with at least one entry, counted back from the latest entry month.
  • Spend unit: the larger of the raffle's minimum bill and ₹100.
  • Tier multiplier: taken from the client's current points balance against the brand's active reward tiers (the highest tier whose min_points is at or below the balance). No tier means 1. A multiplier below 0.01 is treated as 0.01.
  • Weights are rounded to 4 decimals and are always above zero.
  • Exclude recent winners (any mode): drops clients who won any raffle of the brand in the last exclude_recent_days days (default 90).

Auditability

The randomness comes from sha256(seed:counter). The seed is 16 random bytes (hex) generated with crypto at draw time. The seed and the final weights are stored on the raffle (draw_seed, draw_weights), so a result can be reproduced. The winners and the active to drawn flip are committed in one database function (commit_raffle_draw), so a raffle cannot be drawn twice or end up drawn without winners. The function is callable only by the service role.

Prizes

Prize type What is issued
voucher A single-use discount code RAFFLE-XXXXXX (percent up to 100, or a fixed amount), optional validity in days. Up to 3 attempts to find a free code.
membership The winner is enrolled in the chosen membership plan. The plan must belong to the brand and be active, checked at save and again at activation.

Fulfilment is safe to repeat. A winner row is claimed with a 10 minute lease and each claim counts as an attempt. After 3 failed attempts (MAX_PRIZE_ATTEMPTS) the winner is left for the owner to issue manually, and the owner screen shows the prize as failed. If the prize was created but could not be recorded, attempts are exhausted on purpose so a later sweep cannot issue a second prize.

Where owners configure it

Dashboard, Loyalty, Raffles (/dashboard/loyalty/raffles). Fields and defaults for a new raffle:

Field Default or limit
Window Starts now, ends in 30 days; end must be after start
Minimum bill ₹1,000 (stored in minor units, max 100,000,000 minor)
Scope One location, or brand-wide (brand-wide needs owner or brand manager)
Prize Voucher (percent, default 20, validity default 60 days) or membership plan; prize label required, max 200 characters
Winners 1 to 100, default 1
Draw mode random by default. loyalty needs at least one weighting ticked (default ticked: entries)
Exclude recent winners Off by default; 1 to 3650 days, default 90
Auto draw Off by default
Name, description Name required (max 120), description max 500

The detail view shows the latest 200 entries and every winner with their phone, prize detail, whether the WhatsApp was sent, and whether the prize failed. The list shows up to 100 raffles, newest first.

What clients see

  • WhatsApp entry code after each qualifying bill, and a winner message. Messages are skipped, with no error to the client, when the client has no phone, WhatsApp is not enabled for the brand, or the client opted out of WhatsApp marketing.
  • Booking portal (/book/<brand>/portal): a Raffles card listing live raffles that end in the future, the client's own entry codes, and a Details link. Without codes it says "Pay a qualifying bill to get your entry code."
  • Public results page (/raffle/<raffle id>): raffle name, brand, prize, and either Entries close on {date} (active) or the winners list with first name and rank only. No phone numbers or other data. Draft and cancelled raffles return 404. Winners are shown only once the raffle is drawn.

Cron and background work

Job Schedule Endpoint Auth
salonos-raffle-draw Hourly at minute 15 (pg_cron, migration 0264) POST /api/cron/raffle-draw x-cron-secret header checked against CRON_SECRET

Each run does two things: draws every active raffle with auto_draw whose ends_at has passed, then retries unfinished prizes and WhatsApp messages for winners created in the last 7 days. The schedule needs pg_cron, so auto draw only runs on databases that have it.

Spin wheel

How it works

  1. A manager turns the wheel on (is_enabled, off by default) and defines prizes.
  2. A client gets spins in two ways:
    • Milestone spin (free): one spin for every milestone_points of lifetime points earned (default 500). Available spins = milestones reached minus milestone spins already used. Only earn transactions count, and bonus points won from a spin are excluded, so spin winnings cannot create more spins. Burning or expiring points never un-reaches a milestone.
    • Burn spin: costs spin_cost_points (default 200) from the current balance, any time the balance covers it.
  3. The client spins in the portal. The server re-checks eligibility, picks the prize with a weighted random choice over active prizes (probability = weight / total weight), and commits the spin, the point deduction and any bonus points in one database function (spin_wheel_execute_spin) that locks the client row. The browser only animates toward a prize the server already chose.
  4. Errors the client can see: "Spin wheel is not available.", "insufficient_points" (shown as "Not enough points for a burn spin."), "no_milestone_spin_available" (shown as "No free spin available right now."), "No prizes configured.". Spin requests are rate limited per brand and phone.

Prize types

Type Effect
discount_pct Percent off the bill subtotal. Claimed at checkout.
free_addon Marks the prize used; staff add the free line item to the bill themselves (no money effect in code).
bonus_points Points are credited immediately in the same transaction (ledger note "Spin wheel prize").
try_again Nothing to claim.
none Nothing to claim.

Prize fields: label, type, value (percent or points), integer weight above 0, colour, optional image (PNG/JPG/WebP/GIF under 2 MB, SVG rejected), sort order, active flag. The settings page shows each prize's odds as weight over total active weight.

Redeeming at checkout

Unredeemed discount_pct and free_addon prizes appear on the POS bill as "Spin Wheel Prize" with "Apply to bill" (service sales only). On submit, the prize must belong to that client and be unredeemed; it is then consumed atomically (redeemed_at IS NULL guard) and linked to the invoice. If the bill fails or is cancelled the prize is released again. A referral reward cannot be combined with a spin prize on the same bill. The total discount is capped at the subtotal. Staff can also toggle a spin as redeemed or not from the spin history on the settings page.

Where owners configure it

Settings, Spin wheel (/dashboard/settings/spin-wheel): milestone points, burn cost, prize list, and the 50 most recent spins. Nav access is for manager roles.

What clients see

In the booking portal: a wheel card with a "Free Spin (n)" button and a burn-spin button, the prizes on the wheel, a list of won prizes with claimed status, and a rewards showcase of prize images they have won (try again and none are excluded).

Loyalty card

How it works

  1. An owner enables the card and picks a colour theme, optional brand logo, alert text, and stores for the alert.
  2. Clients open /card/<brand slug> (usually from a QR code). They sign in with the same phone OTP as the booking portal; the card has no separate login. The client is always taken from the signed portal session, never from the URL, so one client cannot load another's card.
  3. The page shows the member name, points, tier, progress to the next tier, and a member QR code. The QR value is SLN1.<client id>.<HMAC> signed with PORTAL_SECRET, so a bare or guessed client id is never valid. The app does not include a scanner for this QR code.
  4. The card can be added to Apple Wallet (/api/loyalty-card/<slug>/apple, a signed .pkpass) or Google Wallet (/api/loyalty-card/<slug>/google, which syncs the class and object through the Wallet API and redirects to a save link). A button shows only when that provider's credentials are configured on the server; otherwise the route returns 404 and the button is hidden.
  5. As a fallback the page itself is an installable web app (per-brand manifest at /card/<slug>/manifest.webmanifest, standalone display).

Pass behaviour and limits

  • Pass points are a snapshot. The pass is not updated when points change; its label reads "POINTS (as of DD Mon)". Re-adding the pass refreshes it (Google also re-syncs the class and object on each add).
  • Up to 10 stores are embedded in a pass (Apple and Google both only surface that many). Only stores with coordinates are used. The lock-screen text is the alert text with {store} replaced by the store name. Default text: "You're near {store}, show your card for loyalty points".
  • The Apple pass uses a solid-colour icon in the card background colour; remote logos are not fetched when the pass is built.
  • A new Google class is inserted as UNDER_REVIEW. Until the owner gets it approved in the Google Wallet console, only the issuer's test users can save the pass. Later updates do not resend the review status.
  • Near-store alert on the web page: foreground only. If the client taps "Check if I'm near a store" and allows location, the page watches the position while it stays open and shows the alert text when the client is inside a store's radius (the location's geofence radius, with a default from the staff geofence setting). Nothing is stored or sent.
  • Browser push (opt-in): the client's subscription is stored per endpoint; only real browser push hosts over https are accepted. A welcome push is sent on subscribe. Later offer or points pushes are not sent.

Where owners configure it

Settings, Loyalty card (/dashboard/settings/loyalty-card), owner, brand manager and super admin only.

Setting Detail
Enabled Off by default. When off, the page shows "The loyalty card is not available right now."
Colour theme Oxblood (default), Ink, Slate, Moss, Paper. Saved as three hex colours.
Logo "Use brand logo" copies the brand theme logo; must be an https URL, otherwise no logo.
Alert text Required, max 140 characters, {store} placeholder.
Stores Pick stores for the alert; each selected store must have latitude and longitude (both or neither; -90 to 90 and -180 to 180). Coordinates edited here are saved to the location.

The page also shows the card URL as a QR code for printing, and whether Apple and Google credentials are configured.

Server configuration (names only)

Apple: APPLE_PASS_TYPE_ID, APPLE_TEAM_ID, APPLE_PASS_CERT_PEM, APPLE_PASS_KEY_PEM, APPLE_WWDR_PEM, optional APPLE_PASS_KEY_PASSPHRASE. Google: GOOGLE_WALLET_ISSUER_ID, GOOGLE_WALLET_SERVICE_ACCOUNT_JSON. Browser push: NEXT_PUBLIC_VAPID_PUBLIC_KEY. Barcode signing: PORTAL_SECRET. A wallet provider counts as configured only when all of its values are present.

Points expiry

Points expire on inactivity, not per earn batch.

  1. The brand enables the loyalty program and sets Points expiry (days) on Retention, Loyalty Points (loyalty_configs.expiry_days). Empty or 0 means points never expire.
  2. Daily, the cron finds each client whose latest ledger row is older than expiry_days while the balance is above zero. Any new earn, redeem or adjust restarts the clock.
  3. Reminder pass: clients whose balance expires within 7 days get a WhatsApp reminder (loyalty_points_expiry_reminder) with name, points and expiry date. Only one reminder per (client, last transaction) is sent, so a client is not nagged on every run. Brands without WhatsApp enabled, and clients without a phone, are skipped.
  4. Sweep pass: expire_loyalty_points() writes an expire ledger row that sets the balance to 0 (note "Points expired due to inactivity") and returns how many clients were expired.
Job Schedule Endpoint Auth
salonos-loyalty-points-expiry 30 4 * * * (pg_cron, migration 0176; 04:30 UTC, 10:00 IST) POST /api/cron/loyalty-points-expiry x-cron-secret header

Response is { reminded, expired, timestamp }. If the reminder lookup fails the error is logged and the sweep still runs. If the sweep fails the route returns 500 with reminded and "Failed to process expiry".

Reward tiers

  • A tier has a name, minimum points, points multiplier (default 1.0), discount percent, perks text, colour, sort order and an active flag. Managed at Settings, Reward tiers (/dashboard/settings/reward-tiers, manager roles).
  • A client's tier is the highest active tier whose min_points is at or below their current points balance. It is derived on read; there is no stored tier, no annual reset and no spend-based qualification. Because it uses the current balance, spending or expiring points can lower a client's tier.
  • The settings page shows how many clients sit in each tier.
  • Clients see their tier, perks, VIP discount percent and progress to the next tier in the portal and on the loyalty card.
  • Where the tier values are actually used in code: raffle weighting (multiplier, when the Loyalty tier option is on) and display. Checkout does not apply the tier's points multiplier when earning points or the tier discount percent to the bill.

Data model

Table Key columns
raffles brand, optional location, status (draft, active, drawn, cancelled), window, min_bill_minor, prize fields, winner_count, draw_mode, weighting (jsonb), exclude_recent_*, auto_draw, draw_seed, draw_weights, drawn_at
raffle_entries raffle, client, invoice, code, amount_minor, notified_at; unique per (raffle, invoice) and (raffle, code)
raffle_winners raffle, client, entry, rank, weight, prize_ref, prize_detail, prize_claimed_at, prize_attempts, notified_at; unique per (raffle, client) and (raffle, rank)
spin_wheel_configs one row per brand: is_enabled, milestone_points (default 500), spin_cost_points (default 200)
spin_wheel_prizes label, prize_type, value, weight, colour, image, sort_order, is_active
spin_wheel_spins client, spin_source (milestone/burn), points_spent, prize_snapshot, redeemed_at, redeemed_by, redeemed_invoice_id
loyalty_card_settings one row per brand: is_enabled, three colours, logo_url, alert_text, alert_location_ids
loyalty_card_push_subscriptions client, unique endpoint, p256dh, auth (service role access only)
loyalty_configs per brand: is_enabled, expiry_days (used by expiry), plus earn/redeem fields
loyalty_transactions the ledger: type earn/redeem/adjust/expire, points, balance_after, note
loyalty_expiry_notifications one row per (client, last transaction) reminded
reward_tiers name, min_points, points_multiplier, discount_pct, perks, colour, sort_order, is_active

Raffle writes go through the service-role client (org members can only read raffle data).

Permissions

Action Who
Open Raffles page, create, activate, cancel, draw Manager roles (super admin, org owner, brand manager, location manager). Location-scoped raffles also need access to that location. Brand-wide raffles: owner, brand manager, super admin only.
Spin wheel and Reward tiers pages Manager roles
Loyalty card settings Owner, brand manager, super admin (enforced in the action)
Cron endpoints Anyone holding CRON_SECRET
Raffle results page, card login, portal Public / client OTP session

Edge cases and failure behaviour

  • Raffle entry or WhatsApp failure never affects checkout; errors are captured and the bill goes through.
  • A cancel racing a draw: the draw wins (conditional status update). A second draw returns "This raffle has already been drawn".
  • A failed commit returns "Could not record the draw. Nothing was changed."
  • Activating a draft whose end date has passed, or whose membership plan became inactive, is refused with an explicit message.
  • Raffle voucher or membership issuing failures are retried by the hourly sweep up to 3 times, then flagged for manual issue.
  • Spin: a stale or already redeemed prize at checkout returns "This spin prize is no longer available to redeem" or "This prize was just redeemed on another bill, please retry".
  • Loyalty card: no session returns 401 on the pass routes; a pass build failure returns 500 "Could not create the pass" (details only go to server logs).
  • Wallet buttons and push toggle are hidden, not errored, when server credentials are not set.

Source

  • web/src/lib/raffles/ (service, draw, eligibility, admin-actions, queries, notify)
  • web/src/lib/spin-wheel/ (index, execute-spin, weighted-pick, admin-actions)
  • web/src/lib/loyalty-card/ (settings, passes, apple-pass, google-wallet-api, session, barcode, near-store, portal-actions)
  • web/src/lib/reward-tiers/, web/src/lib/loyalty/
  • web/src/app/(client)/raffle/[id]/page.tsx, web/src/app/(client)/card/[slug]/, web/src/app/api/loyalty-card/[slug]/
  • web/src/app/api/cron/raffle-draw/route.ts, web/src/app/api/cron/loyalty-points-expiry/route.ts
  • web/src/app/(tenant)/dashboard/loyalty/raffles/, .../settings/{spin-wheel,loyalty-card,reward-tiers}/, .../retention/loyalty/
  • web/src/lib/billing/actions.ts (raffle hook, spin redemption, points earn)
  • Migrations: 0057_reward_tiers, 0145/0146 (expiry), 0157/0159/0160 (spin), 0176 (pg_cron jobs), 0260 (raffles), 0261 (loyalty card), 0264 (raffle cron)