# Referral — API

**Author**: Josh S. Sakweli, Backend Lead Team  
**Last Updated**: 2026-11-21  
**Version**: v1.0

**Base URL**: `http://localhost:8765/api/v1` (local) · `https://dev.api.nexgate.co/api/v1` (staging)

**Short Description**: Refer a friend, both get a coupon. The friend gets a **welcome coupon** when they use the inviter's
code right after signing up; the inviter gets a **thank-you coupon 7 days after the friend's first order completes**.
Rewards are NexGate coupons ([coupon API](../coupons/coupon_api_doc.md)); referral decides who earns one and when.
Design and the 17 rules: [`REFERRAL_SPEC.md`](REFERRAL_SPEC.md); build decisions: [`REFERRAL_BUILD_PLAN.md`](REFERRAL_BUILD_PLAN.md) §0a.

**Hints**:
- Every call uses the person's normal login: `Authorization: Bearer <access token>`.
- **Two switches**: the feature switch (off → every endpoint here answers **404**) and the programme's own on/off in the
  admin settings (off → the use-code step is refused with `REFERRAL_PAUSED` and no rewards are given).
- **Sign-up is unchanged.** The code is given in a new step called right after sign-up (endpoint 3).
- A person is identified by `accountId`; toward other people only **first names** are shown, never phones or usernames.
- Refusals are **HTTP 409** with `data.code` and `data.reason` (show the reason as it is).

---

## Contents

- Part 1 — How it works
- Part 2 — App: invite friends and the code step (1–4)
- Part 3 — Admin (5–14)
- Part 4 — Notifications
- Part 5 — Refusal codes
- Part 6 — Web page and installs (not backend)
- Part 7 — Screens checklist

---

# Part 1 — How it works

## 1.1 The journey

```
 ASHA (has a completed order)                 SERVER                                  JUMA (new)
 ────────────────────────────                 ──────                                  ──────────
 Invite friends ─► GET /referrals/me ───────► code K7P2QX4M, link nexgate.co/r/K7P2QX4M
 shares the link (WhatsApp, SMS …)
                                                                                      taps link → installs → signs up (unchanged)
                                              ◄────────────────────────────────────── GET /referrals/codes/K7P2QX4M  ("Invited by Asha")
                                              ◄────────────────────────────────────── POST /referrals/use-code { code }
                                              checks: new member, before first order, within 7 days,
                                              not Asha's own code, not Asha's phone, Asha can invite
                                              welcome coupon (14 days) ─────────────► COUPON_RECEIVED "👋 Welcome! Asha invited you…"
 REFERRAL_FRIEND_JOINED ◄──────────────────── referral SIGNED_UP
                                                                                      first order (≥ minimum, within 30 days,
                                                                                      not at Asha's shop) … completed
 REFERRAL_FRIEND_BOUGHT ◄──────────────────── ORDER_COMPLETED, reward due in 7 days
        … 7 days …                            reward job: refunded? warning signs? monthly cap? pot?
 REFERRAL_REWARD_EARNED ◄──────────────────── REWARDED: thank-you coupon (30 days) in Asha's My coupons
   or REFERRAL_REWARD_HELD  (a warning sign: an admin decides)
   or REFERRAL_REWARD_MISSED (with the reason)
```

## 1.2 States

```
 SIGNED_UP ─► ORDER_COMPLETED ─┬─► REWARDED
     │                         ├─► IN_REVIEW ─┬─► REWARDED       (admin approves)
     │                         │              └─► NOT_REWARDED   (admin refuses)
     │                         └─► NOT_REWARDED  (refunded, cap, paused, removed)
     └─► NOT_REWARDED  (first order under the minimum, after 30 days, at the inviter's own shop / where they are staff)
```

A cancelled order never completes, so the friend's **next** completed order is their first.

## 1.3 Examples

| Juma's first completed order | Asha gets |
|---|---|
| 25,000 of items at Tech Shop, 5 days after joining | the thank-you coupon 7 days later ✅ |
| 15,000 (the minimum is 20,000) | nothing: "His first order was under 20,000" ❌ |
| at Asha's own shop (or a shop where she is staff) | nothing: "His first order was at your own shop" ❌ |
| refunded within the 7 days | nothing: "His first order was refunded or cancelled" ❌ |
| Asha already earned 10 rewards this month | nothing: "Monthly limit of 10 rewards reached" ❌ |
| Juma signed in on Asha's phone | the code is refused at the code step ❌ |

