# Loyalty

The store's loyalty program: points a customer earns
on their orders and spends on rewards, with referrals and VIP tiers beside
it. A storefront does two things with it: it shows the program to every
visitor (the ways to earn, the names, the switches) and it shows a
signed-in shopper their own points. The platform does the rest: an order
earns on the bus, by the store's rules, the moment the store's setting
names; a cancel or a refund takes the points back.

What is built today is the points core, the rewards, the daily clock, the
referrals and the VIP tiers: the program read (the ways to earn, the ways
to redeem, the referral program, the tiers with their entry rewards and
perks), the wallet read (the balance, the history, the rewards the shopper
holds, the day the points reset, the shopper's referral link and referrals,
their VIP standing), earning on an order, on an account and on a birthday,
the reversals, the redemption (the shopper spends points and gets a
single-use code for the checkout's one code field), the expiry of an
untouched balance with its two warnings, the referral link with its claim
and its completion, and the climb through the tiers with what arriving
pays. The mails: the order confirmation, the
cancellation and the refund carry a loyalty section for a customer in the
program (the points earned or returned, the balance, the tier), and the
program sends two mails of its own, Your reward (a code issued: a
redemption, the birthday's points, a referral's reward, a tier's entry
reward) and Expiring soon (the points about to reset, an unused code about
to expire), both leading to the store's `/account`. A storefront builds
nothing for them; the merchant edits them on Settings, Notifications with
the `loyalty.*` variables ([variables.md](variables.md)). The on-site
pieces come with their own step and will be documented here as they land.

## How a shopper earns

- **Points are the customer's**, never the browser's: they accrue to the
  customer row every order carries, and spending them needs the store's
  session ([customer-accounts.md](customer-accounts.md)). With the store's
  participation at `all_customers` a guest's order earns onto their
  customer row and the points wait for them to sign in; at
  `account_holders` only a customer with an account earns.
- **An order earns once per active "Place an order" rule**, on the amount
  the platform derives from the order's own lines: the items the shopper
  paid for, VAT included (the price they saw), a gift card line and the
  store's excluded products left out, shipping only when the store counts
  it. An `increments` rule pays `points` per 1 of the store's currency,
  rounded to the nearest point; a `fixed` rule pays `points` per order.
- **When**: `earn_when` is `paid` (the order reads paid in full: a card
  order at once, a cash on delivery order when the courier collects) or
  `placed` (the moment Place order answers). The points wait `delay_days`
  before they can be spent, pending until then.
- **Taken back**: a canceled order gives back everything it still holds; a
  refund gives back the refunded share of each earn, rounded, so partial
  refunds that add up to the order take it all back.
- **A birthday**: a `birthday` rule pays its points on the day, on the
  store's own clock, once a year, for a birthday saved at least thirty days
  before (the wallet's `birthday`, set through the account; a change within
  a year of a payout waits a year). Points only, never a code.
- **Expiry**: where the store sets `expiry_days`, a balance that has not
  moved for that long resets to zero; any earn, redemption or adjustment
  restarts the clock, and pending points count when they are released. The
  wallet's `expires_at` is the day the spendable points reset unless the
  balance moves (null while the store does not expire points). The store
  warns the shopper twice before, by mail, where the shopper may be mailed.

## How a shopper spends

- **A reward is a discount the merchant priced in points**: an amount
  off, a percentage off, free shipping, or one unit of a product free (up
  to a value). The program read lists them, the cheapest first.
- **The ledger is a money ledger**: one signed row per movement of points,
  never edited, never deleted, the balance the database's own sum. A
  redemption, a cut by the merchant and the expiry are judged under the
  customer's lock, one after the other, and never take the balance below
  zero: of two redemptions fired at once on a balance worth one, the second
  is refused `insufficient_points`. A cancel or a refund takes an earn back
  whole, so a balance can read negative until the next earn.
- **Redeeming mints a code**: `POST /api/store/loyalty/redeem` takes the
  points off the balance at once and answers a single-use code, the same
  kind of code a promotion's pool hands out. The shopper types it into the
  checkout's one code field ([checkout.md](checkout.md), `POST
  /api/store/carts/{id}/codes`) and the platform applies it as it applies
  every code: the discount shows on the cart, combines by the promotion's
  rules, and is refused in one sentence when the cart does not qualify.
  An abandoned code does not return its points by itself; the merchant's
  Refund points does.
- **Locked to the shopper**: where the reward says so (the default), the
  code works only on a cart that carries the customer it was issued to,
  by the store's session or by their email. On anyone else's cart the one
  code field answers `400 promotion_code_not_for_customer`, "This code can
  only be used on the account it was issued to."; the platform judges it
  again when the order is placed.
- **Expiry**: a reward may give its codes a life in days; the wallet shows
  `expires_at` and the state (`issued`, `used`, `expired`, `refunded`).

## How a shopper refers

- **The link is the shopper's**: `{store}/r/{code}`, the `code` the
  wallet's `referral.code`, minted the first time the wallet is read. The
  package's referral section shows it with the sharing channels and the
  message of the program's `referrals.share`; the store mounts the landing
  at `referrals.landing_path` (the home by default) and reads the link on
  arrival (`POST /api/store/loyalty/referral/{code}/visit`, which counts
  the visit).
- **The friend claims with an email**, signed out, on the landing's claim
  popup: a new customer only (no account, no order, not the advocate),
  once per email ever. The claim births the friend's guest customer row,
  as a cart does, and answers the friend reward's code (locked to that row
  where the reward says so), the same kind of code a redemption mints. The
  friend need not use it, nor make an account: their first order with the
  claiming email is enough.
- **The advocate is rewarded** when the friend's first order reaches the
  store's earn moment (`earn_when`: paid in full, or placed): points onto
  their balance (a `points` reward), or a code. Their wallet's `referral`
  lists every friend with the state: `pending` (claimed, no order yet),
  `completed`, `blocked` (the store's fraud rule flagged it; the merchant
  reviews it), `canceled`.
- **Blocked**: a friend's email that reads as the advocate's own (the
  same address without dots and plus tags), too many claims from one
  address in a day, an order that is not the friend's first, or an order
  the advocate placed themselves. The claim popup hears `409
  referral_blocked`; the merchant's Unblock settles it.

## How a shopper climbs

- **The tiers are the store's**: the program's `vip.tiers`, the entry tier
  first, each with its `milestone`, its icon, its `perks` (words to list)
  and its `entry_rewards` (what arriving pays: codes, or points). The unit
  of the milestones is `vip.basis`: `points_earned` (the points earned in
  all, never lowered by a redemption, an expiry or a hand cut, lowered by a
  refund; pending points count once released) or `amount_spent` (the
  orders' totals at the store's earn moment, shipping and VAT included,
  discounts taken off, less what was refunded).
- **The shopper's standing** is the wallet's `vip`: the tier held, since
  when, `progress` in the basis's unit for the current window, the
  `next_tier` and what is `remaining` to reach it. No member is ever
  tier-less: a shopper who has not reached anything stands in the entry
  tier.
- **Moving up** happens the moment the progress meets a milestone (an
  order at the store's earn moment, a hand raise, a referral's points, the
  birthday points), every tier passed when skipping: the entry rewards of
  each are paid at once, points onto the balance or codes into the wallet's
  `rewards` (their `state` as any code's), and the store mails the shopper
  where it may. The merchant may also move a shopper up by hand, which
  pays the same.
- **The window**: `vip.timeframe` `lifetime` never takes a tier away.
  `calendar_year` holds a tier reached in a year for the rest of it and the
  whole next year (`vip.until`, the first instant the tier is judged
  again); the previous year's progress still counts for this year; a
  shopper who did not reach the tier again by then drops to what their
  progress meets, with nothing paid.
- **Who may earn and redeem**: a way to earn or a way to redeem may be
  limited to tiers (`tier_mode` `include` with the tiers in `tier_ids`, or
  `exclude`; null is every customer). A rule the shopper's tier is not in
  pays nothing, and the tier judged is the one held before the order, so
  an order that lifts a shopper earns at the old tier's rate; a reward the
  shopper's tier is not in answers `409 reward_not_eligible` at the redeem
  door. The package shows the lock from the shopper's `vip.tier.id`.

## How a campaign boosts

- **One at a time**: the program's `points.campaign` is the bonus campaign
  running now, or null. It names the Place an order rules it boosts
  (`rule_ids`, among `earning_rules`), its `multiplier` (2 is double
  points) and when it `ends_at`; the merchant may end it sooner, and then
  `ends_at` is that instant. Nothing but orders is boosted: a welcome, a
  birthday, a referral or a tier's reward pays what it always pays.
- **What an order earns**: for each rule the campaign names, the rule's
  points times the multiplier, rounded to the nearest point; the other
  rules pay as always. The campaign multiplies what the rule pays, so a
  rule past its per-customer limit pays nothing, boosted or not. The
  campaign live when the order was PLACED decides,
  so an order placed inside the window and paid after it keeps its boost.
  The wallet's history shows the boosted entry as one line with the
  boosted points. "Up to" for a signed-out visitor is the best rule's
  points times the multiplier, the package's arithmetic.
- **What the package shows**: the nudge once per customer, a card at the
  top of the panel's home, a multiplier badge on the product page and the
  checkout embeds, a banner with the end date in the hub. The nudge's
  once-ness is the platform's: call the campaign-nudge door when it was
  shown, and the wallet's `campaign_nudged_id` names the campaign from then
  on, on every device the shopper signs in on.

## GET /api/store/loyalty: the program

- **Purpose**: the three programs' switches, the names, when an order
  earns, the delay and the expiry rule, the active ways to earn and the
  ways to redeem, the bonus campaign running now, the referral program
  with its two rewards, the VIP tiers with their entry rewards and perks.
- **Auth**: anon (`x-client-id` or the publishable key).
- **Request**: no params.
- **Response**:

```jsonc
{
  "loyalty": {
    "points": {
      "active": true,
      "program_name": null,                 // null: show the store's name
      "currency": { "singular": "point", "plural": "points" },
      "earn_when": "paid",                  // "paid" | "placed"
      "delay_days": 0,                      // days order points wait; 0 is at once
      "expiry_days": null,                  // a balance untouched this many days resets; null never
      "earning_rules": [                    // empty while Points is off
        {
          "id": "ler_…",
          "type": "place_order",            // place_order | create_account | birthday | product_review | click_link | custom_activity
          "name": "Earn 2 points per 1 EUR",
          "icon_url": null,
          "earning_type": "increments",     // increments: `points` per 1 of currency; fixed: `points` per act
          "points": 2,
          "url": null,                      // click_link: where the customer is sent
          "call_to_action": null,           // click_link: the button's words
          "tier_mode": null,                // include (one tier) | exclude (tiers) | null: every customer
          "tier_ids": []
        }
      ],
      "rewards": [                          // the ways to redeem, the cheapest first; empty while Points is off
        {
          "id": "lrw_…",
          "type": "amount_discount",        // amount_discount | percentage_off | free_shipping | free_product
          "name": "5 EUR off",
          "icon_url": null,
          "points_cost": 500,
          "value": 5,                       // the amount off, the percent, or the cap; null covers shipping whole
          "currency_code": "eur",           // null for a percent
          "product_id": null,               // free_product: the product
          "collection_id": null,            // amount_discount, percentage_off: the collection it applies to
          "expires_after_days": 30,         // days an issued code lives; null never
          "tier_mode": null,                // include | exclude | null: every customer may redeem
          "tier_ids": []
        }
      ],
      "campaign": {                         // the bonus campaign running now; null while none runs
        "id": "lbc_…",
        "name": "Double points weekend",
        "multiplier": 2,                    // 2 is double points on the rules named
        "rule_ids": ["ler_…"],              // the Place an order rules it boosts, among earning_rules
        "starts_at": "2026-10-24T00:00:00.000Z",
        "ends_at": "2026-10-26T00:00:00.000Z"   // the merchant may end it sooner; then this is that instant
      }
    },
    "referrals": {
      "active": false,
      "landing_path": "/",                  // where a referral link lands on the store
      "share": { "channels": ["email", "facebook", "x"], "message": null },   // message null: the package's default words
      "preview": { "title": null, "description": null, "image_url": null },
      "advocate_reward": null,              // a reward shape (type "points": `value` the points), or null
      "friend_reward": null                 // a reward shape (a code), or null
    },
    "vip": {
      "active": true,
      "basis": "points_earned",             // points_earned | amount_spent: the unit of the milestones
      "timeframe": "lifetime",              // lifetime | calendar_year
      "tiers": [                            // the entry tier first; empty while VIP is off
        { "id": "ltr_…", "name": "Bronze", "milestone": 0, "icon_url": null, "perks": [], "entry_rewards": [] },
        {
          "id": "ltr_…",
          "name": "Silver",
          "milestone": 500,
          "icon_url": null,
          "perks": ["Early access to sales"],
          "entry_rewards": [                // what arriving pays: codes, or points (type "points", `value` the points)
            { "id": "lrw_…", "type": "percentage_off", "name": "10% off", "points_cost": 0, "value": 10, "currency_code": null, "product_id": null, "collection_id": null, "expires_after_days": 30, "icon_url": null, "tier_mode": null, "tier_ids": [] }
          ]
        }
      ]
    }
  }
}
```

- **Errors**: `400 missing_client_id`.

```bash
# The program: every store answers it, the switches off until the merchant turns one on.
BODY=$(curl -sf "$BASE/api/store/loyalty" -H "x-client-id: $CLIENT_ID")
echo "$BODY" | node -e 'const b=JSON.parse(require("fs").readFileSync(0,"utf8")); const p=b.loyalty&&b.loyalty.points; if(!p||typeof p.active!=="boolean"||!Array.isArray(p.earning_rules)||!Array.isArray(p.rewards)||!p.currency) process.exit(1)'
```

## GET /api/store/loyalty/me: the shopper's wallet

- **Purpose**: the signed-in shopper's balance, pending points, points
  earned in all, the day the points reset, their newest entries, the
  rewards issued to them, their referral link with their referrals, and
  their VIP standing.
- **Auth**: the store's session cookie (the sign-in with a code,
  [customer-accounts.md](customer-accounts.md)) or a bearer token; nobody
  else's wallet is reachable.
- **Request**: no params.
- **Response**:

```jsonc
{
  "wallet": {
    "excluded": false,          // the merchant excluded this customer: nothing of the program reaches them
    "member_since": "2026-10-22T10:00:00.000Z",
    "birthday": null,           // { "month": 2, "day": 29 } once set
    "balance": 460,             // what can be spent now
    "pending": 0,               // order points still inside the delay
    "lifetime_earned": 460,     // never lowered by a redemption, an expiry or a hand cut; a refund lowers it
    "expires_at": null,         // the day the spendable points reset unless the balance moves; null while the store does not expire points
    "history": [                // the newest entries, fifty at most
      {
        "id": "lpe_…",
        "kind": "earn",         // earn | redeem | adjust | reverse | refund | expire | import
        "points": 460,          // signed
        "description": "Earn 2 points per 1 EUR",
        "order_id": "order_…",
        "available_at": "2026-10-22T10:00:00.000Z",
        "occurred_at": "2026-10-22T10:00:00.000Z"
      }
    ],
    "rewards": [                // the rewards issued to the shopper, newest first, fifty at most
      {
        "id": "lrf_…",
        "reward": { "id": "lrw_…", "name": "5 EUR off", "type": "amount_discount", "value": 5, "currency_code": "eur" },
        "code": "LPK7M2PQ9X",   // what to type into the checkout's one code field
        "points": 500,          // what it cost
        "state": "issued",      // issued | used | expired | refunded
        "issued_at": "2026-10-23T10:00:00.000Z",
        "expires_at": "2026-11-22T10:00:00.000Z",
        "order_id": null        // the order that used it, once one did
      }
    ],
    "referral": {               // null while the referral program is off or the shopper may not refer
      "code": "K7M2PQ9X",
      "path": "/r/K7M2PQ9X",    // the link's path on the store
      "clicks": 12,
      "counts": { "pending": 1, "completed": 2, "blocked": 0, "canceled": 0 },
      "history": [              // the newest referrals, fifty at most
        { "id": "lrr_…", "friend_email": "m***@example.com", "state": "completed", "claimed_at": "2026-10-20T09:00:00.000Z", "completed_at": "2026-10-21T15:30:00.000Z" }
      ]
    },
    "vip": {                    // null while VIP is off or the shopper is excluded
      "basis": "points_earned",
      "timeframe": "lifetime",
      "tier": { "id": "ltr_…", "name": "Silver", "milestone": 500, "icon_url": null, "perks": ["Early access to sales"] },
      "since": "2026-10-23T10:00:00.000Z",
      "until": null,            // calendar_year: the first instant the tier is judged again
      "progress": 640,          // in the basis's unit, the current window
      "next_tier": { "id": "ltr_…", "name": "Gold", "milestone": 2000 },   // null at the top
      "remaining": 1360
    },
    "campaign_nudged_id": null  // the bonus campaign whose nudge the shopper has seen; null for none yet
  }
}
```

- **Errors**: `401 unauthenticated` without a session, `400 missing_client_id`.

```bash
# No session, no wallet.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/store/loyalty/me" -H "x-client-id: $CLIENT_ID")
test "$STATUS" = 401
```

## POST /api/store/loyalty/redeem: spend points on a reward

- **Purpose**: the shopper spends points on a reward and gets its code.
- **Auth**: the store's session cookie or a bearer token.
- **Request**: `{ "reward_id": "lrw_…" }`, a reward from the program's
  `rewards`.
- **Response**: `{ "reward": { … the issued reward, as the wallet lists it,
  "state": "issued" … }, "wallet": { … the wallet after … } }`.
- **Errors**: `401 unauthenticated`; `409 insufficient_points` (the balance
  and the cost in `details`), `409 reward_not_active`, `409
  reward_not_eligible` (the reward is for other VIP tiers), `409
  points_off`, `409 customer_not_taking_part`; `403 customer_excluded`;
  `404 not_found`.

```bash
# No session, no redemption.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' -X POST "$BASE/api/store/loyalty/redeem" -H "x-client-id: $CLIENT_ID" -H "content-type: application/json" -d '{"reward_id":"lrw_none"}')
test "$STATUS" = 401
```

## POST /api/store/loyalty/me/campaign-nudge: the nudge was shown

- **Purpose**: the storefront showed the signed-in shopper the running
  bonus campaign's nudge, which is shown once per customer; from then on
  the wallet's `campaign_nudged_id` names the campaign, on every device.
- **Auth**: the store's session cookie or a bearer token.
- **Request**: `{ "campaign_id": "lbc_…" }`, the program's `points.campaign`.
- **Response**: `{ "wallet": { … the wallet after … } }`.
- **Errors**: `401 unauthenticated`; `409 campaign_not_active` once the
  campaign is over; `404 not_found` for a campaign the store has not got.

```bash
# No session, no nudge.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' -X POST "$BASE/api/store/loyalty/me/campaign-nudge" -H "x-client-id: $CLIENT_ID" -H "content-type: application/json" -d '{"campaign_id":"lbc_none"}')
test "$STATUS" = 401
```

## GET /api/store/loyalty/referral/{code}: a referral link

- **Purpose**: what the friend sees on arrival at `{store}/r/{code}`: the
  advocate's first name, the friend reward, where the link lands, the
  link's preview. Pure; `POST .../visit` answers the same and counts the
  visit, the one call the package makes on arrival.
- **Auth**: anon (`x-client-id` or the publishable key).
- **Response**:

```jsonc
{
  "referral": {
    "advocate_first_name": "Alex",      // null when they gave none
    "friend_reward": { "id": "lrw_…", "type": "percentage_off", "name": "10% off your first order", "points_cost": 0, "value": 10, "currency_code": null, "product_id": null, "collection_id": null, "expires_after_days": 30, "icon_url": null },
    "landing_path": "/",
    "preview": { "title": null, "description": null, "image_url": null }
  }
}
```

- **Errors**: `404 referral_code_unknown` (a code nobody holds; a dead
  link reads the same), `409 referrals_off`, `400 missing_client_id`.

```bash
# A code nobody holds is unknown; a store with the program off refuses every code.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/store/loyalty/referral/NOBODY00" -H "x-client-id: $CLIENT_ID")
test "$STATUS" = 404 -o "$STATUS" = 409
```

## POST /api/store/loyalty/referral/{code}/claim: the friend's claim

- **Purpose**: the friend enters their email on the landing's claim popup
  and gets the friend reward's code.
- **Auth**: anon; the popup shows only to a visitor who is signed out.
- **Request**: `{ "email": "friend@example.com" }`.
- **Response**: `{ "referral": { "id": "lrr_…", "state": "pending",
  "claimed_at": "…" }, "reward": { … the issued code, as the wallet lists
  it, or null when the store set no friend reward … } }`, 201.
- **Errors**: `409 friend_not_new` (an account or an order already, or
  the advocate's own address), `409 already_claimed`, `409
  referral_blocked`, `409 referrals_off`; `404 referral_code_unknown`;
  `400 validation_failed` for an address that is none.

```bash
# No code, no claim.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' -X POST "$BASE/api/store/loyalty/referral/NOBODY00/claim" -H "x-client-id: $CLIENT_ID" -H "content-type: application/json" -d '{"email":"friend@example.com"}')
test "$STATUS" = 404 -o "$STATUS" = 409
```

## Settings

- **Loyalty** (admin, Apps): the three programs' switches, the program's
  and the points currency's names, who takes part, when and on what an
  order earns, the products that never earn, the delay, the expiry rule
  with its two warning thresholds, the ways to earn, the ways to redeem
  (each a promotion of the store's own with its pool of codes), every
  customer's points with the merchant's own adjustments, exclusions, Spend
  points and Refund points, the issued rewards and the ledger, the referral
  program (its switch, the advocate's and the friend's rewards, the landing
  path, the sharing channels and message, the link's preview, every
  referral with Cancel and Unblock), the VIP program (its switch, the
  basis, the timeframe and the start date, the tiers with their milestones,
  icons, perks and entry rewards, every tier move, Change tier on a
  customer) (`docs/contracts/admin-api.md` § 52). The daily clock
  (`loyalty-daily`, 06:30 UTC) releases, resets, warns, pays the birthdays
  and judges the tiers due for every store with Points or VIP on.
