Memberships, Wallets, Packages & Gift Cards
How Club and Value Pack plans, prepaid wallets, cashback, session packages and gift cards work in code, and which module set owners should use.
15 min read
Overview
Kagami has five stored-value or prepaid instruments. They overlap in name, and two parallel code and route sets exist for several of them, so this page starts with what is actually reachable.

| Instrument | What the client buys | Where the balance lives | POS tender key |
|---|---|---|---|
| Club Membership | Time-bound % discount (plus optional free-session count) | client_memberships |
membership (free session) or automatic discount |
| Value Pack | Pay X, get Y prepaid wallet credit | wallets (created at enrolment) |
wallet |
| Prepaid wallet | Cash converted to wallet credit, cross-location | wallets + wallet_transactions |
wallet |
| Cashback (store credit) | Credit issued as referral reward or manual credit | store_credit_ledger |
cashback |
| Session package | N prepaid sessions of a service | see "Packages" (two table sets) | package |
| Gift card | Face value redeemed by code | gift_cards |
gift_card |
Client subscriptions (subscription_plans / client_subscriptions) are a sixth, separate feature, described at the end.
Which module set is canonical
Two route sets exist. They do not redirect to each other and they read and write different tables for packages.
| Route set | Pages | Library | Status today |
|---|---|---|---|
| Dashboard set | /dashboard/memberships, /dashboard/packages, /dashboard/prepaid-wallets |
lib/memberships, lib/appointment-packages, lib/retention/wallets |
In the sidebar (Loyalty hub and Menu & Catalog). Reachable. |
| Dashboard set, redirected | /dashboard/gift-cards, /dashboard/wallet, /dashboard/subscriptions, /dashboard/service-combos |
lib/gift-cards, lib/store-credit, lib/subscriptions |
Pages still exist in code but next.config.ts redirects (temporary, 307) gift-cards to /dashboard/loyalty, wallet and subscriptions to /dashboard/memberships, service-combos to /dashboard/packages. The page code cannot be reached by URL. |
| Retention set | /dashboard/retention, /retention/packages, /retention/memberships, /retention/gift-cards, /retention/loyalty |
lib/retention/* |
Not in the sidebar and not redirected. Reachable only by typing the URL (route rule ADMIN_ROLES, parent hub Loyalty). Uses the first brand by name (brands[0]) rather than the active brand. |
What each set actually does:
- Memberships (plans and members): both sets read and write the same tables (
membership_plans,client_memberships). The dashboard page is the fuller UI (members tab, plans tab, payments, edit, delete, per-item allowed tenders, location scoping). The retention page is a smaller plan/enrol view. The POS also useslib/retention/membershipsfor sale, redemption and discounts. - Packages: the sets are not interchangeable. Packages created on
/dashboard/packagesand packages sold at the POS are separate sets of tables (migrations 0045 and 0019). Check with your administrator before selling a package at the POS. See "Session packages" below. - Gift cards: both sets use the same
gift_cardstable. The only issue paths that are reachable are Settings > Vouchers (/dashboard/settings/vouchers) and the retention page; both calllib/retention. The richer dashboard page (templates, lookup, manual redeem) is behind the redirect. POS redemption useslib/retention/gift-cards. - Wallets:
/dashboard/prepaid-walletsis the only live UI for prepaid wallets. Alert and expiry thresholds are set at Settings > Wallets (/dashboard/settings/wallets). - Cashback: the
/dashboard/wallet("Client Wallet") UI for it is behind the redirect.
Recommendation for owners: use the sidebar pages (/dashboard/memberships, /dashboard/prepaid-wallets, Settings > Vouchers, Settings > Wallets) and do not use /dashboard/retention/* for packages. For packages, see the note in "Session packages" before selling any at the POS.
Club vs Value Pack plans
Plans live in membership_plans. plan_kind is club (default) or value_pack (migration 0151; the UI label is "Club & Value Packs").
| Rule | Club | Value Pack |
|---|---|---|
| Price | Must be greater than 0 | 0 or more (free promo packs allowed, SALO-2422) |
| Credit | Not used (credit_amount_minor stored as null) |
credit_amount_minor required and at least the price |
| Validity | Optional validity_days |
Required, greater than 0 |
| Discounts | service_discount_pct, product_discount_pct (0 to 100) |
Forced to 0; a non-zero value is rejected |
| Free sessions | free_sessions count |
Forced to 0 |
| Repeat purchase | One active enrolment per plan per client ("Client is already on this plan") | Can be bought repeatedly |
Validation is shared (validateMembershipPlanInput), and migration 0151 repeats the Value Pack rules as a database CHECK. Other plan fields: max_members (stored, not enforced at enrolment), location_ids (null or empty = all stores; POS filters by the active store), allowed_tenders (see Permissions), included_services / included_products JSON (stored; checkout does not read them, so they have no effect today).
Billing periods
billing_cycle allowed by the database: weekly, monthly, quarterly, annually. The dashboard upsert maps the UI values annual and one_time both to annually, so a "one time" plan is saved as an annual plan.
Renewal date calculation:
- If the plan has
validity_days,renews_atandends_atare bothstart + validity_days. - Otherwise
renews_at = start + one billing cycle(7 days, 1, 3 or 12 months). Club plans keepends_at = null(open-ended); Value Packs without validity getends_at = renews_at. recordMembershipPayment(dashboard "record payment") recomputesrenews_atandnext_payment_atfrom the period end. Its helper has noweeklycase, so a weekly plan advances one month there.
Membership states and transitions
client_memberships.status: active, paused, cancelled, expired (database CHECK).
| Transition | How | Side effects |
|---|---|---|
(new) to active |
Enrol (dashboard) or POS "sell membership" | Row created with started_at, renews_at, ends_at, next_payment_at. For a Value Pack a wallet is created (see Wallets). |
active to paused / back |
Status control in the members tab | Status only. No billing exists to pause. |
any to cancelled or expired |
Status control | ends_at set to today |
| any to any | The action does not check the current status | There is no transition guard. |
No scheduled job moves a membership to expired, renews it, or resets services_used. renews_at is informational; staff record each renewal payment manually. Checkout ignores memberships whose ends_at has passed, even if the status is still active.
Free-session redemption (Club only)
At checkout, getClientActiveMembershipsForCheckout offers a membership only when it is active, not past ends_at, is a Club plan, has free_sessions > 0, and services_used < free_sessions. Redemption (redeemMembershipSession) claims the session by compare-and-swap on services_used, then writes a membership_redemptions row (client_membership_id, invoice_id, appointment_id). A lost race returns "Free session was just redeemed, please retry". Value Packs reject redemption ("redeem via prepaid wallet"). Voiding the invoice decrements services_used and deletes the redemption rows (migrations 0196, 0277).
Club discounts apply automatically at POS: getClientClubBenefitsForCheckout takes the highest service % and the highest product % across the client's active Club memberships (they can come from different plans).
Sale at POS
"Sell membership" creates the invoice first (checkoutType: membership, line "Club Membership: name" or "Value Pack: name"), then enrols the client. If enrolment fails after payment, the invoice is voided and the staff member sees the reason (SALO-624). Default tenders for a membership sale are cash, card, UPI only (SALO-734); a plan can override this through allowed_tenders.
Dashboard enrolment (/dashboard/memberships) does not create an invoice. For a Value Pack it still issues the wallet credit. Payment is recorded separately (membership_payments).
Prepaid wallets
Tables: wallets (one per purchase), wallet_transactions (append-only ledger: credit, debit, top_up, expire, adjustment), wallet_reconciliation (cross-location), brand_wallet_settings, location_wallet_settings (migration 0099, 0143, 0164).
- Issue:
createWalletstorescash_paid_minor,wallet_amount_issued_minorandcost_ratio = cash / wallet amount(1 when cash is 0). Bonus value is issued minus cash paid. Wallet number formatWLT-<BRAND>-<YYYYMMDD>-<6 chars>, unique per org. Value Pack enrolment calls the same function with price as cash, plan credit as amount, andexpires_at = now + validity_days(180 if the plan has none). - Top up: adds to an existing active wallet with an optimistic balance guard. If the ledger insert fails the balance is rolled back. Top-ups do not extend
expires_at. - Redeem at POS (FIFO):
redeemFromWalletstakes active, non-expired wallets with balance, oldestpurchased_atfirst, and debits each through theapply_wallet_debitRPC (advisory lock, expected-balance check). Insufficient total returns "Insufficient balance: X available, Y requested". A wallet cannot be combined with a membership or package redemption on the same invoice (SALO-581), and by default wallet is not an allowed tender for package and combo sales or for membership sales (see Permissions). - Cross-location: brand switch
cross_location_enabled(default on) plus per-locationcross_location_issuance_enabled/cross_location_redemption_enabled(default on). When off, issuance clearssource_location_idand redemption is limited to wallets sourced at that location. A redemption away from the source location writes awallet_reconciliationrow withreconciliation_amount = redeemed * cost_ratio, statuspendinguntil settled. wallet_retail_redemption_enabled: saved by Settings > Wallets but not currently applied at redemption. Product eligibility is governed by per-item allowed tenders (default: wallet allowed for products).- Revenue report:
getWalletRevenueReport(owners only on the page) gives cash collected, bonus credit, redeemed, expired and brand-wide outstanding balance. It countsexpiretransactions, but nothing in the code writes them (see Edge cases).
Wallet alerts (low balance and expiry)
Settings per brand (brand_wallet_settings): low_balance_threshold_minor (default 500000 = ₹5,000) and expiry_warning_days (default 30). When no row exists the code returns the same defaults.
buildWalletAlert returns an alert only when the client has balance above 0 and either:
- balance is at or below the threshold (low balance), or
- the earliest expiry among wallets with balance is within
expiry_warning_days(expiring soon).
The alert shows as (a) a modal when a service starts, (b) at POS checkout and when a walk-in client is picked, and (c) a persistent header banner listing clients mid-visit: appointments in_progress or completed started within the last 36 hours with no paid invoice, brand-wide (SALO-732). Voided-only invoices and visits settled by a later paid bill for the same client are ignored (SALO-2445, SALO-2534).
Expiry reminder cron
POST /api/cron/reminders/wallet-expiry, authenticated by x-cron-secret. Scheduled daily at 04:30 UTC (10:00 IST) by pg_cron job salonos-wallet-expiry (migration 0176). It finds active wallets with balance, expiry_notified_at null and expires_at in the next 7 days (fixed window, independent of expiry_warning_days), for brands with WhatsApp enabled, and sends the wallet_expiry_reminder template with client name, balance and date. Idempotent per wallet (wallet_expiry:<id> slot). Brands with WhatsApp enabled but no credentials are skipped with a server log. Clients without a phone are skipped silently.
Cashback (store credit)
"Cashback" is the checkout label for the store credit ledger (store_credit_ledger, type credit or debit), separate from prepaid wallets.
- Balance: the latest
balance_afterfor the client and brand. Writes go through theapply_store_creditRPC (advisory lock per client+brand). A debit is capped at the balance and raises "no store credit balance" when empty. Debit rows store a negativeamount_minor. - Sources: referral rewards (
lib/referrals/rewards.ts), the AI delight-referral reward (lib/ai/delight-referral.ts), and manual credit (retentionaddStoreCreditAction, permissionwallets.add_money; thelib/store-creditactions behind the redirected/dashboard/walletpage). Cashback is not earned automatically on bills (there is no percentage-of-bill rule). - Spend at POS: tender
cashback, needs a selected client (not available to guests). Debited synchronously; if a later step fails the checkout rolls it back with a compensating credit. If the balance is lower than the requested amount the debit takes what is there (deducted_minor). - Where shown: client profile "Cashback Balance" and the client portal.
- Expiry: none. The ledger type list mentions
expirebut the RPC only acceptscreditanddebit. - Zylu import: Zylu cashback tenders were mapped to cashback or wallet by the importers (the Zylu import wizard and the nightly
zylu-sync, both retired in SALO-3006 and removed in SALO-3041). The imported rows stay as history.
Session packages (appointment packages)
Two unrelated table sets both describe prepaid session bundles:
| Dashboard / POS catalogue | Retention | |
|---|---|---|
| Plan table | session_packages (total_sessions, valid_days, location_ids, allowed_tenders) |
packages (sessions, validity_days) |
| Client table | client_session_packages (sessions_remaining) |
client_packages (sessions_used, is_active) |
| Redemption table | session_redemptions |
package_redemptions |
| Created from | /dashboard/packages |
/dashboard/retention/packages |
Behaviour per set:
session_packagesset:issueClientPackagesetsexpires_at = now + valid_days(null if no validity). Manual redeem on the packages page decrementssessions_remainingwith compare-and-swap and writessession_redemptions; "No sessions remaining" and "Package expired" are rejected. The page KPIs are revenue, active packages, sessions sold and sessions left.client_packagesset:sellPackageToClientsetsexpires_at = now + validity_days(default 365 in the plan). Redemption at POS (redeemPackageSession) rejects inactive, expired or used-up packages, claims by compare-and-swap onsessions_used, flipsis_activeoff when the last session is used, and writespackage_redemptions(invoice_id,value_minor). Voiding the invoice returns the session and reactivates the package.
Note for owners: packages created on /dashboard/packages and packages sold at the POS are separate sets of tables. Check with your administrator before selling a package at the POS. If a POS package sale cannot be completed, the invoice is voided and the screen shows "Payment succeeded but package sale failed" with the reason.
Service combos (/dashboard/service-combos, redirected to /dashboard/packages) are a separate entity (service_combos) and not covered here.
Gift cards
- Code: 12 characters from
ABCDEFGHJKLMNPQRSTUVWXYZ23456789inXXXX-XXXX-XXXXform. Lookup upper-cases and trims input. - Issue: requires
wallets.add_moneyand an open salon day (saleBlockedReason). Amount must be a positive integer in minor units. Expiry differs by module: the retention path (the one reachable from Settings > Vouchers) uses the suppliedexpires_ator no expiry; the redirected dashboard path defaults to 365 days (validity_days) and supports denomination templates (gift_card_templates:value_minor, optionalsale_price_minor,validity_days). - Redeem at POS: pass
giftCardCode. The server validates found, active, not expired, and balance covering the entire invoice total (otherwise "Gift card balance (X) is less than invoice total (Y)"). So a card can pay a bill in full and keep a remaining balance, but cannot be combined with other tenders to cover a bill larger than its balance. Lookup is by org, not brand. - Redemption write: compare-and-swap on
balance_minor, then agift_card_redemptionsrow. A card that reaches 0 becomes inactive. Retention caps the redeemed amount at the balance; the dashboard-set redeem rejects over-balance amounts. - Void: the invoice void RPC restores balance, reactivates the card and deletes the redemption rows.
- Sending: the app does not send a card by WhatsApp or email; recipient fields are stored only.
Client subscriptions
subscription_plans (price, billing_period, credits_per_period) and client_subscriptions (status active/paused/cancelled, credits_used, next_billing_at) with a subscription_usages log (migration 0051). The only UI is /dashboard/subscriptions, which redirects to /dashboard/memberships, so the feature is not reachable from the app today. Behaviour in code: usage stops at credits_per_period ("No credits remaining this period"); nothing resets credits_used or bills automatically; price_minor of active subscriptions is summed as "MRR" regardless of period. Treat the feature as not available.
Permissions
Sidebar and route access for these pages is ADMIN_ROLES (super admin, org owner, brand manager, location manager). Action-level checks use the permission toggles in lib/auth/permissions.ts (default roles: org owner, brand manager, location manager; owner can grant others). requireManagerOrPermission always passes managers and requires the toggle for anyone else.
| Action | Check in code |
|---|---|
| Create / edit / delete membership plan (dashboard) | memberships.plans |
| Create / edit / toggle / delete session package (dashboard) | packages.manage |
| Issue client session package | manager, or billing.create |
| Sell retention package (used by POS) | manager, or billing.create, plus open salon day |
| Issue wallet, top up wallet | wallets.add_money, plus open salon day |
| Issue gift card | wallets.add_money, plus open salon day |
| Add store credit (retention action) | wallets.add_money |
| Redeem gift card (dashboard action) | billing.create |
| Void an invoice (reverses all of the above) | billing.void toggle |
The pages listed in this document are admin pages: they are shown only to the admin roles above. Other actions (enrolling a client, changing a membership's status, recording a membership payment, manual session redemption, wallet settings, reconciliation) are managed from those pages. The wallet revenue report is shown to owners only. Use the Settings > Roles page to control which roles can use the permission-toggled actions in the table.
Per-item allowed tenders (allowed_tenders, migration 0167, SALO-741) are edited on the plan and package rows; defaults when null: membership cash/card/UPI; package and combo cash/card/UPI/other; product cash/card/UPI/wallet/other. Cashback, loyalty points, complimentary and gift card are fixed-rule tenders, not per-item.
Data model (key tables)
| Table | Key columns |
|---|---|
membership_plans |
plan_kind, billing_cycle, price_minor, credit_amount_minor, validity_days, free_sessions, service_discount_pct, product_discount_pct, max_members, location_ids, allowed_tenders, is_active |
client_memberships |
status, started_at, renews_at, ends_at, next_payment_at, last_payment_at, services_used, notes |
membership_payments, membership_redemptions |
payment per period; one row per free session used |
wallets / wallet_transactions / wallet_reconciliation |
see Prepaid wallets; expiry_notified_at for the reminder |
brand_wallet_settings / location_wallet_settings |
thresholds and cross-location switches |
store_credit_ledger |
signed amount_minor, balance_after, type, ref_id, note |
session_packages / client_session_packages / session_redemptions |
dashboard package set |
packages / client_packages / package_redemptions |
retention package set (used by POS redemption) |
gift_cards / gift_card_redemptions / gift_card_templates |
card balance, expiry, template |
subscription_plans / client_subscriptions / subscription_usages |
subscriptions |
Migrations: 0019 (retention base), 0028 (gift card templates), 0029 (membership columns), 0045 (session packages), 0051 (subscriptions), 0094 (atomic store credit), 0099 (wallets), 0126 (store filters), 0143, 0151 (plan kinds), 0164 (alert thresholds), 0167 (allowed tenders), 0176 (pg_cron), 0179 (cashback payment method), 0180 (wallet stats RPC), 0196 and 0277 (void reversal RPC).
Edge cases and failure behaviour
- Expired wallets still count in balances.
getClientWalletSummary(POS balance, alert) andgetClientWalletBalance(portal) sum every active wallet's balance without excluding expired wallets, while redemption does exclude them. A client can see a spendable balance that FIFO redemption then refuses. No job writesexpiretransactions or deactivates expired wallets, so the revenue report's expired figure is always 0 unless data was imported. - Value Pack partial failure: if the membership row is created but the wallet creation fails, enrolment returns an error with the membership id and the message "Membership enrolled but wallet failed". At POS this voids the invoice, but the membership row is not removed (staff should check the client's memberships before retrying).
- Gift card, package and wallet write failures are rolled back where a ledger write fails after the balance claim (gift card, wallet top-up, checkout rollback).
- Cashback is not reversed by an invoice void. Voiding an invoice restores gift cards, packages, memberships, wallet debits and loyalty points; cashback paid on the invoice is not credited back (a checkout that fails part-way does roll cashback back). Add the credit back by hand if needed.
- Dashboard KPI "Monthly Recurring" sums the plan price of every active member regardless of billing cycle or Value Pack kind.
- Redirected pages (gift cards, wallet, subscriptions) show no error; the user simply lands on another page.
- Salon day closed: issuing wallets, top-ups, gift cards and package sales return the closed-day message instead of writing.
- Errors from these actions come back as
{ error }strings shown in the UI. List actions (plans, memberships, gift cards, wallet transactions, alert feeds) return an empty list when loading fails, so a loading error can look like "no data"; refresh the page to retry.
Source
web/src/lib/memberships/,web/src/lib/retention/memberships.ts,membership-plan-kind.tsweb/src/lib/retention/wallets.ts,wallet-alert.ts,wallet-admin-actions.ts,types.tsweb/src/lib/store-credit/,web/src/lib/retention/store-credit.tsweb/src/lib/appointment-packages/,web/src/lib/retention/packages.tsweb/src/lib/gift-cards/,web/src/lib/retention/gift-cards.tsweb/src/lib/subscriptions/web/src/lib/billing/actions.ts(checkout redemption order, POS lists, void),tender-eligibility.tsweb/src/app/(tenant)/dashboard/{memberships,packages,prepaid-wallets,gift-cards,wallet,subscriptions,retention}/web/src/app/api/cron/reminders/wallet-expiry/route.tsweb/next.config.ts(redirects),web/src/lib/nav/sections.ts,web/src/lib/auth/permissions.tsweb/supabase/migrations/(numbers listed above)