---

## Standard Response Format

```json
{ "success": true, "httpStatus": "OK", "message": "Invite code used", "action_time": "2026-11-21T10:30:45", "data": { } }
```
```json
{ "success": false, "httpStatus": "CONFLICT", "message": "You can't use your own invite code", "action_time": "2026-11-21T10:30:45",
  "data": { "code": "REFERRAL_OWN_CODE", "reason": "You can't use your own invite code" } }
```

---

# Part 2 — App

## 1. Invite friends (my code and numbers)
**Purpose**: The person's own code and link (made the first time), whether they can invite yet, and their numbers.

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/referrals/me`

**Access Level**: 🔒 Protected

**Success Response JSON Sample**:
```json
{
  "success": true, "httpStatus": "OK", "message": "Invite friends", "action_time": "2026-11-21T10:30:45",
  "data": {
    "code": "K7P2QX4M", "link": "https://nexgate.co/r/K7P2QX4M", "canInvite": true, "programmeOn": true, "rewardDiscount": "5,000 off",
    "numbers": { "signedUp": 8, "bought": 5, "rewarded": 4, "waiting": 3, "notRewarded": 1 }
  }
}
```

| Field | Description |
|-------|-------------|
| `code`, `link` | Always shown (Copy / Share). The code is random and never changes |
| `canInvite` / `whyNot` | false: show `whyNot` ("Complete your first order to start inviting", "Inviting friends is paused right now", "Your invite code has been switched off; contact support") |
| `rewardDiscount` | What one thank-you coupon is worth: "rewards earned 4 × 5,000 off" |
| `numbers` | `signedUp` friends who used the code; `bought` their first order completed (or later); `rewarded`; `waiting` for a first order; `notRewarded` |

---

## 2. My invited friends
**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/referrals/me/friends?page=0&size=20`

**Access Level**: 🔒 Protected

```json
{
  "friends": [
    { "firstName": "Juma", "state": "ORDER_COMPLETED", "joinedAt": "2026-11-21T10:00:00", "rewardOn": "2026-12-05T14:00:00" },
    { "firstName": "Neema", "state": "NOT_REWARDED", "joinedAt": "2026-11-10T09:00:00", "reason": "His first order was at your own shop" },
    { "firstName": "Baraka", "state": "IN_REVIEW", "joinedAt": "2026-11-12T09:00:00", "reason": "Being checked" }
  ],
  "page": 0, "size": 20, "hasNext": false
}
```

| State | Show |
|---|---|
| `SIGNED_UP` | "Waiting for their first order" |
| `ORDER_COMPLETED` | "Bought! Your reward comes on {rewardOn}" |
| `IN_REVIEW` | "Being checked" |
| `REWARDED` | "Reward earned" (the coupon is in My coupons) |
| `NOT_REWARDED` | the `reason` |

---

## 3. The code step after sign-up
**Purpose**: Link the new person to the inviter and give the welcome coupon. Called automatically when the person came
through a link; otherwise an optional "Have an invite code?" step (type or skip).

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/referrals/use-code`

**Access Level**: 🔒 Protected (the new person, signed in)

**Request JSON Sample**:
```json
{ "code": "K7P2QX4M" }
```

| Parameter | Type | Required | Validation |
|---|---|---|---|
| code | string | Yes | the code or the whole link (`https://nexgate.co/r/K7P2QX4M`); any case |

**Success Response JSON Sample**:
```json
{ "success": true, "httpStatus": "OK", "message": "Invite code used", "action_time": "2026-11-21T10:30:45",
  "data": { "inviterFirstName": "Asha", "welcomeCouponId": "7c1e…" } }
```

`welcomeCouponId` null: the referral counts but there is no welcome coupon right now (the welcome pot is empty). Calling
again with the same code is safe. Show "Invited by Asha ✅" and the welcome coupon.

Show this step only **within 7 days of signing up and before the first order**; after that it disappears.

**Errors** (409): `REFERRAL_PAUSED`, `REFERRAL_CODE_NOT_FOUND` (counts as a wrong try), `REFERRAL_TRIES_PAUSED` (5 wrong in 60
minutes), `REFERRAL_OWN_CODE`, `REFERRAL_TOO_LATE` (more than 7 days, or already ordered), `REFERRAL_INVITER_NOT_READY`
(the inviter has no completed order yet), `REFERRAL_SAME_DEVICE` (the inviter's own phone), `REFERRAL_ALREADY_USED` (a
different code was used before).

---

## 4. Check a code
**Purpose**: "Invited by Asha" before using it (the sign-up step).

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/referrals/codes/{code}`

**Access Level**: 🔒 Protected

```json
{ "code": "K7P2QX4M", "valid": true, "inviterFirstName": "Asha" }
```
`valid: false` for a code that doesn't exist or was switched off (counts as a wrong try). `REFERRAL_TRIES_PAUSED` after
5 wrong tries.

---

# Part 3 — Admin

Base: `{base_url}/admin/referrals`. **Who**: staff + super admin, except settings (super admin). Every decision is in
the admin audit log with its reason.

## 5–6. Settings (super admin)
<span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `/admin/referrals/settings` ·
<span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `/admin/referrals/settings` (only the fields sent change; `reason` required)

```json
{
  "programmeOn": true, "minFirstOrder": 20000, "firstOrderDays": 30, "rewardDelayDays": 7, "useCodeDays": 7, "monthlyCap": 10,
  "welcomeValidDays": 14, "thankYouValidDays": 30, "welcomeCouponId": "…", "thankYouCouponId": "…",
  "wrongCodeLimit": 5, "wrongCodePauseMinutes": 60, "updatedAt": "…"
}
```

| Setting | Start with | Meaning |
|---|---|---|
| `programmeOn` | false | the whole programme |
| `minFirstOrder` | 20,000 | items of the friend's first order (before coupons) |
| `firstOrderDays` | 30 | the first order must be placed within this many days of joining |
| `rewardDelayDays` | 7 | days after completion before the reward |
| `useCodeDays` | 7 | the code step is open this long after sign-up |
| `monthlyCap` | 10 | rewards per inviter per calendar month |
| `welcomeValidDays` / `thankYouValidDays` | 14 / 30 | how long each person has to use their coupon |
| `welcomeCouponId` / `thankYouCouponId` | — | two **NexGate** coupons made in coupon admin (their pots pay; top them up there). Suggested: welcome 5,000 off over 20,000, audience new to NexGate, hidden; thank-you 5,000 off over 20,000, hidden |

Errors: `REFERRAL_COUPON_INVALID` (not a NexGate coupon).

## 7. Report
<span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `/admin/referrals/report?from=2026-11-01` (default: this month)
```json
{ "from": "2026-11-01T00:00:00", "codesUsed": 120, "welcomesGiven": 118, "firstOrders": 54, "newCustomers": 54, "rewarded": 40,
  "inReview": 3, "notRewarded": 11,
  "cost": { "welcomeCoupons": 230000, "thankYouCoupons": 160000, "total": 390000, "perNewCustomer": 7222 } }
```
Counts are for friends who joined since `from`; `cost` is what the two coupons have taken off orders so far (net of refunds).

## 8. Waiting for review · 9. Approve · 10. Refuse
<span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `/admin/referrals/review` → oldest first:
```json
[ { "referralId": "…", "inviter": { "accountId": "…", "name": "Asha Mushi" }, "friend": { "accountId": "…", "name": "Juma Ally" },
    "code": "K7P2QX4M", "state": "IN_REVIEW", "reason": "Being checked",
    "warningSigns": ["Tops up from the inviter's own mobile money number"], "welcomeGiven": true,
    "firstOrderId": "…", "firstOrderNumber": "ORD-2026-0042", "firstOrderItems": 21000, "firstOrderShopId": "…",
    "friendSignedUpAt": "…", "orderCompletedAt": "…", "rewardDueAt": "…" } ]
```

<span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `/admin/referrals/{referralId}/approve` · `/refuse` with `{ "reason": "…" }` (required). Approving still checks the
programme, the monthly cap and the pot. Refusing tells the inviter "Not approved after a check". Deciding twice is safe.

Warning signs: same phone as 2+ other friends of the inviter · tops up from the inviter's own mobile-money number · same
top-up number as 2+ other friends · first order at the same shop as 2+ other friends · only order, under 110 % of the
minimum.

## 11. A person
<span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `/admin/referrals/people/{accountId}` → `{ person, code, codeActive, removedReason, invitedBy, invited: [...] }`

## 12–13. Remove · restore
<span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `/admin/referrals/people/{accountId}/remove` · `/restore` with `{ "reason": "Fake celebrity giveaway" }`.
Removing switches the person's code off (it stops working at once; history stays; their pending rewards are not given)
and sends `REFERRAL_CODE_REMOVED`.

---

# Part 4 — Notifications (all to the inviter, except the last)

| Type | When | Text | Opens |
|---|---|---|---|
| `REFERRAL_FRIEND_JOINED` | a friend used the code | 🎉 Juma joined with your code · You get 5,000 off when they complete their first order | Invite friends |
| `REFERRAL_FRIEND_BOUGHT` | the friend's first order completed | Juma bought! · Your reward comes on 5 Dec | Invite friends |
| `REFERRAL_REWARD_EARNED` | reward given (instead of `COUPON_RECEIVED`) | 🎁 You earned 5,000 off for inviting Juma · Use by 4 Jan | My coupons |
| `REFERRAL_REWARD_HELD` | a warning sign (in-app only) | Your reward for inviting Juma is being checked · We'll let you know | Invite friends |
| `REFERRAL_REWARD_MISSED` | no reward (in-app only) | No reward for inviting Juma · {the reason} | Invite friends |
| `REFERRAL_CODE_REMOVED` | removed by an admin | Your invite code has been switched off · {reason}. Contact support if this is a mistake. | Invite friends |
| `REFERRAL_REVIEW_WAITING` | 08:00 daily while rewards wait (admins) | 4 referral rewards are waiting for review · Oldest waiting 2 days | admin review |

The friend's welcome is `COUPON_RECEIVED` with the headline "👋 Welcome! Asha invited you: 5,000 off your first order".
The friend never hears about the inviter's reward. Targets: `INVITE_FRIENDS`, `MY_COUPONS`, `ADMIN_REFERRAL_REVIEW`.

---

# Part 5 — Refusal codes (409)

| Code | When |
|---|---|
| `REFERRAL_PAUSED` | the programme is off |
| `REFERRAL_CODE_NOT_FOUND` | no such code, or it was switched off |
| `REFERRAL_TRIES_PAUSED` | 5 wrong codes: paused |
| `REFERRAL_OWN_CODE` | your own code |
| `REFERRAL_TOO_LATE` | more than 7 days after sign-up, or after the first order |
| `REFERRAL_INVITER_NOT_READY` | the inviter has no completed order yet |
| `REFERRAL_SAME_DEVICE` | used on the inviter's own phone |
| `REFERRAL_ALREADY_USED` | a different code was used before (one inviter, never changed) |
| `REFERRAL_COUPON_INVALID` | admin: the reward must be a NexGate coupon |

---

# Part 6 — Web page and installs (not backend)

- `nexgate.co/r/<code>` (web): store links and "Your invite code: K7P2QX4M · Copy". The page shows the code from the
  link itself; it doesn't call the API (no public code look-up, so codes can't be used to find names).
- Android: pass the code through the Play Install Referrer and call endpoint 3 after sign-up. iPhone: the person copies
  the code into the "Have an invite code?" step.

---

# Part 7 — Screens checklist

| Screen | Calls |
|---|---|
| Me → Invite friends | 1 (code, link, Copy, Share, numbers or why not yet) · friends list 2 |
| After sign-up | link code → 4 then 3 automatically; else "Have an invite code?" (type → 4 → 3, or skip); hide after 7 days or the first order |
| My coupons | the welcome / thank-you coupons (coupon API) |
| Admin → Referrals | settings 5–6, report 7, review 8–10, person 11, remove / restore 12–13 |