# System Offers

# Coupons — API

**Author**: Josh S. Sakweli, Backend Lead Team  
**Last Updated**: 2026-11-28  
**Version**: v1.1 (a coupon can end earlier for one person: live drops and the referral welcome, `endsAt` on the card is your own end; coupons grabbed in a live drop land in My coupons; flash prices and coupons: `NO_COUPON_ON_FLASH`)

**Base URL**: `http://localhost:8765/api/v1` (local) · `https://dev.api.nexgate.co/api/v1` (staging)

**Short Description**: Discounts with conditions. **NexGate coupons** are paid from a NexGate pot (the seller still gets the full price); **shop coupons** are paid by the shop (its order is cheaper); **event coupons** are paid by the event's organiser (the ticket is cheaper). Buyers collect a coupon or type its code, and use it at checkout. Design and the 19 coupon rules: [`COUPON_SPEC.md`](COUPON_SPEC.md); build decisions: [`COUPON_BUILD_PLAN.md`](COUPON_BUILD_PLAN.md) §0a.

**Hints**:

- Every call uses the person's normal login: `Authorization: Bearer <access token>`.
- **The feature has a switch.** While coupons are off, every endpoint here answers **404** and checkouts ignore coupon fields. Hide the coupon screens when `GET /coupons/mine` answers 404.
- Every rule is checked **by the server** when a coupon is collected or typed, when a checkout is made or changed, and **again at payment**. The app only shows what the server says.
- Amounts are TZS. A percent coupon always has a cap. Codes are letters and numbers, any case: `yoyo-10` = `YOYO10`.
- Refusals are **HTTP 409** with `data.code` and `data.reason` (show the reason as it is). Full list in [Part 9](#part-9--refusal-codes).

---

## Contents

- Part 1 — How it works (diagrams, money, examples)
- Part 2 — Buyer: find, collect, type a code, My coupons (1–5)
- Part 3 — Buyer: coupons at checkout (changes to existing endpoints)
- Part 4 — Shop owner: shop coupons (6–16)
- Part 5 — Event organiser: event coupons (17–24)
- Part 6 — NexGate admin: NexGate coupons (25–37)
- Part 7 — Admin support (38–40)
- Part 8 — Notifications
- Part 9 — Refusal codes
- Part 10 — Screens checklist

---

# Part 1 — How it works

## 1.1 Three creators

<table id="bkmrk-nexgate-coupon-shop-"><thead><tr><th></th><th>NexGate coupon</th><th>Shop coupon</th><th>Event coupon</th></tr></thead><tbody><tr><td>Made by</td><td>super admin</td><td>the shop owner, or staff whose role can make price offers</td><td>the event's organiser</td></tr><tr><td>Paid by</td><td>the coupon's **pot** (from `COUPONS-CAMPAIGNS`)</td><td>the shop: its order is cheaper</td><td>the organiser: the ticket is cheaper</td></tr><tr><td>Seller / organiser gets</td><td>**full price**</td><td>price − discount (commission on that)</td><td>price − discount</td></tr><tr><td>Works on</td><td>shop orders; chat offers, group buys, event tickets **where its switches say**</td><td>shop orders only</td><td>paid tickets of that event (its ticket types), not group prices</td></tr><tr><td>Stops when</td><td>the pot is empty, total uses, end date</td><td>spending limit, total uses, end date</td><td>spending limit, total uses **in tickets**, end date, the event starts / is cancelled / completes</td></tr><tr><td>Never on</td><td>instalments, gifts, delivery</td><td>chat offers, group buys, instalments, gifts, delivery</td><td>free or donation tickets, group prices</td></tr></tbody></table>

**At most one NexGate coupon + one coupon per shop** on an order (rule 6).

## 1.2 From a coupon to a discount

```
 NexGate / shop / organiser                     BUYER (Juma)
 ──────────────────────────                     ────────────
 creates coupon, code YOYO10,
 "Show in app" on or off
        │
        ├── shown on:  shop page / product page   ─► GET /coupons/shown?shopId=   ─► [Collect]  POST /coupons/{id}/collect
        │              event page                 ─► GET /coupons/shown-for-event
        ├── a code anywhere (Instagram, sticker,  ─► types it: POST /coupons/redeem { code } (also what nexgate.co/ opens)
        │   influencer, private coupons)
        └── given to people (sorry, thank-you,    ─► lands straight in My coupons (COUPON_RECEIVED)
            referral)

 My coupons  GET /coupons/mine ─► ACTIVE · USED · EXPIRED
        │
        ▼
 checkout:  nexgateCouponId / shopCouponIds / eventCouponId  ─► discount shown, checked again at payment
        │
        ▼
 paid ─► the coupon is USED for this person (even if the order is later refunded: rule 18)

```

A held coupon belongs to that account: a screenshot is useless to anyone else (rule 13).

## 1.3 Where the money goes

**NexGate coupon** (shoes 30,000; NexGate 5,000 off; gift balance 8,000):

```
 ┌───────────────┐   5,000   ┌─────────────────────────┐
 │ coupon's pot  │ ────────► │                         │
 ├───────────────┤   8,000   │  order escrow  30,000   │ ──► seller gets 30,000 − commission
 │ gift balance  │ ────────► │  (the FULL price)       │
 ├───────────────┤  17,000   │                         │
 │ wallet        │ ────────► │                         │
 └───────────────┘           └─────────────────────────┘
 Juma pays 25,000: gift first, then wallet. Payment answer: amountPaid 30,000 · couponDiscount 5,000 · giftPaid 8,000 · walletPaid 17,000

```

**Shop coupon** (Mama Yoyo's 10% off, at most 5,000; shoes 30,000):

```
 checkout total 27,000 (pricing.shopDiscount 3,000) ──► order escrow 27,000 ──► the shop gets 27,000 − commission
 No money moves for the coupon: the order is simply cheaper. The order shows discount 3,000.

```

**Both on one order**: the shop's coupon comes off first, the NexGate coupon is worked out on what is left, then gift balance, then the wallet (rule 17).

```
 shoes 30,000 ─► shop coupon −3,000 = 27,000 ─► NexGate 10% (cap 5,000) on 27,000 = −2,700 ─► Juma pays 24,300

```

**A cart over two shops** shares a NexGate coupon by the size of each shop's covered items (rule 19): dress 30,000 (Mama Yoyo) + earphones 10,000 (Tech Shop), coupon 8,000 → 6,000 + 2,000. A shop coupon stays inside its own shop.

## 1.4 Refunds (rule 18)

<table id="bkmrk-juma%27s-order-back-to"><thead><tr><th>Juma's order</th><th>Back to Juma</th><th>Back to the coupon</th><th>The coupon</th></tr></thead><tbody><tr><td>Whole order cancelled, paid 5,000 coupon + 8,000 gift + 17,000 wallet</td><td>8,000 gift + 17,000 wallet</td><td>5,000 to the pot (to `COUPONS-CAMPAIGNS` if it has ended)</td><td>**stays used**</td></tr><tr><td>One of two items returned (half)</td><td>his half, in the same gift / wallet mix</td><td>half of the coupon to the pot</td><td>stays used</td></tr><tr><td>A shop-coupon order refunded</td><td>what he paid</td><td>the shop's spending limit comes back</td><td>stays used</td></tr></tbody></table>

The refund notice says: *"… · The TZS 5,000 coupon used on this order is not returned"*.

## 1.5 Codes (rule 16)

- Unique among **live** coupons across NexGate (scheduled, running, paused, ran out).
- After a coupon ends its code stays **reserved for its owner for 90 days**, then anyone may take it.
- Letters and numbers, 4–20; any case; spaces and dashes ignored. Shops can't start a code with `NEXGATE`.
- Empty code → made automatically from the shop / event name: `MAMAYO7K2P`.
- A code can't change after the coupon is made. **5 wrong codes → 60-minute pause.**

## 1.6 Editing after someone holds it

<table id="bkmrk-can-change-can%27t-cha"><thead><tr><th>Can change</th><th>Can't change once anyone collected or used it</th></tr></thead><tbody><tr><td>title · a later end date · higher limits (per buyer, total uses, spending limit) · the show switch</td><td>discount · cap · minimum · audience · what it covers · switches · start (once started)</td></tr></tbody></table>

To change those: stop it and make a new one (`COUPON_TERMS_LOCKED`).

---

## Standard Response Format

### Success

```json
{ "success": true, "httpStatus": "OK", "message": "Coupon collected", "action_time": "2026-11-21T10:30:45", "data": { } }

```

### Coded refusal (HTTP 409)

```json
{
  "success": false, "httpStatus": "CONFLICT", "message": "Add 5000 TZS more to use this coupon", "action_time": "2026-11-21T10:30:45",
  "data": { "code": "COUPON_MIN_ORDER", "reason": "Add 5000 TZS more to use this coupon" }
}

```

<table id="bkmrk-status-when-401-miss"><thead><tr><th>Status</th><th>When</th></tr></thead><tbody><tr><td>`401`</td><td>missing or expired token</td></tr><tr><td>`403`</td><td>admin endpoint without the right role</td></tr><tr><td>`404`</td><td>coupons are switched off; or the coupon / shop / event isn't found or isn't yours</td></tr><tr><td>`409`</td><td>a coded refusal (Part 9)</td></tr><tr><td>`422`</td><td>a field fails validation</td></tr></tbody></table>

---

## Shared objects

### CouponCard (what a buyer sees)

```json
{
  "couponId": "7c1e…", "creator": "SHOP",
  "shop": { "shopId": "cfb6…", "name": "Mama Yoyo",
            "logo": { "fileId": "1d2e…", "status": "READY", "thumbUrl": "https://…/thumb.webp", "mimeType": "image/webp" } },
  "title": "10% off for followers", "code": "YOYO10", "kind": "PERCENT", "value": 10, "cap": 5000, "minOrder": 20000,
  "startsAt": "2026-11-21T00:00:00", "endsAt": "2026-11-30T23:59:00", "audience": "FOLLOWERS",
  "covers": { "shops": 0, "categories": 0, "products": 3, "notOnSale": true, "chatOffers": false, "groupBuys": false, "events": false },
  "held": true, "state": "ACTIVE", "usesLeft": 1, "canCollect": false, "whyNot": null
}

```

<table id="bkmrk-field-description-cr"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`creator`</td><td>`NEXGATE`, `SHOP`, `ORGANISER`</td></tr><tr><td>`shop`</td><td>For shop coupons: the shop and its logo (media standard: `ShopLogoPrimaryMedia`); `null` otherwise</td></tr><tr><td>`code`</td><td>Only for coupons shown in the app. A private code is never sent: whoever has it already knows it</td></tr><tr><td>`kind` / `value` / `cap`</td><td>`FIXED`: `value` TZS off. `PERCENT`: `value` %, at most `cap`</td></tr><tr><td>`minOrder`</td><td>Counted on the covered items only</td></tr><tr><td>`audience`</td><td>`EVERYONE`, `NEW_TO_NEXGATE`, `NEW_TO_SHOP`, `FOLLOWERS`, `PAST_BUYERS`, `CHOSEN`</td></tr><tr><td>`covers`</td><td>How many shops / categories / products it is limited to (0 = all), and which other payments a NexGate coupon also works on</td></tr><tr><td>`endsAt`</td><td>When the coupon ends **for you**. Usually the coupon's own end. A coupon you grabbed in a live drop lasts as long as the shop chose (1 hour to 7 days from the grab) and a referral welcome coupon 14 days: then `endsAt` is that earlier time. Never later than the coupon's own end</td></tr><tr><td>`held` / `state` / `usesLeft`</td><td>In My coupons: `ACTIVE`, `USED` (no uses left for you), `EXPIRED` (the coupon ended, or your own `endsAt` passed)</td></tr><tr><td>`canCollect` / `whyNot`</td><td>On shop, product and event pages: show **Collect**, or the reason it isn't for you</td></tr></tbody></table>

Show the discount as "5,000 off" or "10% off, up to 5,000"; "Min. order 20,000"; "Ends 30 Nov".

### CouponResponse (what its creator sees)

```json
{
  "couponId": "7c1e…", "creator": "NEXGATE", "shopId": null, "eventId": null, "title": "Welcome: 5,000 off", "code": "WELCOME5",
  "showInApp": true, "kind": "FIXED", "value": 5000, "cap": null, "minOrder": 20000,
  "startsAt": "2026-11-21T00:00:00", "endsAt": "2026-12-31T23:59:00", "audience": "NEW_TO_NEXGATE", "followedBefore": false,
  "shopIds": [], "categoryIds": [], "productIds": [], "excludedProductIds": [], "notOnSale": false,
  "allowChatOffers": false, "allowGroupBuys": true, "allowEvents": false, "perBuyerLimit": 1, "totalUses": 1000,
  "state": "RUNNING", "termsLocked": true,
  "numbers": { "holders": 340, "orders": 120, "buyers": 118, "discountGiven": 595000, "returned": 5000 },
  "pot": { "accountNumber": "CPOT-7c1e…", "funded": 2000000, "used": 600000, "returned": 5000, "left": 1405000 },
  "limit": null, "createdAt": "2026-11-21T09:00:00", "endedAt": null
}

```

<table id="bkmrk-field-description-st"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`state`</td><td>`SCHEDULED`, `RUNNING`, `PAUSED`, `RAN_OUT` (pot empty, limit or uses reached), `ENDED`, `CANCELLED`</td></tr><tr><td>`termsLocked`</td><td>Someone holds or used it: only the fields in 1.6 can change</td></tr><tr><td>`numbers`</td><td>`orders` = payments that used it (a refund doesn't lower it); `discountGiven` is net of refunds</td></tr><tr><td>`pot`</td><td>NexGate coupons only</td></tr><tr><td>`limit`</td><td>Shop / event coupons: `{ limit, used }` (the spending limit)</td></tr><tr><td>`ticketTypeIds`</td><td>Event coupons (in the request; the response carries the event in `eventId`)</td></tr></tbody></table>

### CouponRequest (create and edit)

<table id="bkmrk-field-type-required-"><thead><tr><th>Field</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>title</td><td>string</td><td>Yes</td><td>Shown to buyers</td><td>max 80</td></tr><tr><td>code</td><td>string</td><td>No</td><td>Empty = made automatically</td><td>4–20 letters/numbers; shops: not `NEXGATE…`; can't change later</td></tr><tr><td>showInApp</td><td>boolean</td><td>No</td><td>Shown on shop / product / event pages (default `true`); off = a private code</td><td></td></tr><tr><td>kind</td><td>string</td><td>Yes</td><td>`FIXED` or `PERCENT`</td><td></td></tr><tr><td>value</td><td>number</td><td>Yes</td><td>TZS off, or the %</td><td>whole numbers; % from 1 to 100</td></tr><tr><td>cap</td><td>number</td><td>PERCENT</td><td>The most it takes off</td><td>required for `PERCENT`</td></tr><tr><td>minOrder</td><td>number</td><td>No</td><td>Minimum of the covered items</td><td>≥ 0</td></tr><tr><td>startsAt</td><td>datetime</td><td>No</td><td>Default now</td><td></td></tr><tr><td>endsAt</td><td>datetime</td><td>Yes</td><td></td><td>after start and in the future; event coupons: by the event start / ticket sales end</td></tr><tr><td>audience</td><td>string</td><td>No</td><td>Default `EVERYONE`</td><td>NexGate: `EVERYONE`, `NEW_TO_NEXGATE`, `CHOSEN`; shop: `EVERYONE`, `NEW_TO_SHOP`, `FOLLOWERS`, `PAST_BUYERS`, `CHOSEN`; event: `EVERYONE`</td></tr><tr><td>followedBefore</td><td>boolean</td><td>No</td><td>Followers only: only people who followed before it started</td><td>only with `FOLLOWERS`</td></tr><tr><td>shopIds</td><td>UUID\[\]</td><td>No</td><td>NexGate: only these shops (empty = all)</td><td>must exist</td></tr><tr><td>categoryIds</td><td>UUID\[\]</td><td>No</td><td>Only these product categories</td><td>must exist</td></tr><tr><td>productIds / excludedProductIds</td><td>UUID\[\]</td><td>No</td><td>Shop: only / never these products</td><td>the shop's own</td></tr><tr><td>notOnSale</td><td>boolean</td><td>No</td><td>Shop: not on items already on sale</td><td></td></tr><tr><td>allowChatOffers / allowGroupBuys / allowEvents</td><td>boolean</td><td>No</td><td>NexGate only: also on chat offers / a member's own group-buy share / paid event tickets</td><td></td></tr><tr><td>perBuyerLimit</td><td>integer</td><td>No</td><td>Uses per person (default 1)</td><td>≥ 1</td></tr><tr><td>totalUses</td><td>integer</td><td>No</td><td>Total uses (event coupons: tickets)</td><td>≥ 1</td></tr><tr><td>spendLimit</td><td>number</td><td>shop / event</td><td>The most given in discounts in total</td><td>required for shops and events; never for NexGate</td></tr><tr><td>budget</td><td>number</td><td>NexGate create</td><td>Moved from `COUPONS-CAMPAIGNS` into the pot</td><td>required on NexGate create</td></tr><tr><td>reason</td><td>string</td><td>No</td><td>For the admin audit log</td><td>max 300</td></tr><tr><td>ticketTypeIds</td><td>UUID\[\]</td><td>No</td><td>Event coupons: only these ticket types</td><td>the event's own</td></tr></tbody></table>

---

# Part 2 — Buyer

## 1. Coupons on a shop or product page

**Purpose**: Public coupons a buyer can collect here: the shop's own and NexGate's that cover it.

**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}/coupons/shown?shopId={shopId}` or `?productId={productId}`

**Access Level**: 🔒 Protected

<table id="bkmrk-parameter-type-requi"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>shopId</td><td>UUID</td><td>one of the two</td><td>Shop page: every coupon for this shop</td></tr><tr><td>productId</td><td>UUID</td><td>one of the two</td><td>Product page: only coupons that cover this product</td></tr></tbody></table>

**Success Response**: `data` = list of [CouponCard](#couponcard-what-a-buyer-sees). Show **Collect** when `canCollect`, else `whyNot`("Only for people who follow this shop"). Running coupons only; ones that ran out are left out.

---

## 2. Coupons on an event page

**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}/coupons/shown-for-event?eventId={eventId}`

**Access Level**: 🔒 Protected

**Success Response**: list of CouponCard: the organiser's own coupons for this event and NexGate coupons that work on event tickets.

---

## 3. Collect

**Purpose**: Put a shown coupon into My coupons.

**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}/coupons/{couponId}/collect`

**Access Level**: 🔒 Protected

No body. Collecting twice is safe (the same card comes back). Private coupons can't be collected (404): they are typed.

**Success Response**: the [CouponCard](#couponcard-what-a-buyer-sees) with `held: true`.

**Errors** (409): `COUPON_ENDED`, `COUPON_NOT_STARTED`, `COUPON_RAN_OUT`, `COUPON_NOT_FOR_YOU` (audience, or you are the shop's own team / the organiser), `COUPON_USED_UP`.

---

## 4. Type a code

**Purpose**: Add a coupon by its code (public or private). The `nexgate.co/` link opens the app and calls this.

**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}/coupons/redeem`

**Access Level**: 🔒 Protected

**Request JSON Sample**:

```json
{ "code": "yoyo-10" }

```

<table id="bkmrk-parameter-type-requi-1"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Validation</th></tr></thead><tbody><tr><td>code</td><td>string</td><td>Yes</td><td>max 40; any case, spaces / dashes ignored</td></tr></tbody></table>

**Success Response**: the CouponCard, `held: true`.

**Errors** (409): `COUPON_CODE_NOT_FOUND` (counts as a wrong try), `COUPON_CODE_TRIES_PAUSED` (5 wrong in 60 minutes), and the errors of endpoint 3.

---

## 5. My coupons

**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}/coupons/mine?state=ACTIVE`

**Access Level**: 🔒 Protected

<table id="bkmrk-parameter-type-requi-2"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Default</th></tr></thead><tbody><tr><td>state</td><td>string</td><td>No</td><td>`ACTIVE`, `USED`, `EXPIRED`</td><td>all</td></tr></tbody></table>

**Success Response**: list of CouponCard (newest first), each with `held: true`, `state`, `usesLeft`.

What is in the list: coupons you collected, typed, were given (by a shop, the referral welcome / thank-you), and coupons you **grabbed in a live or meeting coupon drop** (`POST /live/streams/{streamId}/drops/{dropId}/grab`, live doc; `POST /meetings/{meetingId}/drops/{dropId}/grab`, calls &amp; meetings doc). A grabbed coupon works like any shop coupon at checkout until its `endsAt`; while it can be used, your orders in that shop also count for the live or meeting.

---

# Part 3 — Coupons at checkout (changes to existing endpoints)

Also in `commerce_logistics_changes.md` §16. With coupons off, these fields are ignored and nothing new appears.

## 3.1 Shop checkouts

<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}/e-commerce/checkout-sessions` · <span style="background-color: #fd7e14; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span> `{base_url}/e-commerce/checkout-sessions/{sessionId}`

**New request fields**:

<table id="bkmrk-field-type-on-descri"><thead><tr><th>Field</th><th>Type</th><th>On</th><th>Description</th></tr></thead><tbody><tr><td>nexgateCouponId</td><td>UUID</td><td>create, update</td><td>One NexGate coupon from My coupons</td></tr><tr><td>removeCoupon</td><td>boolean</td><td>update</td><td>`true` takes the NexGate coupon off</td></tr><tr><td>shopCouponIds</td><td>UUID\[\]</td><td>create, update</td><td>At most one per shop (shop orders only: buy now, cart). On update the list **replaces** the shop coupons; `[]` takes them off</td></tr></tbody></table>

```json
{ "sessionType": "REGULAR_CART", "nexgateCouponId": "7c1e…", "shopCouponIds": ["a4b2…"], "useGiftBalance": true }

```

**New response fields**:

```json
{
  "pricing": { "subtotal": 30000, "shopDiscount": 3000, "shippingCost": 0, "tax": 0, "total": 27000, "currency": "TZS" },
  "shopCoupons": [ { "couponId": "a4b2…", "shopId": "cfb6…", "discount": 3000, "byPart": { "cfb6…": 3000 } } ],
  "nexgateCouponId": "7c1e…", "couponDiscount": 2700, "amountToPay": 24300
}

```

<table id="bkmrk-field-description-pr"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`pricing.shopDiscount`</td><td>**New.** Shop coupons, already taken off `pricing.total`</td></tr><tr><td>`shopCoupons`</td><td>**New.** Each shop coupon and its discount per order group</td></tr><tr><td>`nexgateCouponId`, `couponDiscount`</td><td>**New.** The NexGate coupon and its discount (paid by NexGate; `pricing.total` stays the price before it)</td></tr><tr><td>`amountToPay`</td><td>**New.** `pricing.total − couponDiscount`: what gift balance and wallet pay</td></tr></tbody></table>

Where they work: NexGate coupons on buy now and cart; on chat offers and group buys only when that coupon allows it; **never on instalments**. Shop coupons on buy now and cart only.

**Flash prices (from a live or meeting) take no coupon on top:**

- A **shop coupon** is refused with `NO_COUPON_ON_FLASH` when that shop's items in this order include a flash price. Other shops' coupons in the same cart still work.
- A **NexGate coupon** comes off the items without a flash price. It is refused with `NO_COUPON_ON_FLASH` only when **every** item has a flash price.

## 3.2 Event checkout

<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}/e-events/checkout`

<table id="bkmrk-new-field-descriptio"><thead><tr><th>New field</th><th>Description</th></tr></thead><tbody><tr><td>nexgateCouponId</td><td>A NexGate coupon that allows event tickets</td></tr><tr><td>eventCouponId</td><td>The organiser's coupon for this event (paid tickets, not group prices)</td></tr></tbody></table>

The organiser's coupon lowers `pricing.total`; a NexGate coupon is then worked out on what is left.

## 3.3 Balance check and payment

`GET /wallet/checkout-balance-check` gains `couponDiscount` (the NexGate coupon); `giftPart` and `shortfall` count it.

`POST …/process-payment` (shop) and `POST /e-events/checkout/{id}/payment` gain `couponDiscount`:

```json
{ "status": "COMPLETED", "amountPaid": 30000, "couponDiscount": 5000, "giftPaid": 8000, "walletPaid": 17000 }

```

`amountPaid` = the price held for the seller; the buyer paid `giftPaid + walletPaid`.

**At payment every coupon is checked again.** If one no longer applies (ended, ran out, unfollowed the shop, someone took the last use) the payment is refused with its code (`COUPON_RAN_OUT`, `COUPON_ENDED`, `COUPON_NOT_FOR_YOU`, `COUPON_CHANGED`, …) and nothing is taken. Show the reason, take the coupon off (`PATCH` with `removeCoupon` / a new `shopCouponIds`), show the new price.

## 3.4 Order detail and refund notice

`GET /e-commerce/orders/{orderId}` gains:

<table id="bkmrk-field-description-di"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`discount`</td><td>The shop coupon's discount on this order (the shop paid it)</td></tr><tr><td>`coupon`</td><td>The NexGate coupon: `{ couponId, code, title, discount, returnedToCoupon }`. Show "Coupon WELCOME5 −5,000"; after a refund "(not returned)"</td></tr></tbody></table>

`ESCROW_REFUNDED` data: `refund.body` ends with *"· The TZS 5,000 coupon used on this order is not returned"*; `refund.coupon` carries the amount.

---

# Part 4 — Shop owner: shop coupons

Base: `{base_url}/shops/{shopId}/coupons`. **Who**: the shop owner, or staff whose shop role has **price offers**. A coupon of another shop answers 404.

## 6. Create

<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}/shops/{shopId}/coupons`

```json
{
  "title": "Followers: 10% off", "code": "YOYO10", "showInApp": true, "kind": "PERCENT", "value": 10, "cap": 5000, "minOrder": 20000,
  "endsAt": "2026-11-30T23:59:00", "audience": "FOLLOWERS", "followedBefore": false,
  "productIds": [], "categoryIds": [], "excludedProductIds": ["d1c0…"], "notOnSale": true,
  "perBuyerLimit": 1, "totalUses": 100, "spendLimit": 200000
}

```

Body: [CouponRequest](#couponrequest-create-and-edit) (`spendLimit` required, no `budget`, no `shopIds` or switches). **Response**: [CouponResponse](#couponresponse-what-its-creator-sees) with `limit`. A followers-only coupon that starts now tells the shop's followers (once a day per shop).

**Errors**: `NOT_YOUR_SHOP`, `COUPON_CODE_TAKEN`, `COUPON_CODE_RESERVED`, `COUPON_CODE_INVALID`, `COUPON_CAP_REQUIRED`, `COUPON_VALUE_INVALID`, `COUPON_DATES_INVALID`, `COUPON_AUDIENCE_NOT_ALLOWED`, `COUPON_FIELD_NOT_ALLOWED`, `COUPON_LIMIT_REQUIRED`, `PRODUCT_NOT_IN_SHOP`, `CATEGORY_NOT_FOUND`.

## 7. My coupons (list) · 8. Side by side

<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}/shops/{shopId}/coupons` → list of CouponResponse.

<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}/shops/{shopId}/coupons/compare`

```json
[ { "couponId": "…", "code": "INSTA10", "title": "Instagram 10%", "state": "RUNNING", "orders": 40, "newCustomers": 25,
    "discountGiven": 120000, "salesCompleted": 1200000 },
  { "couponId": "…", "code": "RADIO10", "title": "Radio 10%", "state": "ENDED", "orders": 3, "newCustomers": 1,
    "discountGiven": 9000, "salesCompleted": 90000 } ]

```

## 9. One coupon

<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}/shops/{shopId}/coupons/{couponId}` → CouponResponse.

## 10. Report (the coupon's impact)

<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}/shops/{shopId}/coupons/{couponId}/report`

```json
{
  "couponId": "…", "code": "YOYO10", "title": "Followers: 10% off", "state": "RUNNING",
  "people": { "newCustomers": 31, "returning": 13, "newFollowers": 85 },
  "money": { "salesCompleted": 1320000, "discountGiven": 132000, "costPerOrder": 3000, "averageOrder": 30000, "usualOrder": 22000 },
  "funnel": { "holders": 120, "orders": 48, "completed": 44, "cancelled": 4, "takeUpPercent": 40.0 },
  "perDay": [ { "day": "2026-11-21", "orders": 9, "discount": 27000 } ],
  "topProducts": [ { "productName": "Red dress", "quantity": 18 } ],
  "limits": { "spendLimit": 200000, "spent": 132000, "totalUses": 100, "used": 48 }
}

```

<table id="bkmrk-section-meaning-peop"><thead><tr><th>Section</th><th>Meaning</th></tr></thead><tbody><tr><td>`people`</td><td>first: **new customers** (no earlier order at this shop) vs returning; new followers while it ran</td></tr><tr><td>`money`</td><td>completed orders' items sales; discount net of refunds; per order; **average order with the coupon vs the shop's usual** (its average completed order in the 90 days before)</td></tr><tr><td>`funnel`</td><td>holders → orders → completed / cancelled; take-up = orders ÷ holders</td></tr><tr><td>`perDay`, `topProducts`, `limits`</td><td>for the small chart, best sellers, and how much of the limit is used</td></tr></tbody></table>

## 11. Its orders

<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}/shops/{shopId}/coupons/{couponId}/orders?page=1&size=20`

```json
{ "content": [ { "orderId": "…", "orderNumber": "ORD-2026-0042", "shopId": "…", "shopName": "Mama Yoyo", "orderItems": 30000,
                 "discount": 3000, "status": "COMPLETED", "newCustomer": true, "orderedAt": "2026-11-21T11:02:10" } ],
  "totalElements": 48, "number": 0, "size": 20 }

```

## 12. Edit

<span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/shops/{shopId}/coupons/{couponId}` — the whole CouponRequest. Once held, only what 1.6 allows (`COUPON_TERMS_LOCKED`); the code never changes (`COUPON_CODE_FIXED`); an ended coupon can't change (`COUPON_CLOSED`).

## 13–15. Pause · resume · stop

<span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/{couponId}/pause` · `…/resume` · `…/stop` (stop: optional `{ "reason": "…" }`). Calling twice is safe. A stopped coupon is final: people who hold it see it as expired; its code is reserved for the shop for 90 days.

## 16. Give to people

<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}/shops/{shopId}/coupons/{couponId}/give`

```json
{ "accountIds": ["3213…", "77c1…"], "reason": "Sorry for the late delivery" }

```

```json
{ "given": 1, "alreadyHeld": 0, "notFound": [], "notAllowed": ["77c1…"] }

```

A shop gives only to **its followers, past buyers (a completed order) or people it chats with**; others come back in `notAllowed`. Each person gets `COUPON_RECEIVED`.

---

# Part 5 — Event organiser: event coupons

Base: `{base_url}/events/{eventId}/coupons`. **Who**: the event's organiser.

<table id="bkmrk-%23-method-endpoint-17"><thead><tr><th>\#</th><th>Method</th><th>Endpoint</th><th></th></tr></thead><tbody><tr><td>17</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span></td><td>`…/coupons`</td><td>create</td></tr><tr><td>18</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`…/coupons`</td><td>list</td></tr><tr><td>19</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`…/coupons/{couponId}`</td><td>one</td></tr><tr><td>20</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`…/coupons/{couponId}/report`</td><td>uses and discount</td></tr><tr><td>21</td><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span></td><td>`…/coupons/{couponId}`</td><td>edit</td></tr><tr><td>22–24</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span></td><td>`…/{couponId}/pause` · `/resume` · `/stop`</td><td></td></tr></tbody></table>

```json
{ "title": "Early bird: 2,000 off", "code": "EARLYBIRD", "kind": "FIXED", "value": 2000, "endsAt": "2026-12-01T18:00:00",
  "ticketTypeIds": ["4f19…"], "totalUses": 50, "spendLimit": 100000 }

```

Rules:

- **One event**; optionally chosen ticket types (`TICKET_NOT_IN_EVENT`).
- It **ends by the time the event starts or its ticket sales end** (`COUPON_DATES_INVALID`), and ends by itself when the event starts, is cancelled or completes.
- Paid tickets only, never group ticket prices; **`totalUses` counts tickets** ("first 50 tickets").
- Audience: everyone. The organiser can't use their own coupon. Errors: `NOT_YOUR_EVENT`, `EVENT_CLOSED`, plus Part 4's.

---

# Part 6 — NexGate admin: NexGate coupons

Base: `{base_url}/admin/coupons`. **Who**: super admin. Every action is in the admin audit log.

Money first: move money `PLATFORM-REVENUE → COUPONS-CAMPAIGNS` with the existing finance transfer (`POST /admin/finance/system-accounts/transfer`, `toAccount: "COUPONS-CAMPAIGNS"`). Each coupon's budget then moves into its own pot.

<table id="bkmrk-%23-method-endpoint-bo"><thead><tr><th>\#</th><th>Method</th><th>Endpoint</th><th>Body / answer</th></tr></thead><tbody><tr><td>25</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span></td><td>`/admin/coupons`</td><td>CouponRequest with `budget` → CouponResponse (`COUPON_BUDGET_REQUIRED`, `COUPON_BUDGET_LOW`)</td></tr><tr><td>26</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`/admin/coupons`</td><td>all NexGate coupons</td></tr><tr><td>27</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`/admin/coupons/compare`</td><td>side by side</td></tr><tr><td>28</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`/admin/coupons/{couponId}`</td><td>one</td></tr><tr><td>29</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`/admin/coupons/{couponId}/report`</td><td>as 10, plus `pot` and `byShop: [ { shopId, shopName, orders, discount } ]`</td></tr><tr><td>30</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`/admin/coupons/{couponId}/orders`</td><td>as 11</td></tr><tr><td>31</td><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span></td><td>`/admin/coupons/{couponId}`</td><td>edit (as 12)</td></tr><tr><td>32–34</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span></td><td>`…/{couponId}/pause` · `/resume` · `/stop`</td><td>optional `{ "reason" }`; stopping sends the pot's leftover back to `COUPONS-CAMPAIGNS`</td></tr><tr><td>35</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span></td><td>`…/{couponId}/top-up`</td><td>`{ "amount": 500000, "reason": "…" }`</td></tr><tr><td>36</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span></td><td>`…/{couponId}/give`</td><td>`{ "accountIds": [...], "reason" }` → `{ given, alreadyHeld, notFound, notAllowed }`; NexGate may give to anyone</td></tr></tbody></table>

A NexGate coupon's pot under 10 % of what was funded tells the admins (`COUPON_POT_LOW`, once a day). Refunds after the coupon ended land in its pot and are moved on to the budget by the timer.

---

# Part 7 — Admin support

**Who**: staff admin and super admin.

<table id="bkmrk-%23-method-endpoint-38"><thead><tr><th>\#</th><th>Method</th><th>Endpoint</th><th></th></tr></thead><tbody><tr><td>38</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`/admin/coupons/search?code=YOYO10`</td><td>every coupon that ever had this code (any creator), newest first</td></tr><tr><td>39</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`/admin/coupons/people/{accountId}`</td><td>`{ accountId, coupons: [CouponCard] }`</td></tr><tr><td>40</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span></td><td>`/admin/coupons/{couponId}/stop-shop-coupon`</td><td>`{ "reason": "Misleading: price raised first" }` (required) → stops a shop's or organiser's coupon; `COUPON_NEXGATE_OWN` for NexGate's own</td></tr></tbody></table>

Admins can **never edit a shop's coupon or move a shop's money**.

---

# Part 8 — Notifications

<table id="bkmrk-type-to-when-text-op"><thead><tr><th>Type</th><th>To</th><th>When</th><th>Text</th><th>Opens</th></tr></thead><tbody><tr><td>`COUPON_RECEIVED`</td><td>buyer</td><td>given a coupon</td><td>🎟️ Mama Yoyo gave you 5,000 off · Use by 30 Dec</td><td>My coupons (`MY_COUPONS`)</td></tr><tr><td>`COUPON_EXPIRING`</td><td>buyer</td><td>2 days before a held, unused coupon ends (once)</td><td>Your 5,000 off from Mama Yoyo ends in 2 days</td><td>My coupons</td></tr><tr><td>`COUPON_NEW_FOR_FOLLOWERS`</td><td>followers</td><td>a followers-only shop coupon starts (max one a day per shop)</td><td>Mama Yoyo has 10% off for followers · Until 30 Nov</td><td>the shop (`SHOP`, `shopId`; `couponId` in data)</td></tr><tr><td>`COUPON_RAN_OUT`</td><td>shop owner</td><td>spending limit or total uses reached</td><td>YOYO10 has stopped · Spending limit reached. Raise it to restart.</td><td>the coupon (`COUPON`)</td></tr><tr><td>`COUPON_ENDED`</td><td>shop owner</td><td>the end date came</td><td>YOYO10 ended · 40 uses · TZS 120,000 discount · TZS 600,000 in sales</td><td>the coupon</td></tr><tr><td>`COUPON_POT_LOW`</td><td>admins</td><td>a NexGate pot under 10 % (once a day)</td><td>WELCOME5 pot: TZS 180,000 left of TZS 2,000,000</td><td>admin coupon (`ADMIN_COUPON`)</td></tr></tbody></table>

Data for apps that draw their own text: `couponId`, `actor.name`, `shop.name`, `coupon.code`, `coupon.discount`("5,000 off" / "10% off"), `coupon.endsOn`, and per type `coupon.stopReason`, `coupon.uses`, `coupon.discountTotal`, `coupon.sales`, `coupon.potLeft`, `coupon.potTotal`.

---

# Part 9 — Refusal codes

All **HTTP 409**; show `data.reason`.

<table id="bkmrk-code-when-coupon_not"><thead><tr><th>Code</th><th>When</th></tr></thead><tbody><tr><td>`COUPON_NOT_FOUND`</td><td>no such coupon (for this kind of use)</td></tr><tr><td>`COUPON_NOT_HELD`</td><td>collect or type it first</td></tr><tr><td>`NO_COUPON_ON_FLASH`</td><td>"A flash price takes no coupon on top": a shop coupon on a shop whose items have a flash price, or a NexGate coupon when every item has one (3.1)</td></tr><tr><td>`COUPON_NOT_STARTED` / `COUPON_ENDED` / `COUPON_CLOSED`</td><td>not yet / no longer running, or your own `endsAt` passed (live drop, referral welcome) / ended (can't be changed)</td></tr><tr><td>`COUPON_RAN_OUT`</td><td>pot empty, spending limit or total uses reached (event: "Only N tickets are left")</td></tr><tr><td>`COUPON_USED_UP`</td><td>you have used it as many times as allowed</td></tr><tr><td>`COUPON_NOT_FOR_YOU`</td><td>audience (new, followers, past buyers, chosen) or the shop's own team / the organiser</td></tr><tr><td>`COUPON_NOT_FOR_THIS`</td><td>not on this payment (chat offer, group buy, instalment, ticket type, free ticket, another event) or covers nothing here</td></tr><tr><td>`COUPON_MIN_ORDER`</td><td>"Add X TZS more to use this coupon"</td></tr><tr><td>`COUPON_ONE_PER_SHOP`</td><td>two coupons of the same shop</td></tr><tr><td>`COUPON_SELLER_LIMIT`</td><td>the shop's coupon doesn't fit with its delivery offer on this order</td></tr><tr><td>`COUPON_CHANGED`</td><td>a shop / organiser coupon changed between checkout and payment</td></tr><tr><td>`COUPON_CODE_NOT_FOUND` / `COUPON_CODE_TRIES_PAUSED`</td><td>wrong code / 5 wrong codes: paused</td></tr><tr><td>`COUPON_CODE_TAKEN` / `COUPON_CODE_RESERVED` / `COUPON_CODE_INVALID` / `COUPON_CODE_FIXED`</td><td>creating: code in use or reserved / `NEXGATE…` / format / can't change</td></tr><tr><td>`COUPON_TERMS_LOCKED`</td><td>editing what can't change once held</td></tr><tr><td>`COUPON_CAP_REQUIRED` / `COUPON_VALUE_INVALID` / `COUPON_DATES_INVALID` / `COUPON_AUDIENCE_NOT_ALLOWED` / `COUPON_FIELD_NOT_ALLOWED` / `COUPON_LIMIT_REQUIRED`</td><td>creating / editing</td></tr><tr><td>`COUPON_BUDGET_REQUIRED` / `COUPON_BUDGET_LOW` / `COUPON_HAS_NO_POT`</td><td>NexGate money</td></tr><tr><td>`COUPON_GIVE_NOT_ALLOWED` / `COUPON_NEXGATE_OWN`</td><td>giving event coupons / admin stop on a NexGate coupon</td></tr><tr><td>`NOT_YOUR_SHOP` / `NOT_YOUR_EVENT` / `ADMIN_ONLY`</td><td>who may manage</td></tr><tr><td>`SHOP_NOT_FOUND` / `CATEGORY_NOT_FOUND` / `PRODUCT_NOT_IN_SHOP` / `TICKET_NOT_IN_EVENT` / `EVENT_CLOSED` / `EVENT_REQUIRED` / `SHOP_REQUIRED` / `COUPON_SHOP_REQUIRED`</td><td>lists and scope</td></tr></tbody></table>

---

# Part 10 — Screens checklist

<table id="bkmrk-screen-calls-shop-pa"><thead><tr><th>Screen</th><th>Calls</th></tr></thead><tbody><tr><td>Shop page / product page</td><td>coupons strip (1) with **Collect** (3)</td></tr><tr><td>Event page</td><td>coupons strip (2) with **Collect**</td></tr><tr><td>Me → My coupons</td><td>tabs Active / Used / Expired (5); **Add a code** (4)</td></tr><tr><td>`nexgate.co/` link</td><td>open the app → (4) with the code</td></tr><tr><td>Checkout</td><td>"Use a coupon": My coupons that fit; send `nexgateCouponId` / `shopCouponIds` / `eventCouponId`; show `shopDiscount`, `couponDiscount`, `amountToPay`; on a coupon refusal at payment, take it off and show the new price</td></tr><tr><td>Receipt / order detail</td><td>`couponDiscount`, `giftPaid`, `walletPaid`; order `discount` and `coupon`</td></tr><tr><td>Shop dashboard → Coupons</td><td>list (7), side by side (8), create / edit (6, 12), report (10), orders (11), pause / resume / stop (13–15), give (16)</td></tr><tr><td>Event dashboard → Coupons</td><td>17–24</td></tr><tr><td>Admin → Coupons</td><td>25–36; finance transfer to `COUPONS-CAMPAIGNS` first</td></tr><tr><td>Admin → Support</td><td>38–40</td></tr></tbody></table>

# Gift — API

**Author**: Josh S. Sakweli, Backend Lead Team  
**Last Updated**: 2026-11-28  
**Version**: v1.2 (moment gifts in meetings and calls: places `MEETING` and `CALL`; an item's `places` optional, empty = every place; v1.1: Part 13 moment gifts, spec v6)

**Base URL**: `http://localhost:8765/api/v1` (local) · `https://dev.api.nexgate.co/api/v1` (staging)

**Short Description**: Everything the NexGate app (Android, iOS, web) and the admin panel need for gifts. A person buys a gift from their wallet: **for someone** (a private gift, by account or phone number), **as codes** (anyone who types the code gets it) or **for themselves** (loads their own gift balance). The receiver claims it into their **gift balance**, which pays first at every checkout. Design and rules: [`GIFT_SYSTEM_SPEC.md`](GIFT_SYSTEM_SPEC.md).

**Hints**:

- Every call uses the person's normal login: `Authorization: Bearer <access token>`.
- **The feature has a switch.** While gifts are off, every endpoint here answers **404**, payments take no gift part and the extra fields on existing responses are missing. Hide the Gift entries when `GET /gifts/designs` answers 404.
- A person is always an **`accountId`**. Find people with the existing user search, then send their `accountId`.
- Amounts are **TZS, whole shillings** (`20000`, not `20000.50`). Dates are server local time, ISO 8601 without zone (`2026-11-21T10:30:45`).
- Rules are checked by the server **when the checkout opens and again when it is paid**. The app may grey things out from `GET /gifts/designs`, but the server's answer wins.
- Refusals are **HTTP 409** with `data.code` (branch on it) and `data.reason` (written for people: show it as it is). The full list is in [Part 11](#part-11--refusal-codes).

---

## Contents

- Part 1 — How it works (flows, diagrams, money)
- Part 2 — Designs (1)
- Part 3 — Buying a gift (2–5)
- Part 4 — My gifts: lists and one gift (6–9)
- Part 5 — Opening, declining, cancelling, redeeming (10–14)
- Part 6 — Gift balance (15–16)
- Part 7 — Changes to existing endpoints (checkout, payment, refunds)
- Part 8 — The gift card in a chat
- Part 9 — Notifications
- Part 10 — Admin (17–29)
- Part 10a — Who can send me gifts (30–32)
- Part 11 — Refusal codes
- Part 12 — Screens checklist
- **Part 13 — Moment gifts (33–41), new in v1.1**

---

# Part 1 — How it works

## 1.1 Three kinds of gift

<table id="bkmrk-kind-who-gets-it-how"><thead><tr><th>Kind</th><th>Who gets it</th><th>How it is opened</th><th>Starts as</th></tr></thead><tbody><tr><td>`PRIVATE`</td><td>one person, chosen by account or phone number</td><td>the receiver taps **Claim** (or **Decline**)</td><td>`SENT`</td></tr><tr><td>`PUBLIC`</td><td>whoever types the code first (one code = one person)</td><td>anyone: **Redeem a code**</td><td>`ACTIVE`</td></tr><tr><td>`SELF`</td><td>the buyer</td><td>nothing to do: straight into their gift balance</td><td>`CLAIMED`</td></tr></tbody></table>

A gift is a **card until it is opened, money after**. While it waits, the money sits in NexGate's gift account, not with the buyer and not with the receiver. Opened, it becomes **gift balance**: it pays for things on NexGate, it can't be withdrawn or sent on.

## 1.2 Buying a gift for someone (Asha → Juma)

```
 ASHA (NexGate app)                              SERVER                                  JUMA (NexGate app)
 ──────────────────                              ──────                                  ──────────────────
 Gift ─► GET /gifts/designs ───────────────────► designs, amounts, today's limits
 picks "Birthday", TZS 20,000, Juma, message
 POST /gifts/checkout-sessions ────────────────► checks every rule, holds nothing yet
   { kind: PRIVATE, designId, amount: 20000,      session PENDING_PAYMENT (15 minutes)
     recipientId: Juma, message }
 shows: total, wallet balance, "Pay"
 POST /gifts/checkout-sessions/{id}/process-payment
                                               ► checks every rule again
                                                 one ledger entry: Asha's wallet → gift account
                                                 card SENT, expires in 14 days
 "Your gift to Juma is on its way" ◄──────────── session COMPLETED + cards[ ]
 bell GIFT_PURCHASED (+ email receipt)           bell + push GIFT_RECEIVED ────────────► "🎁 Asha sent you a gift
                                                                                          TZS 20,000 · claim by 5 Dec"
                                                 ◄────────────────────────────────────── POST /gifts/{id}/claim
                                                 gift account → Juma's gift balance
 bell + push GIFT_CLAIMED ◄───────────────────── card CLAIMED                            gift balance TZS 20,000
 "🎉 Juma claimed your gift"

```

- Sent **from a one-to-one chat** with Juma (`conversationId`): the gift also appears in that chat as a card ([Part 8](#part-8--the-gift-card-in-a-chat)).
- Juma may **Decline** instead: the money goes straight back to Asha's wallet and she gets `GIFT_REJECTED`.

## 1.3 A gift to someone not on NexGate yet (by phone number)

```
 ASHA                                   SERVER                                   0754 123 456 (not on NexGate)
 ────                                   ──────                                   ─────────────────────────────
 POST /gifts/checkout-sessions
   { kind: PRIVATE, recipientPhone:
     "0754123456", amount: 20000 } ───► number has no account → card keeps the number
 pays ────────────────────────────────► card SENT, recipient = null
                                        SMS GIFT_INVITE_SMS ───────────────────► "Asha sent you a TZS 20,000 gift
                                                                                   on NexGate. Get the app and sign up
                                                                                   with this number to claim it."
                                                                                 installs, signs up with THAT number
                                        ◄─────────────────────────────────────── opens Gifts (GET /gifts/received)
                                        card linked to the new account
                                        (only the account with that exact number)
                                                                                 Claim → gift balance

```

- If the number **already** belongs to someone on NexGate, it goes to that person (1.2), but **Asha is never told whose number it is**: the checkout, her Sent list and her notices show only `+255•••••3456` until the person **claims** (then "Juma claimed your gift"). Declined or returned: the name is never shown. Numbers can't be used to look people up.
- Asha sees the number masked: `+255•••••3456`.
- One day before it would come back, the number gets a reminder SMS.

## 1.4 Gift codes (PUBLIC)

```
 ASHA buys 3 codes of TZS 10,000
 POST /gifts/checkout-sessions { kind: PUBLIC, amount: 10000, quantity: 3 }
 POST …/process-payment ─► cards[ {code: "NXG-7K4Q-M2PX-9DFT"}, {code: …}, {code: …} ]   ◄─ the ONLY list with full codes
                            shows Copy / Share for each

 later: My codes ─► GET /gifts/codes ─► "…9DFT  ACTIVE"   (codeLast4 only)
        tap Show ─► GET /gifts/{id}/code ─► full code again (only while ACTIVE)

 ANYONE (even Asha herself) ─► POST /gifts/redeem { code: "nxg 7k4q m2px 9dft" } ─► gift balance + TZS 10,000
 ASHA: bell + push GIFT_CODE_REDEEMED "Your gift code …9DFT was redeemed"  (never says who)

```

- A code is `NXG-` + 12 letters/digits. People may type it in any case, with or without `NXG`, spaces or dashes.
- The letters `0 O 1 I L U` are never used, so a code survives being read aloud.
- **5 wrong codes** → that person is paused for **60 minutes** (`CODE_TRIES_PAUSED`).

## 1.5 Buying for yourself (SELF)

```
 POST /gifts/checkout-sessions { kind: SELF, amount: 50000 } ─► POST …/process-payment
 wallet − 50,000 ─► gift balance + 50,000      card CLAIMED at once      bell GIFT_BALANCE_LOADED

```

Useful to set money aside for shopping. It can't be cancelled or moved back to the wallet.

## 1.6 The life of one gift card

```
                              PRIVATE                                             PUBLIC (code)
                         ┌────────────────┐                                  ┌────────────────┐
           paid ───────► │      SENT      │                       paid ────► │     ACTIVE     │
                         └───────┬────────┘                                  └───────┬────────┘
     ┌──────────────┬────────────┼──────────────┬───────────┐          ┌─────────────┼──────────────┬───────────┐
     ▼              ▼            ▼              ▼           ▼          ▼             ▼              ▼           ▼
 ┌────────┐   ┌──────────┐ ┌───────────┐ ┌──────────┐ ┌────────┐  ┌──────────┐ ┌───────────┐ ┌──────────┐ ┌────────┐
 │CLAIMED │   │ REJECTED │ │ CANCELLED │ │ RETURNED │ │ FROZEN │  │ REDEEMED │ │ CANCELLED │ │ RETURNED │ │ FROZEN │
 └────────┘   └──────────┘ └───────────┘ └──────────┘ └───┬────┘  └──────────┘ └───────────┘ └──────────┘ └───┬────┘
 receiver     receiver     buyer, within  14 days, not    │ support    anyone      buyer, within  14 days,     │
 claims       declines     24 h           opened          │            types it    24 h           not used     │
                                                          ▼                                                    ▼
                                           support: unfreeze (back to SENT / ACTIVE) or return to the buyer (RETURNED)

 SELF: created CLAIMED, nothing else happens to it.
 Money:  CLAIMED / REDEEMED → receiver's gift balance.  REJECTED / CANCELLED / RETURNED → buyer's WALLET (never gift).

```

`SENT` and `ACTIVE` are "waiting". Everything else is final, except `FROZEN`, which only support can end.

## 1.7 The 14 days of a waiting gift

```
 day 0 ── bought ───────────────────────────────────────────────────────────────────────────────► day 14
 │◄── 24 h: buyer can Cancel ──►│
                                                  day 11            day 12              day 13       day 14
                                                  receiver:         buyer:              receiver:    not opened →
                                                  GIFT_CLAIM_       GIFT_RETURNING_     GIFT_CLAIM_  back to buyer's wallet
                                                  REMINDER          SOON (bell only)    REMINDER     GIFT_RETURNED
                                                  (3 days left)                         (1 day left;
                                                                                         SMS if not on NexGate)

```

The reminders and the return run every hour, so they arrive within the hour of these times. A frozen gift is skipped: it never comes back on its own (support decides, [Part 10](#part-10--admin)).

## 1.8 Where the money goes

```
                       ┌──────────────────────────────── refunds of a shop order: fair share ───────────────────────┐
                       │                                                                                            │
 ┌───────────┐  buy   ┌┴───────────────────┐ claim / redeem ┌─────────────────┐  pay an order   ┌──────────────────┐ │
 │ Asha's    │ ─────► │ NexGate gift       │ ─────────────► │ Juma's gift     │ ──────────────► │ order escrow     │─┘
 │ WALLET    │        │ account (waiting)  │                │ balance         │  (pays first)   │ (as for any      │
 │           │ ◄───── │                    │                └─────────────────┘                 │  payment)        │
 └─────┬─────┘ decline│                    │                                                    └──────────────────┘
       │     cancel   └────────────────────┘                                                     ▲
       │     14 days                                                                             │ the rest
       │ SELF: straight into Asha's own gift balance                                             │
       └───────────────────────────────────────────── Juma's WALLET ─────────────────────────────┘

```

- Every move is one double-entry ledger entry, so nothing can be in two places or lost.
- Admin's report checks every day that the gift account holds exactly the waiting cards ([29](#29-report)).

## 1.9 Paying a shop order with gift balance

Juma has **TZS 20,000** gift balance and **TZS 50,000** in his wallet. He buys shoes for **TZS 35,000**.

```
 POST /e-commerce/checkout-sessions { …, useGiftBalance: true (or left out) }
 GET  /wallet/checkout-balance-check → giftBalance 20000, giftPart 20000, walletBalance 50000, shortfall 0
 POST /e-commerce/checkout-sessions/{id}/process-payment
      → amountPaid 35000, giftPaid 20000, walletPaid 15000
 after: gift balance 0, wallet 35,000

```

<table id="bkmrk-juma%27s-choice-gift-p"><thead><tr><th>Juma's choice</th><th>Gift pays</th><th>Wallet pays</th></tr></thead><tbody><tr><td>`useGiftBalance` left out or `true`</td><td>20,000</td><td>15,000</td></tr><tr><td>`useGiftBalance: false`</td><td>0</td><td>35,000</td></tr><tr><td>Instalment checkout (any value)</td><td>0</td><td>all of it (instalments never use gift)</td></tr></tbody></table>

**Refund**: the order is cancelled. Juma gets back **TZS 20,000 to his gift balance** and **TZS 15,000 to his wallet**, the same mix he paid with. A part refund is split in the same proportion (fair share). The `ESCROW_REFUNDED` notice says it: "TZS 35,000 refunded · From order ORD-… · TZS 20,000 to your gift balance · TZS 15,000 to your wallet".

Gift balance pays at: buy now, cart, group buys, chat offers, event tickets. It does **not** pay for: instalments, another gift, wallet top-ups, withdrawals, transfers.

---

## Standard Response Format

### Success Response Structure

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Gift claimed",
  "action_time": "2026-11-21T10:30:45",
  "data": { }
}

```

### Coded refusal (HTTP 409)

```json
{
  "success": false,
  "httpStatus": "CONFLICT",
  "message": "Smallest gift is 1000 TZS",
  "action_time": "2026-11-21T10:30:45",
  "data": { "code": "GIFT_TOO_SMALL", "reason": "Smallest gift is 1000 TZS" }
}

```

### Standard Response Fields

<table id="bkmrk-field-type-descripti"><thead><tr><th>Field</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>`success`</td><td>boolean</td><td>`true` for success, `false` for errors</td></tr><tr><td>`httpStatus`</td><td>string</td><td>HTTP status name (`OK`, `CONFLICT`, `NOT_FOUND`, …)</td></tr><tr><td>`message`</td><td>string</td><td>What happened, for people</td></tr><tr><td>`action_time`</td><td>string</td><td>When the response was made</td></tr><tr><td>`data`</td><td>object</td><td>The answer; for a refusal `{ code, reason }`</td></tr></tbody></table>

### Other errors

<table id="bkmrk-status-when-401-unau"><thead><tr><th>Status</th><th>When</th></tr></thead><tbody><tr><td>`401 UNAUTHORIZED`</td><td>missing or expired token</td></tr><tr><td>`403 FORBIDDEN`</td><td>admin endpoint without the right admin role</td></tr><tr><td>`404 NOT_FOUND`</td><td>gifts are switched off; or the gift / session doesn't exist **or isn't yours** (the same answer, on purpose)</td></tr><tr><td>`409 CONFLICT`</td><td>a coded refusal (Part 11)</td></tr><tr><td>`422 UNPROCESSABLE_ENTITY`</td><td>a field fails validation (`data` names the fields)</td></tr></tbody></table>

### HTTP Method Badges

<span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> read · <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> create / act · <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> replace · <span style="background-color: #fd7e14; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span> change a part

---

## Shared objects

These appear in many answers. Each endpoint below refers to them.

### GiftCard

```json
{
  "id": "9f1c2d3e-4b5a-6789-8abc-def012345678",
  "kind": "PRIVATE",
  "status": "SENT",
  "amount": 20000,
  "message": "Happy birthday Juma!",
  "designId": "3a7b…",
  "designName": "Birthday",
  "designImage": {
    "fileId": "8c2e…", "status": "READY", "mimeType": "image/webp",
    "variants": { "thumb": "https://files.nexgate.co/…/thumb.webp", "medium": "https://files.nexgate.co/…/medium.webp" }
  },
  "from": { "accountId": "304e…", "name": "Asha Mushi",
            "userProfileMedia": { "fileId": "1d2e…", "status": "COMPLETED", "thumbUrl": "https://…/thumb.jpg", "mimeType": "image/jpeg" } },
  "to":   { "accountId": "3213…", "name": "Juma Ally", "userProfileMedia": null },
  "recipientPhone": null,
  "code": null,
  "codeLast4": null,
  "createdAt": "2026-11-21T10:30:45",
  "expiresAt": "2026-12-05T10:30:45",
  "openedAt": null,
  "closedAt": null,
  "cancelUntil": "2026-11-22T10:30:45"
}

```

<table id="bkmrk-field-description-id"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`id`</td><td>The gift. Notifications and the chat card open it with `GET /gifts/{id}`</td></tr><tr><td>`kind`</td><td>`PRIVATE`, `PUBLIC` (code), `SELF`</td></tr><tr><td>`status`</td><td>`SENT`, `ACTIVE`, `CLAIMED`, `REDEEMED`, `REJECTED`, `CANCELLED`, `RETURNED`, `FROZEN` (see 1.6)</td></tr><tr><td>`amount`</td><td>TZS, one card</td></tr><tr><td>`message`</td><td>The buyer's words, or `null`</td></tr><tr><td>`designId`, `designName`, `designImage`</td><td>The design **as it was when bought** (a later edit of the design doesn't change sent cards). The picture has **no words or amount on it**: the app draws amount, message and names on top</td></tr><tr><td>`from`</td><td>The buyer (`accountId`, `name`, `userProfileMedia`)</td></tr><tr><td>`to`</td><td>The receiver. **Always `null` for a code** (the buyer never learns who redeemed it). For a gift sent to a **typed number**, `null` until it is `CLAIMED` (show `recipientPhone` instead)</td></tr><tr><td>`recipientPhone`</td><td>Masked number (`+255•••••3456`) for a gift sent to a phone number; otherwise `null`</td></tr><tr><td>`code`</td><td>The full code. Only in the payment answer (endpoint 4) and `GET /gifts/{id}/code` (10). Everywhere else `null`</td></tr><tr><td>`codeLast4`</td><td>Last 4 characters of a code (`9DFT`) to tell codes apart; `null` for other kinds</td></tr><tr><td>`createdAt`</td><td>When it was bought</td></tr><tr><td>`expiresAt`</td><td>When it goes back to the buyer if still waiting (bought + 14 days)</td></tr><tr><td>`openedAt`</td><td>When it was claimed / redeemed</td></tr><tr><td>`closedAt`</td><td>When it stopped waiting (any final status)</td></tr><tr><td>`cancelUntil`</td><td>Present **only while the buyer can still cancel** (waiting and within 24 h). Show **Cancel** only when it's there</td></tr></tbody></table>

### GiftPerson

<table id="bkmrk-field-description-ac"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`accountId`</td><td>The person</td></tr><tr><td>`name`</td><td>Display name, or first + last name</td></tr><tr><td>`userProfileMedia`</td><td>Profile photo (`fileId`, `status`, `thumbUrl`, `mimeType`) or `null`</td></tr></tbody></table>

---

# Part 2 — Designs

## 1. Designs to choose from

**Purpose**: The gift designs a person can buy now, the amounts each one allows per kind, and how much they can still buy today.

**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}/gifts/designs`

**Access Level**: 🔒 Protected (any signed-in person)

**Authentication**: Bearer token

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift designs", "action_time": "2026-11-21T10:30:45",
  "data": {
    "designs": [
      { "id": "3a7b…", "name": "Birthday", "occasion": "Birthday",
        "image": { "fileId": "8c2e…", "status": "READY", "mimeType": "image/webp", "variants": { "thumb": "https://…/thumb.webp" } },
        "presetAmounts": [5000, 10000, 20000],
        "kinds": [ { "kind": "PRIVATE", "minAmount": 1000, "maxAmount": 100000 },
                   { "kind": "PUBLIC",  "minAmount": 1000, "maxAmount": 100000 } ] },
      { "id": "0b11…", "name": "NexGate", "occasion": "General", "image": null,
        "presetAmounts": [5000, 10000, 20000, 50000],
        "kinds": [ { "kind": "PRIVATE", "minAmount": 1000, "maxAmount": 500000 },
                   { "kind": "PUBLIC",  "minAmount": 1000, "maxAmount": 200000 },
                   { "kind": "SELF",    "minAmount": 1000, "maxAmount": 1000000 } ] }
    ],
    "maxCardsPerPurchase": 20,
    "leftToday": 1000000,
    "leftTodayForCodes": 500000
  }
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-de"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`designs[]`</td><td>Designs showing now, in the admin's order. The **NexGate** card is always there (last)</td></tr><tr><td>`designs[].image`</td><td>The picture (no words on it), or `null` for the NexGate card until one is uploaded: draw the NexGate brand card</td></tr><tr><td>`designs[].presetAmounts`</td><td>Quick-pick amounts (up to 6). The person may still type any amount in the range</td></tr><tr><td>`designs[].kinds[]`</td><td>The kinds this design can be bought as, with the **real** range: the design's range made stricter by the platform limits. **A kind not listed can't be bought with this design**: hide that option</td></tr><tr><td>`maxCardsPerPurchase`</td><td>Most codes in one purchase</td></tr><tr><td>`leftToday`</td><td>TZS this person can still spend on gifts today (all kinds)</td></tr><tr><td>`leftTodayForCodes`</td><td>TZS left today for codes (codes have a smaller limit inside the daily one)</td></tr></tbody></table>

Grey out amounts above `leftToday` (or `leftTodayForCodes` for codes) and say "Daily gift limit".

---

# Part 3 — Buying a gift

Buying is a **gift checkout**, separate from shop checkouts: open → (look) → pay. A session lives **15 minutes**. Nothing is taken from the wallet until **process-payment**.

## 2. Open a gift checkout

**Purpose**: Check the gift against every rule and get a session to pay.

**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}/gifts/checkout-sessions`

**Access Level**: 🔒 Protected (any signed-in person)

**Authentication**: Bearer token

**Request JSON Sample** (private, to a person, from a chat):

```json
{
  "kind": "PRIVATE",
  "designId": "3a7b…",
  "amount": 20000,
  "recipientId": "3213…",
  "message": "Happy birthday Juma!",
  "conversationId": "c9d0…"
}

```

Other kinds:

```json
{ "kind": "PRIVATE", "amount": 20000, "recipientPhone": "0754 123 456" }
{ "kind": "PUBLIC",  "designId": "3a7b…", "amount": 10000, "quantity": 3, "message": "Asante!" }
{ "kind": "SELF",    "amount": 50000 }

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>kind</td><td>string</td><td>Yes</td><td>`PRIVATE`, `PUBLIC` or `SELF`</td><td>enum</td></tr><tr><td>designId</td><td>UUID</td><td>No</td><td>A design from endpoint 1. Left out = the NexGate card</td><td>must be showing now and allow this `kind`</td></tr><tr><td>amount</td><td>number</td><td>Yes</td><td>TZS for **one** card</td><td>whole shillings; inside the design's range for this kind; &gt; 0</td></tr><tr><td>quantity</td><td>integer</td><td>No</td><td>How many codes (PUBLIC only). Default 1</td><td>1 to `maxCardsPerPurchase`; must be 1 (or left out) for PRIVATE and SELF</td></tr><tr><td>recipientId</td><td>UUID</td><td>PRIVATE: one of the two</td><td>The receiver, from the user search</td><td>not yourself; nobody blocked</td></tr><tr><td>recipientPhone</td><td>string</td><td>PRIVATE: one of the two</td><td>Any Tanzanian format: `0754…`, `255754…`, `+255754…`, spaces allowed</td><td>must be a valid number; not your own</td></tr><tr><td>message</td><td>string</td><td>No</td><td>The buyer's words on the card</td><td>max 280 characters; blank = none; **no links** (`www.`, `https://`, `wa.me/…`, `bit.ly/…`, `name.com` …)</td></tr><tr><td>conversationId</td><td>UUID</td><td>No</td><td>Send from a one-to-one chat: the gift also appears in that chat</td><td>PRIVATE only (ignored otherwise); must be a personal chat between you and the receiver</td></tr></tbody></table>

- Send `recipientId` **or** `recipientPhone` for PRIVATE, never both. Send neither for PUBLIC and SELF.
- A phone number that belongs to a NexGate account becomes a gift to that account (the app is not told).

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift checkout opened", "action_time": "2026-11-21T10:30:45",
  "data": {
    "sessionId": "5e6f…",
    "status": "PENDING_PAYMENT",
    "kind": "PRIVATE",
    "designId": "3a7b…",
    "amount": 20000,
    "quantity": 1,
    "total": 20000,
    "recipient": { "accountId": "3213…", "name": "Juma Ally", "userProfileMedia": null },
    "recipientPhone": null,
    "message": "Happy birthday Juma!",
    "walletBalance": 75000,
    "expiresAt": "2026-11-21T10:45:45",
    "cards": []
  }
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-se"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`sessionId`</td><td>Use it to pay (4), look (3) or leave (5)</td></tr><tr><td>`status`</td><td>`PENDING_PAYMENT`, `COMPLETED`, `CANCELLED`, `EXPIRED`</td></tr><tr><td>`designId`</td><td>The design used (the NexGate card's id when none was sent)</td></tr><tr><td>`amount`, `quantity`, `total`</td><td>`total = amount × quantity`: what will leave the wallet</td></tr><tr><td>`recipient`</td><td>The receiver when picked by `recipientId`. `null` when a number was typed, even if it is on NexGate</td></tr><tr><td>`recipientPhone`</td><td>Masked number for a gift to someone not on NexGate, else `null`</td></tr><tr><td>`walletBalance`</td><td>The buyer's **wallet** now. Gifts are paid from wallet only, never from gift balance. If `walletBalance < total`, offer a top-up first</td></tr><tr><td>`expiresAt`</td><td>Pay before this (15 minutes)</td></tr><tr><td>`cards`</td><td>Empty until paid</td></tr></tbody></table>

**Errors** (409 `data.code`): `GIFT_RECIPIENT`, `GIFT_PHONE`, `GIFT_SELF`, `GIFT_CHAT`, `DESIGN_UNAVAILABLE`, `DESIGN_KIND`, `GIFT_AMOUNT`, `GIFT_TOO_SMALL`, `GIFT_TOO_BIG`, `GIFT_QUANTITY`, `GIFT_DAILY_LIMIT`, `GIFT_DAILY_CODE_LIMIT`, `GIFT_NOT_ACCEPTED`, `GIFT_MESSAGE_LINK`, `GIFTS_ON_HOLD`. 404 "Person not found" for an unknown `recipientId`.

---

## 3. Look at a gift checkout

**Purpose**: The session again (for example after the app was closed). Once paid it carries the cards, **without** full codes.

**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}/gifts/checkout-sessions/{sessionId}`

**Access Level**: 🔒 Protected (the buyer only; anyone else gets 404)

**Authentication**: Bearer token

**Path Parameters**:

<table id="bkmrk-parameter-type-requi-1"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>sessionId</td><td>UUID</td><td>Yes</td><td>From endpoint 2</td><td>must be yours</td></tr></tbody></table>

**Success Response**: the same object as endpoint 2 (`cards` filled when `COMPLETED`, each with `code: null`).

---

## 4. Pay

**Purpose**: Take the money from the buyer's wallet and create the cards, both in one step: either both happen or neither.

**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}/gifts/checkout-sessions/{sessionId}/process-payment`

**Access Level**: 🔒 Protected (the buyer only)

**Authentication**: Bearer token

**Path Parameters**:

<table id="bkmrk-parameter-type-requi-2"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>sessionId</td><td>UUID</td><td>Yes</td><td>From endpoint 2</td><td>must be yours, `PENDING_PAYMENT`, not expired</td></tr></tbody></table>

No body. Every rule from endpoint 2 is checked **again** (a design may have been switched off, today's total may have changed in another tab).

**Success Response JSON Sample** (3 codes):

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift paid", "action_time": "2026-11-21T10:31:20",
  "data": {
    "sessionId": "5e6f…", "status": "COMPLETED", "kind": "PUBLIC", "designId": "3a7b…",
    "amount": 10000, "quantity": 3, "total": 30000,
    "recipient": null, "recipientPhone": null, "message": "Asante!",
    "walletBalance": 45000, "expiresAt": "2026-11-21T10:45:45",
    "cards": [
      { "id": "a1…", "kind": "PUBLIC", "status": "ACTIVE", "amount": 10000, "code": "NXG-7K4Q-M2PX-9DFT", "codeLast4": "9DFT",
        "from": { "accountId": "304e…", "name": "Asha Mushi", "userProfileMedia": null }, "to": null,
        "expiresAt": "2026-12-05T10:31:20", "cancelUntil": "2026-11-22T10:31:20", "…": "rest of GiftCard" },
      { "id": "a2…", "kind": "PUBLIC", "status": "ACTIVE", "amount": 10000, "code": "NXG-HR3W-8BNZ-T6QA", "codeLast4": "T6QA", "…": "…" },
      { "id": "a3…", "kind": "PUBLIC", "status": "ACTIVE", "amount": 10000, "code": "NXG-K9PD-2XVE-C4MS", "codeLast4": "C4MS", "…": "…" }
    ]
  }
}

```

**Success Response Fields**: the session (endpoint 2) with `status: COMPLETED` and `cards[]` ([GiftCard](#giftcard)).

<table id="bkmrk-kind-cards-private-o"><thead><tr><th>Kind</th><th>`cards`</th></tr></thead><tbody><tr><td>PRIVATE</td><td>one card, `SENT`; the receiver is told (or gets the SMS)</td></tr><tr><td>PUBLIC</td><td>`quantity` cards, `ACTIVE`, **each with its full `code`**. This is the only list that ever carries full codes: show them with **Copy** and **Share**</td></tr><tr><td>SELF</td><td>one card, `CLAIMED`; the gift balance already has the money</td></tr></tbody></table>

- **Paying twice is safe**: a second call on a `COMPLETED` session returns the same cards and takes no money (still- `ACTIVE` codes come with their full code again).
- Network lost after tapping Pay? Call it again with the same `sessionId`.

**Errors** (409): `CHECKOUT_CLOSED` (left or already ended), `CHECKOUT_EXPIRED` (over 15 minutes: start again), `INSUFFICIENT_BALANCE` (reason says how much to top up: "Top up 5000 TZS to continue"), and every code from endpoint 2.

---

## 5. Leave a gift checkout

**Purpose**: The buyer backs out before paying.

**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}/gifts/checkout-sessions/{sessionId}/cancel`

**Access Level**: 🔒 Protected (the buyer only)

**Authentication**: Bearer token

No body. A `PENDING_PAYMENT` session becomes `CANCELLED`; any other session is returned unchanged (calling it twice is safe). Nothing was taken, so nothing is given back. To cancel a gift **after** paying, use endpoint 13.

**Success Response**: the session (endpoint 2) with `status: CANCELLED`.

---

# Part 4 — My gifts

The Gift menu has three lists: **Received**, **Sent** and **My codes**. Each comes with counts for the tabs / chips.

## 6. Gifts I received

**Purpose**: Private gifts sent to me, newest first. Also links any gifts sent to **my phone number** before I joined.

**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}/gifts/received`

**Access Level**: 🔒 Protected

**Authentication**: Bearer token

**Query Parameters**:

<table id="bkmrk-parameter-type-requi-3"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th><th>Default</th></tr></thead><tbody><tr><td>page</td><td>integer</td><td>No</td><td>Page, from 0</td><td>≥ 0</td><td>0</td></tr><tr><td>size</td><td>integer</td><td>No</td><td>Cards per page</td><td>1–50</td><td>20</td></tr></tbody></table>

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gifts received", "action_time": "2026-11-21T10:30:45",
  "data": {
    "cards": [ { "id": "9f1c…", "kind": "PRIVATE", "status": "SENT", "amount": 20000, "…": "GiftCard" } ],
    "counts": { "waiting": 1, "opened": 4, "returned": 0, "rejected": 1, "cancelled": 0, "onHold": 0 },
    "page": 0, "size": 20, "hasNext": false
  }
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-ca"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`cards[]`</td><td>[GiftCard](#giftcard)s</td></tr><tr><td>`counts.waiting`</td><td>`SENT` + `ACTIVE`: still to be opened</td></tr><tr><td>`counts.opened`</td><td>`CLAIMED` + `REDEEMED`</td></tr><tr><td>`counts.returned`</td><td>`RETURNED` (not opened in 14 days)</td></tr><tr><td>`counts.rejected`</td><td>`REJECTED`</td></tr><tr><td>`counts.cancelled`</td><td>`CANCELLED` by the buyer</td></tr><tr><td>`counts.onHold`</td><td>`FROZEN` by support</td></tr><tr><td>`page`, `size`, `hasNext`</td><td>Paging: ask for `page + 1` while `hasNext`</td></tr></tbody></table>

Show **Claim / Decline** on cards with `status: SENT`.

---

## 7. Gifts I sent

**Purpose**: Private gifts I bought for other people, newest first.

**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}/gifts/sent`

**Access Level**: 🔒 Protected

**Authentication**: Bearer token

**Query Parameters**: `page`, `size` as in endpoint 6.

**Success Response**: the same shape as endpoint 6. `counts` are over my sent gifts. Show **Cancel** while `cancelUntil` is present.

---

## 8. My codes

**Purpose**: Gift codes I bought, newest first. Codes show `codeLast4` only.

**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}/gifts/codes`

**Access Level**: 🔒 Protected

**Authentication**: Bearer token

**Query Parameters**: `page`, `size` as in endpoint 6.

**Success Response**: the same shape as endpoint 6. On each card `to` is `null`. A `REDEEMED` code shows "Redeemed on {closedAt}" (never by whom). An `ACTIVE` code shows **Show code** (endpoint 10) and **Cancel** while `cancelUntil` is present.

---

## 9. One gift

**Purpose**: One gift, for its buyer or its receiver. Notifications and the chat card open this.

**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}/gifts/{giftId}`

**Access Level**: 🔒 Protected (the buyer or the receiver; anyone else gets 404)

**Authentication**: Bearer token

**Path Parameters**:

<table id="bkmrk-parameter-type-requi-4"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>giftId</td><td>UUID</td><td>Yes</td><td>The gift</td><td></td></tr></tbody></table>

**Success Response**: one [GiftCard](#giftcard) (`code` always `null` here).

What to show:

<table id="bkmrk-i-am-status-buttons-"><thead><tr><th>I am</th><th>Status</th><th>Buttons</th></tr></thead><tbody><tr><td>receiver</td><td>`SENT`</td><td>Claim · Decline</td></tr><tr><td>buyer</td><td>waiting, `cancelUntil` present</td><td>Cancel</td></tr><tr><td>buyer of a code</td><td>`ACTIVE`</td><td>Show code · Share</td></tr><tr><td>anyone</td><td>`FROZEN`</td><td>"On hold by NexGate support"</td></tr><tr><td>anyone</td><td>final</td><td>the status and `closedAt`</td></tr></tbody></table>

---

# Part 5 — Opening, declining, cancelling, redeeming

All of these are **safe to call twice**: repeating a claim that already happened returns the card as it is, without moving money again.

## 10. Show a code again

**Purpose**: The buyer sees the full code of an unused code (to share it again).

**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}/gifts/{giftId}/code`

**Access Level**: 🔒 Protected (the code's buyer only)

**Authentication**: Bearer token

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift code", "action_time": "2026-11-21T10:30:45",
  "data": { "giftId": "a1…", "code": "NXG-7K4Q-M2PX-9DFT" }
}

```

Put it behind a tap (and the phone's PIN / fingerprint if the app has it): a code is money for whoever reads it.

**Errors**: 404 (not a code, or not yours); 409 `CODE_CLOSED` (no longer `ACTIVE`: once used, cancelled or returned the code is deleted and can never be shown again).

---

## 11. Claim

**Purpose**: The receiver takes a private gift into their gift balance.

**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}/gifts/{giftId}/claim`

**Access Level**: 🔒 Protected (the receiver only; anyone else gets 404)

**Authentication**: Bearer token

No body.

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift claimed", "action_time": "2026-11-21T11:02:10",
  "data": { "id": "9f1c…", "kind": "PRIVATE", "status": "CLAIMED", "amount": 20000,
            "openedAt": "2026-11-21T11:02:10", "closedAt": "2026-11-21T11:02:10", "cancelUntil": null, "…": "GiftCard" }
}

```

Then: show "TZS 20,000 added to your gift balance" and refresh `GET /wallet/gift`. The buyer gets `GIFT_CLAIMED`.

**Errors** (409): `GIFT_CLOSED` (already declined, cancelled or returned), `GIFT_EXPIRED` (past 14 days, on its way back), `GIFT_ON_HOLD` (frozen by support), `GIFTS_ON_HOLD` (my account's gifts are frozen).

---

## 12. Decline

**Purpose**: The receiver says no thanks. The money goes **straight back to the buyer's wallet**.

**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}/gifts/{giftId}/reject`

**Access Level**: 🔒 Protected (the receiver only)

**Authentication**: Bearer token

No body. Ask "Decline this gift? The money goes back to Asha." first.

**Success Response**: the [GiftCard](#giftcard) with `status: REJECTED`. The buyer gets `GIFT_REJECTED`.

**Errors** (409): `GIFT_CLOSED`, `GIFT_EXPIRED`, `GIFT_ON_HOLD`.

---

## 13. Cancel (buyer)

**Purpose**: The buyer takes back a waiting private gift or an unused code, **within 24 hours** of buying. The money goes back to their wallet.

**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}/gifts/{giftId}/cancel`

**Access Level**: 🔒 Protected (the buyer only; SELF gifts can't be cancelled)

**Authentication**: Bearer token

No body. The receiver is **not** told; the card just shows Cancelled. A cancelled code stops working at once.

**Success Response**: the [GiftCard](#giftcard) with `status: CANCELLED`.

**Errors** (409): `CANCEL_WINDOW_PASSED` ("Gifts can only be cancelled within 24 hours; it comes back by itself if it isn't opened in time"), `GIFT_CLOSED` (already opened), `GIFT_EXPIRED`, `GIFT_ON_HOLD`.

---

## 14. Redeem a code

**Purpose**: Anyone types a gift code and gets its money in their gift balance.

**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}/gifts/redeem`

**Access Level**: 🔒 Protected (any signed-in person, the buyer too)

**Authentication**: Bearer token

**Request JSON Sample**:

```json
{ "code": "nxg 7k4q m2px 9dft" }

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi-5"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>code</td><td>string</td><td>Yes</td><td>As the person typed or pasted it</td><td>not blank; any case; `NXG` optional; spaces and dashes ignored</td></tr></tbody></table>

**Success Response**: the [GiftCard](#giftcard) with `status: REDEEMED`, `to: null`. Show "TZS 10,000 added to your gift balance". The buyer gets `GIFT_CODE_REDEEMED` (unless they redeemed it themselves).

Redeeming the same code twice by the same person returns the card again (no second credit).

**Errors** (409):

<table id="bkmrk-code-show-code_not_f"><thead><tr><th>Code</th><th>Show</th></tr></thead><tbody><tr><td>`CODE_NOT_FOUND`</td><td>"That code doesn't exist; check it and try again" (counts as a wrong try)</td></tr><tr><td>`CODE_USED`</td><td>"This code has already been used or is no longer valid"</td></tr><tr><td>`CODE_EXPIRED`</td><td>"This code has expired"</td></tr><tr><td>`GIFT_ON_HOLD`</td><td>"This code is on hold; contact support"</td></tr><tr><td>`CODE_TRIES_PAUSED`</td><td>"Too many wrong codes; try again in 60 minutes" (5 wrong tries)</td></tr><tr><td>`GIFTS_ON_HOLD`</td><td>gifts are frozen for my account</td></tr></tbody></table>

---

# Part 6 — Gift balance

## 15. My gift balance

**Purpose**: How much gift money I have.

**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}/wallet/gift`

**Access Level**: 🔒 Protected

**Authentication**: Bearer token

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift balance", "action_time": "2026-11-21T10:30:45",
  "data": { "balance": 20000, "currency": "TZS" }
}

```

The wallet screen shows two lines: **Wallet** (`/wallet/my-wallet`, unchanged: pay, withdraw, send) and **Gift**(this: pay only). Never add them into one number labelled "balance".

---

## 16. Gift balance history

**Purpose**: Every move in and out of my gift balance, newest first.

**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}/wallet/gift/history`

**Access Level**: 🔒 Protected

**Authentication**: Bearer token

**Query Parameters**:

<table id="bkmrk-parameter-type-requi-6"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th><th>Default</th></tr></thead><tbody><tr><td>page</td><td>integer</td><td>No</td><td>Page, from 0</td><td>≥ 0</td><td>0</td></tr><tr><td>size</td><td>integer</td><td>No</td><td>Entries per page</td><td>1–100</td><td>20</td></tr></tbody></table>

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift balance history", "action_time": "2026-11-21T10:30:45",
  "data": {
    "entries": [
      { "entryId": "e3…", "type": "GIFT_REFUND", "amount": 20000,  "description": "Gift part back from ESC-2026-0042", "at": "2026-11-23T09:12:00" },
      { "entryId": "e2…", "type": "GIFT_USE",    "amount": -20000, "description": "Contribution to ESC-2026-0042", "at": "2026-11-22T18:40:31" },
      { "entryId": "e1…", "type": "GIFT_CLAIM",  "amount": 20000,  "description": "Gift opened", "at": "2026-11-21T11:02:10" }
    ],
    "page": 0, "size": 20, "hasNext": false
  }
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-en"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`entries[].type`</td><td>`GIFT_CLAIM` (a private gift claimed), `GIFT_LOAD` (bought for myself), `GIFT_USE` (paid an order / ticket), `GIFT_REFUND` (a refund's gift part came back)</td></tr><tr><td>`entries[].amount`</td><td>**+ money in, − money out**</td></tr><tr><td>`entries[].description`</td><td>Short text from the ledger</td></tr><tr><td>`entries[].at`</td><td>When</td></tr></tbody></table>

A redeemed code shows as `GIFT_CLAIM` too.

---

# Part 7 — Changes to existing endpoints

Also listed in `commerce_logistics_changes.md` §15. With gifts **off**, none of this appears.

## 7.1 Creating or changing a checkout: `useGiftBalance`

**Endpoints**: <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}/e-commerce/checkout-sessions` · <span style="background-color: #fd7e14; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span> `{base_url}/e-commerce/checkout-sessions/{sessionId}` · <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}/e-events/checkout`

**New Request Body Parameter**:

<table id="bkmrk-parameter-type-requi-7"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>useGiftBalance</td><td>boolean</td><td>No</td><td>Left out or `true`: gift balance pays first, the wallet the rest. `false`: wallet only for this payment</td><td>ignored by instalment checkouts (always cash)</td></tr></tbody></table>

```json
{ "sessionType": "REGULAR_DIRECTLY", "items": [ … ], "useGiftBalance": false }

```

- On the pay screen show a toggle **"Use gift balance (TZS 20,000)"**, on by default, only when the gift balance is more than 0. Changing it on an open checkout: `PATCH` with `useGiftBalance`.
- The "not enough money" check when a checkout is created now counts **wallet + gift** (when the toggle is on). Before, a person paying partly with gift was refused here.
- Event tickets: gift is not used for tickets sold at the door, cash-receipt sales or free tickets.

## 7.2 Balance check before paying

**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}/wallet/checkout-balance-check?sessionId={id}&domain={PRODUCT|EVENT}`

**New response fields** (only when gifts are on):

```json
{
  "success": true, "httpStatus": "OK", "message": "Checkout balance check completed", "action_time": "2026-11-22T18:40:00",
  "data": {
    "walletBalance": 50000,
    "sessionTotal": 35000,
    "giftBalance": 20000,
    "giftPart": 20000,
    "shortfall": 0,
    "hasSufficientBalance": true,
    "pspMinimum": 1000,
    "currency": "TZS"
  }
}

```

<table id="bkmrk-field-description-gi"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`giftBalance`</td><td>**New.** The person's gift balance now</td></tr><tr><td>`giftPart`</td><td>**New.** What the gift will pay for this checkout: `min(giftBalance, sessionTotal)`, or 0 when `useGiftBalance` is false / instalment / not allowed</td></tr><tr><td>`shortfall`</td><td>**Changed.** `sessionTotal − giftPart − walletBalance` (at least 0)</td></tr><tr><td>`walletBalance`</td><td>Unchanged: the wallet</td></tr></tbody></table>

Show: "Gift TZS 20,000 · Wallet TZS 15,000 · Total TZS 35,000".

## 7.3 Payment answer

**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}/e-commerce/checkout-sessions/{sessionId}/process-payment` (and the event payment)

**New response fields**:

```json
{ "success": true, "status": "COMPLETED", "amountPaid": 35000, "giftPaid": 20000, "walletPaid": 15000, "currency": "TZS", "…": "unchanged" }

```

<table id="bkmrk-field-description-gi-1"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`giftPaid`</td><td>**New.** Paid from the gift balance (0 when none)</td></tr><tr><td>`walletPaid`</td><td>**New.** Paid from the wallet (not cash in hand: every payment goes through the wallet; this is the part that wasn't gift balance). `giftPaid + walletPaid = amountPaid`</td></tr></tbody></table>

**New refusal** (409): `GIFT_BALANCE_CHANGED`: "Your gift balance has changed; check the price again". The gift balance went down between the balance check and Pay (for example, spent on another phone). Call the balance check again and show the new split.

## 7.4 Refund notice (`ESCROW_REFUNDED`)

The notification data gains a `refund` object with ready lines. In-app shows `refund.title` and `refund.body`:

<table id="bkmrk-paid-with-refund.tit"><thead><tr><th>Paid with</th><th>`refund.title`</th><th>`refund.body`</th></tr></thead><tbody><tr><td>wallet only</td><td>TZS 35,000 refunded to your wallet</td><td>From order ORD-2026-0042</td></tr><tr><td>gift + wallet</td><td>TZS 35,000 refunded</td><td>From order ORD-2026-0042 · TZS 20,000 to your gift balance · TZS 15,000 to your wallet</td></tr></tbody></table>

With a gift part, `refund` also has `total`, `toGift`, `toWallet` (formatted, e.g. `"TZS 20,000"`). A refund that went **all** to the gift balance now notifies too (before, nothing to the wallet = no notice). The old `amount` field stays as it was (the wallet part).

## 7.5 Transaction history

New `type` values in the transaction history (`GET /transaction-history`):

<table id="bkmrk-type-direction-when-"><thead><tr><th>Type</th><th>Direction</th><th>When</th></tr></thead><tbody><tr><td>`GIFT_PURCHASE`</td><td>debit</td><td>bought a gift / codes</td></tr><tr><td>`GIFT_LOADED`</td><td>debit</td><td>bought for myself (wallet → gift)</td></tr><tr><td>`GIFT_SPENT`</td><td>debit</td><td>the gift part of a payment</td></tr><tr><td>`GIFT_REFUNDED`</td><td>credit</td><td>the gift part of a refund</td></tr><tr><td>`GIFT_RECEIVED`</td><td>credit</td><td>a gift claimed or a code redeemed (into the gift balance)</td></tr><tr><td>`GIFT_RETURNED`</td><td>credit</td><td>a gift came back to the wallet (declined, cancelled, 14 days, support)</td></tr></tbody></table>

---

# Part 8 — The gift card in a chat

A private gift bought with `conversationId` writes a message of type **`GIFT_REF`** into that one-to-one chat (push preview "🎁 Gift"). It is written **after** payment succeeds. Group chats can't carry gifts.

The card is built **each time it is shown**, from the gift as it is now: when Juma claims, the card in both phones shows `CLAIMED` without a new message.

```json
{
  "kind": "GIFT",
  "labelKey": "card.gift",
  "title": "Birthday",
  "thumbUrl": "https://files.nexgate.co/…/thumb.webp",
  "amount": { "minor": 2000000, "currency": "TZS" },
  "status": "SENT",
  "target": { "type": "GIFT", "id": "9f1c…" },
  "details": { "giftId": "9f1c…", "expiresAt": "2026-12-05T10:30:45", "forMe": true, "canAnswer": true }
}

```

<table id="bkmrk-field-description-ti"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`title`</td><td>The design's name</td></tr><tr><td>`thumbUrl`</td><td>The design picture's thumbnail (or `null`: draw the NexGate card)</td></tr><tr><td>`amount.minor`</td><td>**Minor units** like every chat card (`2000000` = TZS 20,000.00)</td></tr><tr><td>`status`</td><td>The gift's status now</td></tr><tr><td>`target`</td><td>Tap → `GET /gifts/{id}`</td></tr><tr><td>`details.forMe`</td><td>The viewer is the receiver</td></tr><tr><td>`details.canAnswer`</td><td>Show **Claim** / **Decline** on the card (receiver and still `SENT`)</td></tr></tbody></table>

```
 Asha's phone                                  Juma's phone
 ┌───────────────────────────────┐             ┌───────────────────────────────┐
 │ [Birthday picture]            │             │ [Birthday picture]            │
 │ TZS 20,000                    │             │ TZS 20,000                    │
 │ "Happy birthday Juma!"        │             │ "Happy birthday Juma!"        │
 │ Waiting · until 5 Dec         │             │ [ Claim ]  [ Decline ]        │
 └───────────────────────────────┘             └───────────────────────────────┘
                after Juma claims, both show:  ✓ Claimed

```

---

# Part 9 — Notifications

All have `targetType: "GIFT"` and `targetId` = the gift id (open `GET /gifts/{id}`), except `GIFT_BALANCE_LOADED`(`targetType: "GIFT_BALANCE"`, no id: open the gift balance). Settings category: **Gifts**.

<table id="bkmrk-type-to-when-channel"><thead><tr><th>Type</th><th>To</th><th>When</th><th>Channels</th><th>In-app text (example)</th></tr></thead><tbody><tr><td>`GIFT_RECEIVED`</td><td>receiver</td><td>a private gift arrives</td><td>bell, push</td><td>🎁 Asha sent you a gift · TZS 20,000 · claim by 5 Dec</td></tr><tr><td>`GIFT_INVITE_SMS`</td><td>a phone not on NexGate</td><td>a gift to that number; reminder 1 day before return</td><td>SMS only</td><td>(bell for the buyer: "Gift sent to +255•••••3456 · They get an SMS to sign up and claim it")</td></tr><tr><td>`GIFT_CLAIM_REMINDER`</td><td>receiver</td><td>3 days and 1 day before return</td><td>bell, push</td><td>Your gift from Asha expires in 3 days · Claim TZS 20,000 before 5 Dec</td></tr><tr><td>`GIFT_CLAIMED`</td><td>buyer</td><td>receiver claimed</td><td>bell, push</td><td>🎉 Juma claimed your gift · TZS 20,000</td></tr><tr><td>`GIFT_REJECTED`</td><td>buyer</td><td>receiver declined</td><td>bell, push</td><td>Juma declined your gift · TZS 20,000 is back in your wallet</td></tr><tr><td>`GIFT_CODE_REDEEMED`</td><td>buyer</td><td>someone else used a code</td><td>bell, push</td><td>Your gift code …9DFT was redeemed · TZS 10,000 · 22 Nov</td></tr><tr><td>`GIFT_RETURNING_SOON`</td><td>buyer</td><td>2 days before return</td><td>bell</td><td>Your gift to Juma is not opened yet · It returns to your wallet on 5 Dec</td></tr><tr><td>`GIFT_RETURNED`</td><td>buyer</td><td>not opened in 14 days (or support returned it)</td><td>bell, push</td><td>TZS 20,000 is back in your wallet · Your gift to Juma wasn't opened in time</td></tr><tr><td>`GIFT_PURCHASED`</td><td>buyer</td><td>paid (private / codes)</td><td>bell, email</td><td>Your gift to Juma is on its way · TZS 20,000 paid from your wallet</td></tr><tr><td>`GIFT_BALANCE_LOADED`</td><td>buyer</td><td>bought for myself</td><td>bell</td><td>TZS 50,000 added to your gift balance · Pay only · it can't be withdrawn</td></tr></tbody></table>

Notification `data` (for apps that draw their own text): `giftId`, `actor.name` (buyer), `recipient.name` (or masked phone), `gift.amount`, `gift.expiresOn`, `gift.kind`, `gift.codeLast4`, `gift.daysLeft` (reminders), `gift.count` / `gift.total` (purchase), `isCode`.

Cancelling sends nothing to the receiver. Freezing sends nothing to anyone.

---

# Part 10 — Admin

Base: `{base_url}/admin/gifts`. Every change asks for a `reason` and is written to the admin audit log with who did it.

<table id="bkmrk-role-can-role_staff_"><thead><tr><th>Role</th><th>Can</th></tr></thead><tbody><tr><td>`ROLE_STAFF_ADMIN`</td><td>look up, freeze / unfreeze gifts and accounts, needs-decision list, report</td></tr><tr><td>`ROLE_SUPER_ADMIN`</td><td>all of that + designs, settings, **return a gift to its buyer**</td></tr></tbody></table>

## 17. All designs

**Purpose**: Every design, switched on or off, in display order.

**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}/admin/gifts/designs`

**Access Level**: 🔒 Protected (super admin)

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift designs", "action_time": "2026-11-21T10:30:45",
  "data": [
    { "id": "3a7b…", "name": "Birthday", "occasion": "Birthday",
      "image": { "fileId": "8c2e…", "status": "READY", "mimeType": "image/webp", "variants": { "thumb": "https://…" } },
      "minAmount": 1000, "maxAmount": 100000, "presetAmounts": [5000, 10000, 20000],
      "allowPrivate": true, "allowPublic": true, "allowSelf": false,
      "active": true, "fallback": false, "showFrom": null, "showUntil": null, "sortOrder": 10 },
    { "id": "0b11…", "name": "NexGate", "occasion": "General", "image": null, "minAmount": 1000, "maxAmount": 1000000,
      "presetAmounts": [5000, 10000, 20000, 50000], "allowPrivate": true, "allowPublic": true, "allowSelf": true,
      "active": true, "fallback": true, "showFrom": null, "showUntil": null, "sortOrder": 1000 }
  ]
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-mi"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`minAmount`, `maxAmount`</td><td>The design's own range. People get the stricter of this and the platform limits (settings)</td></tr><tr><td>`allowPrivate`, `allowPublic`, `allowSelf`</td><td>Which kinds can use it</td></tr><tr><td>`active`</td><td>Switched on</td></tr><tr><td>`fallback`</td><td>The NexGate card: always there, can't be switched off</td></tr><tr><td>`showFrom`, `showUntil`</td><td>Optional dates (a Christmas design from 1 Dec to 31 Dec)</td></tr><tr><td>`sortOrder`</td><td>Lower shows first</td></tr></tbody></table>

---

## 18. Add a design

**Purpose**: A new design from an uploaded picture.

**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}/admin/gifts/designs`

**Access Level**: 🔒 Protected (super admin)

**Request JSON Sample**:

```json
{
  "name": "Christmas",
  "occasion": "Holiday",
  "imageFileId": "77aa…",
  "minAmount": 2000,
  "maxAmount": 200000,
  "presetAmounts": [5000, 10000, 25000],
  "allowPrivate": true,
  "allowPublic": true,
  "allowSelf": false,
  "showFrom": "2026-12-01T00:00:00",
  "showUntil": "2026-12-31T23:59:59",
  "sortOrder": 5,
  "reason": "Christmas season"
}

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi-8"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>name</td><td>string</td><td>Yes</td><td>Shown to people</td><td>max 60</td></tr><tr><td>occasion</td><td>string</td><td>No</td><td>Grouping label</td><td>max 30</td></tr><tr><td>imageFileId</td><td>UUID</td><td>No</td><td>A picture uploaded to File Thunder with context **`GIFT_DESIGN`** (domain `GIFTS`), **with no words or amount on it**</td><td>must be `READY`, an image, context `GIFT_DESIGN`</td></tr><tr><td>minAmount, maxAmount</td><td>number</td><td>Yes</td><td>The design's range</td><td>&gt; 0; min ≤ max</td></tr><tr><td>presetAmounts</td><td>number\[\]</td><td>No</td><td>Quick picks</td><td>up to 6; each inside the range</td></tr><tr><td>allowPrivate, allowPublic, allowSelf</td><td>boolean</td><td>Yes</td><td>Kinds</td><td>at least one true</td></tr><tr><td>showFrom, showUntil</td><td>datetime</td><td>No</td><td>When it shows</td><td>from before until</td></tr><tr><td>sortOrder</td><td>integer</td><td>No</td><td>Order</td><td></td></tr><tr><td>reason</td><td>string</td><td>No</td><td>For the audit log</td><td></td></tr></tbody></table>

**Success Response**: the design (as in 17).

**Errors** (409): `DESIGN_LIMITS`, `DESIGN_KINDS`, `DESIGN_DATES`, `DESIGN_PRESETS`, `DESIGN_IMAGE` (not found), `DESIGN_IMAGE_NOT_READY` (still processing: try again shortly), `DESIGN_IMAGE_TYPE` (not a picture), `DESIGN_IMAGE_CONTEXT`(not uploaded as `GIFT_DESIGN`).

---

## 19. Edit a design

**Purpose**: Change a design. Cards already sent keep the name and picture they were bought with.

**Endpoint**: <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/admin/gifts/designs/{designId}`

**Access Level**: 🔒 Protected (super admin)

**Request Body**: the same as 18 (send every field). **Response / errors**: as 18; 404 for an unknown design.

---

## 20. Switch a design on / off, reorder

**Purpose**: Hide or show a design, or move it, without editing it.

**Endpoint**: <span style="background-color: #fd7e14; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span> `{base_url}/admin/gifts/designs/{designId}/state`

**Access Level**: 🔒 Protected (super admin)

**Request JSON Sample**:

```json
{ "active": false, "sortOrder": 20, "reason": "Season over" }

```

<table id="bkmrk-parameter-type-requi-9"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>active</td><td>boolean</td><td>No</td><td>On / off</td></tr><tr><td>sortOrder</td><td>integer</td><td>No</td><td>New position</td></tr><tr><td>reason</td><td>string</td><td>No</td><td>For the audit log</td></tr></tbody></table>

A checkout opened with a design that is switched off before paying is refused at pay (`DESIGN_UNAVAILABLE`).

**Errors** (409): `DESIGN_FALLBACK` (the NexGate card can't be switched off).

---

## 21. Gift settings

**Purpose**: The platform-wide gift rules.

**Endpoints**: <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}/admin/gifts/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> `{base_url}/admin/gifts/settings`

**Access Level**: 🔒 Protected (super admin)

**Request JSON Sample** (PUT: **only the fields sent change**):

```json
{ "dailyCodes": 300000, "wrongCodeLimit": 3, "reason": "Fraud wave on codes" }

```

**Response JSON Sample** (both):

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift settings", "action_time": "2026-11-21T10:30:45",
  "data": {
    "minAmount": 1000, "maxPrivate": 500000, "maxPublic": 200000, "maxSelf": 1000000,
    "maxCardsPerPurchase": 20, "dailyTotal": 1000000, "dailyCodes": 500000,
    "cancelWindowHours": 24, "returnDays": 14, "buyerNoticeDaysBefore": 2,
    "wrongCodeLimit": 5, "wrongCodePauseMinutes": 60, "updatedAt": "2026-11-21T10:30:45"
  }
}

```

<table id="bkmrk-field-default-meanin"><thead><tr><th>Field</th><th>Default</th><th>Meaning</th></tr></thead><tbody><tr><td>`minAmount`</td><td>1,000</td><td>Smallest card, any kind</td></tr><tr><td>`maxPrivate` / `maxPublic` / `maxSelf`</td><td>500,000 / 200,000 / 1,000,000</td><td>Largest card per kind</td></tr><tr><td>`maxCardsPerPurchase`</td><td>20</td><td>Most codes in one purchase</td></tr><tr><td>`dailyTotal`</td><td>1,000,000</td><td>Most TZS one person buys per day, all kinds</td></tr><tr><td>`dailyCodes`</td><td>500,000</td><td>Most TZS of codes per day (inside `dailyTotal`)</td></tr><tr><td>`cancelWindowHours`</td><td>24</td><td>Buyer may cancel within</td></tr><tr><td>`returnDays`</td><td>14</td><td>Unopened gifts go back after (applies to gifts bought **after** the change)</td></tr><tr><td>`buyerNoticeDaysBefore`</td><td>2</td><td>`GIFT_RETURNING_SOON` this many days before</td></tr><tr><td>`wrongCodeLimit` / `wrongCodePauseMinutes`</td><td>5 / 60</td><td>Wrong code tries before a pause, and its length</td></tr></tbody></table>

All amounts must be &gt; 0; `reason` is required on PUT.

---

## 22. Find gifts

**Purpose**: Support looks gifts up by person, phone number, code or status.

**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}/admin/gifts`

**Access Level**: 🔒 Protected (staff admin, super admin)

**Query Parameters**:

<table id="bkmrk-parameter-type-requi-10"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th><th>Default</th></tr></thead><tbody><tr><td>accountId</td><td>UUID</td><td>No</td><td>Gifts this person bought, received or redeemed</td><td></td><td></td></tr><tr><td>phone</td><td>string</td><td>No</td><td>Gifts sent to this phone number (not on NexGate)</td><td>valid number</td><td></td></tr><tr><td>code</td><td>string</td><td>No</td><td>The full code a customer reads out (found by its hash)</td><td></td><td></td></tr><tr><td>status</td><td>string</td><td>No</td><td>One status</td><td>GiftStatus enum</td><td></td></tr><tr><td>page</td><td>integer</td><td>No</td><td></td><td>≥ 0</td><td>0</td></tr><tr><td>size</td><td>integer</td><td>No</td><td></td><td>1–100</td><td>20</td></tr></tbody></table>

Filters combine. **Success Response**: as endpoint 6 (`counts` are all 0 here).

---

## 23. One gift (admin)

**Purpose**: Everything support needs about one gift.

**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}/admin/gifts/{giftId}`

**Access Level**: 🔒 Protected (staff admin, super admin)

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift", "action_time": "2026-11-21T10:30:45",
  "data": {
    "card": { "id": "a1…", "kind": "PUBLIC", "status": "REDEEMED", "amount": 10000, "codeLast4": "9DFT", "…": "GiftCard" },
    "redeemedBy": { "accountId": "77c1…", "name": "Neema John", "userProfileMedia": null },
    "checkoutSessionId": "5e6f…",
    "recipientPhone": null,
    "buyerFrozen": false,
    "recipientFrozen": false
  }
}

```

<table id="bkmrk-field-description-ca-1"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`card`</td><td>The [GiftCard](#giftcard)</td></tr><tr><td>`redeemedBy`</td><td>Who redeemed a code (**staff only**: never shown to the buyer)</td></tr><tr><td>`checkoutSessionId`</td><td>The purchase it came from (with its ledger entry)</td></tr><tr><td>`recipientPhone`</td><td>The **full** number for a phone gift</td></tr><tr><td>`buyerFrozen`, `recipientFrozen`</td><td>The account's gifts are on hold</td></tr></tbody></table>

The freeze, unfreeze and return endpoints answer with this same object.

---

## 24. A person's gift balance (admin)

**Purpose**: One person's gift balance, freeze state and last 50 moves.

**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}/admin/gifts/people/{accountId}`

**Access Level**: 🔒 Protected (staff admin, super admin)

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift balance", "action_time": "2026-11-21T10:30:45",
  "data": {
    "person": { "accountId": "3213…", "name": "Juma Ally", "userProfileMedia": null },
    "giftBalance": 20000,
    "frozen": false,
    "frozenReason": null,
    "history": [ { "entryId": "e1…", "type": "GIFT_CLAIM", "amount": 20000, "description": "Gift opened", "at": "2026-11-21T11:02:10" } ]
  }
}

```

The account freeze endpoints answer with this same object.

---

## 25. Freeze / unfreeze one gift

**Purpose**: Put a waiting gift on hold (suspected fraud, a complaint), or release it.

**Endpoints**: <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}/admin/gifts/{giftId}/freeze` · <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}/admin/gifts/{giftId}/unfreeze`

**Access Level**: 🔒 Protected (staff admin, super admin)

**Request JSON Sample**:

```json
{ "reason": "Buyer reports their phone was stolen" }

```

<table id="bkmrk-parameter-type-requi-11"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Validation</th></tr></thead><tbody><tr><td>reason</td><td>string</td><td>Yes</td><td>not blank, max 300</td></tr></tbody></table>

- Freeze: `SENT` / `ACTIVE` → `FROZEN`. It can't be claimed, redeemed, declined or cancelled, and **the 14-day return skips it**. Freezing twice is safe.
- Unfreeze: back to what it was (`SENT` or `ACTIVE`). If it is past its 14 days, the next hourly run returns it.

**Errors** (409): `GIFT_CLOSED` (freeze: already opened or final), `GIFT_NOT_FROZEN` (unfreeze).

---

## 26. Return a gift to its buyer

**Purpose**: The only hand-made money move: send a waiting or frozen gift's money back to the buyer's wallet.

**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}/admin/gifts/{giftId}/return`

**Access Level**: 🔒 Protected (**super admin only**)

**Request**: `{ "reason": "…" }` as in 25.

The gift becomes `RETURNED`, a code stops working, the buyer gets `GIFT_RETURNED`. Returning twice is safe. An opened gift can't be returned (its money is already someone's gift balance).

**Errors** (409): `GIFT_CLOSED` ("Only an unopened or frozen gift can be returned").

---

## 27. Freeze / unfreeze a person's gifts

**Purpose**: Stop one account from buying, claiming, redeeming or **paying with** gifts.

**Endpoints**: <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}/admin/gifts/people/{accountId}/freeze` · <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}/admin/gifts/people/{accountId}/unfreeze`

**Access Level**: 🔒 Protected (staff admin, super admin)

**Request**: `{ "reason": "…" }`. **Response**: as 24.

While frozen, that person gets `GIFTS_ON_HOLD` on gift checkout, claim and redeem, and their checkouts pay **from the wallet only** (the gift balance is left untouched). Their wallet is not affected. Calling twice is safe.

---

## 28. Needs a decision

**Purpose**: Frozen gifts past their 14 days: they will never come back on their own, so someone must unfreeze or return them.

**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}/admin/gifts/needs-decision`

**Access Level**: 🔒 Protected (staff admin, super admin)

**Success Response**: a list of the object in 23.

---

## 29. Report

**Purpose**: What was bought and what happened to it, and a check that the money adds up.

**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}/admin/gifts/report?from=2026-11-01`

**Access Level**: 🔒 Protected (staff admin, super admin)

**Query Parameters**:

<table id="bkmrk-parameter-type-requi-12"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th><th>Default</th></tr></thead><tbody><tr><td>from</td><td>date</td><td>No</td><td>Cards bought since this day</td><td>`YYYY-MM-DD`</td><td>first day of this month</td></tr></tbody></table>

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift report", "action_time": "2026-11-21T10:30:45",
  "data": {
    "from": "2026-11-01T00:00:00",
    "byStatus": { "SENT": 60000, "ACTIVE": 30000, "CLAIMED": 140000, "REDEEMED": 20000, "RETURNED": 10000 },
    "countByStatus": { "SENT": 3, "ACTIVE": 3, "CLAIMED": 9, "REDEEMED": 2, "RETURNED": 1 },
    "waitingNow": 90000,
    "liabilityBalance": 90000,
    "giftBalancesTotal": 135000,
    "reconciled": true,
    "difference": 0
  }
}

```

<table id="bkmrk-field-description-by"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`byStatus`</td><td>TZS of cards bought since `from`, by their status now</td></tr><tr><td>`countByStatus`</td><td>Number of those cards by status</td></tr><tr><td>`waitingNow`</td><td>TZS in all cards waiting or frozen now (any purchase date)</td></tr><tr><td>`liabilityBalance`</td><td>What NexGate's gift account holds now</td></tr><tr><td>`giftBalancesTotal`</td><td>Sum of everyone's gift balances now</td></tr><tr><td>`reconciled`</td><td>`true` when the gift account holds exactly the waiting cards</td></tr><tr><td>`difference`</td><td>`liabilityBalance − waitingNow`; anything but 0 is a problem to look into at once</td></tr></tbody></table>

The same check runs every night at 03:15 and writes a log line on a mismatch.

---

# Part 10a — Who can send me gifts

Each person chooses who may send them a **private** gift. Codes and buying for yourself are not affected. Gifts already sent stay (they can still be claimed or declined).

<table id="bkmrk-setting-asha-can-sen"><thead><tr><th>Setting</th><th>Asha can send Juma a gift when</th></tr></thead><tbody><tr><td>`EVERYONE` (default)</td><td>always, unless one has blocked the other</td></tr><tr><td>`PEOPLE_I_FOLLOW`</td><td>Juma follows Asha</td></tr><tr><td>`NOBODY`</td><td>never</td></tr></tbody></table>

```
 ASHA picks Juma (chat, profile, person picker)
        │
        ▼
 GET /gifts/can-send?recipientId=Juma ──► canSend: false ──► grey out Gift, show reason
        │ canSend: true                     "Juma isn't accepting gifts from you"
        ▼
 POST /gifts/checkout-sessions ─────────► checked again ─► 409 GIFT_NOT_ACCEPTED if Juma changed it meanwhile
        ▼
 POST …/process-payment ─────────────────► checked again ─► 409, nothing paid

```

## 30. Can I send this person a gift?

**Purpose**: Ask before checkout, to show or grey out **Gift** with the reason.

**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}/gifts/can-send`

**Access Level**: 🔒 Protected

**Authentication**: Bearer token

**Query Parameters**:

<table id="bkmrk-parameter-type-requi-13"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th><th>Default</th></tr></thead><tbody><tr><td>recipientId</td><td>UUID</td><td>One of the two</td><td>The person picked</td><td></td><td></td></tr><tr><td>recipientPhone</td><td>string</td><td>One of the two</td><td>A typed number</td><td>valid phone</td><td></td></tr></tbody></table>

**Success Response JSON Sample** (always HTTP 200; the answer is in `canSend`):

```json
{
  "success": true, "httpStatus": "OK", "message": "Can send a gift", "action_time": "2026-11-21T10:30:45",
  "data": { "canSend": false, "code": "GIFT_NOT_ACCEPTED", "reason": "Juma isn't accepting gifts from you",
            "recipient": { "accountId": "3213…", "name": "Juma Ally", "userProfileMedia": null }, "recipientPhone": null }
}

```

<table id="bkmrk-field-description-ca-2"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`canSend`</td><td>`true`: go to checkout</td></tr><tr><td>`code`, `reason`</td><td>Only when `canSend` is false: `GIFT_NOT_ACCEPTED`, `GIFT_SELF`, `GIFT_RECIPIENT`, `GIFT_PHONE`, `GIFTS_ON_HOLD`. Show `reason`</td></tr><tr><td>`recipient`</td><td>The person, when picked by `recipientId`. **Always `null` for a typed number**, so a number never reveals its owner</td></tr><tr><td>`recipientPhone`</td><td>The typed number, masked (`+255•••••3456`)</td></tr></tbody></table>

A typed number not on NexGate answers `canSend: true` (the person gets an SMS after paying). 404 for an unknown `recipientId`.

---

## 31. My gift setting

**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}/gifts/me/preferences`

**Access Level**: 🔒 Protected

**Success Response JSON Sample**:

```json
{ "success": true, "httpStatus": "OK", "message": "Gift preferences", "action_time": "2026-11-21T10:30:45",
  "data": { "whoCanSendGifts": "EVERYONE" } }

```

---

## 32. Change my gift setting

**Endpoint**: <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/gifts/me/preferences`

**Access Level**: 🔒 Protected

**Request JSON Sample**:

```json
{ "whoCanSendGifts": "PEOPLE_I_FOLLOW" }

```

<table id="bkmrk-parameter-type-requi-14"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>whoCanSendGifts</td><td>string</td><td>Yes</td><td>Who may send me private gifts</td><td>`EVERYONE`, `PEOPLE_I_FOLLOW`, `NOBODY`</td></tr></tbody></table>

**Success Response**: as 31, with the new value. Show it in Settings → Privacy → **Who can send me gifts**.

---

# Part 11 — Refusal codes

All are **HTTP 409**; show `data.reason`.

<table id="bkmrk-code-where-when-gift"><thead><tr><th>Code</th><th>Where</th><th>When</th></tr></thead><tbody><tr><td>`GIFT_RECIPIENT`</td><td>open</td><td>PRIVATE without exactly one of `recipientId` / `recipientPhone`; or a recipient on PUBLIC / SELF</td></tr><tr><td>`GIFT_PHONE`</td><td>open, admin search</td><td>not a valid phone number</td></tr><tr><td>`GIFT_SELF`</td><td>open</td><td>the recipient is yourself (use SELF)</td></tr><tr><td>`GIFT_CHAT`</td><td>open</td><td>`conversationId` isn't a one-to-one chat between you and the receiver</td></tr><tr><td>`GIFT_NOT_ACCEPTED`</td><td>can-send, open, pay</td><td>the receiver doesn't take gifts from you (their setting, or one of you blocked the other; the reason never says which). Typed number: "This number can't receive a gift from you"</td></tr><tr><td>`GIFT_MESSAGE_LINK`</td><td>open, pay</td><td>the message has a link</td></tr><tr><td>`DESIGN_UNAVAILABLE`</td><td>open, pay</td><td>design switched off or outside its dates</td></tr><tr><td>`DESIGN_KIND`</td><td>open, pay</td><td>design doesn't allow this kind</td></tr><tr><td>`GIFT_AMOUNT`</td><td>open, pay</td><td>not whole shillings</td></tr><tr><td>`GIFT_TOO_SMALL` / `GIFT_TOO_BIG`</td><td>open, pay</td><td>outside the range for this design and kind</td></tr><tr><td>`GIFT_QUANTITY`</td><td>open, pay</td><td>several cards for PRIVATE / SELF, or more than `maxCardsPerPurchase`</td></tr><tr><td>`GIFT_DAILY_LIMIT`</td><td>open, pay</td><td>over today's gift total</td></tr><tr><td>`GIFT_DAILY_CODE_LIMIT`</td><td>open, pay</td><td>over today's code total</td></tr><tr><td>`GIFTS_ON_HOLD`</td><td>open, pay, claim, redeem</td><td>the account's gifts are frozen</td></tr><tr><td>`INSUFFICIENT_BALANCE`</td><td>pay</td><td>wallet too low; reason says how much to top up</td></tr><tr><td>`CHECKOUT_CLOSED`</td><td>pay</td><td>session left or ended</td></tr><tr><td>`CHECKOUT_EXPIRED`</td><td>pay</td><td>over 15 minutes</td></tr><tr><td>`GIFT_CLOSED`</td><td>claim, decline, cancel, admin</td><td>the gift isn't waiting any more</td></tr><tr><td>`GIFT_EXPIRED`</td><td>claim, decline, cancel</td><td>past its 14 days (on its way back)</td></tr><tr><td>`GIFT_ON_HOLD`</td><td>claim, decline, cancel, redeem</td><td>the gift is frozen</td></tr><tr><td>`CANCEL_WINDOW_PASSED`</td><td>cancel</td><td>more than 24 h after buying</td></tr><tr><td>`CODE_NOT_FOUND`</td><td>redeem</td><td>no such code (counts as a wrong try)</td></tr><tr><td>`CODE_USED`</td><td>redeem</td><td>used, cancelled or returned</td></tr><tr><td>`CODE_EXPIRED`</td><td>redeem</td><td>past its 14 days</td></tr><tr><td>`CODE_TRIES_PAUSED`</td><td>redeem</td><td>too many wrong codes: paused</td></tr><tr><td>`CODE_CLOSED`</td><td>show code</td><td>the code isn't `ACTIVE` any more</td></tr><tr><td>`GIFT_BALANCE_CHANGED`</td><td>shop / event payment</td><td>gift balance went down under the payment; check again</td></tr><tr><td>`GIFT_NOT_FROZEN`</td><td>admin unfreeze</td><td>the gift isn't frozen</td></tr><tr><td>`DESIGN_FALLBACK`</td><td>admin design state</td><td>the NexGate card can't be switched off</td></tr><tr><td>`DESIGN_LIMITS` / `DESIGN_KINDS` / `DESIGN_DATES` / `DESIGN_PRESETS`</td><td>admin design</td><td>bad range / no kind / dates / presets</td></tr><tr><td>`DESIGN_IMAGE` / `DESIGN_IMAGE_NOT_READY` / `DESIGN_IMAGE_TYPE` / `DESIGN_IMAGE_CONTEXT`</td><td>admin design</td><td>picture missing / processing / not a picture / not uploaded as `GIFT_DESIGN`</td></tr><tr><td>`GIFT_NOT_HERE`</td><td>catalogue, moment send, card open / pay from a live</td><td>the live isn't on, the person isn't who can receive here, not your one-to-one chat</td></tr><tr><td>`GIFT_PLACE`</td><td>moment send, card open, admin items / settings</td><td>a place not built yet (`POST`); a card from a place where cards don't show; a public / self card with a place</td></tr><tr><td>`GIFT_ITEM_UNAVAILABLE`</td><td>moment send</td><td>the item is switched off, out of its dates, or not allowed in this place</td></tr><tr><td>`GIFT_ACCOUNT_NEW`</td><td>catalogue, moment send</td><td>the sender's account is younger than `momentMinAccountAgeDays`</td></tr><tr><td>`GIFT_KEY_REUSED`</td><td>moment send</td><td>this `idempotencyKey` was already used for a different gift</td></tr><tr><td>`GIFT_SELF`</td><td>moment send</td><td>a moment gift to yourself</td></tr><tr><td>`GIFT_DAILY_LIMIT`</td><td>moment send</td><td>over today's moment total (`momentDailyTotal`)</td></tr><tr><td>`ITEM_KEY` / `ITEM_KEY_TAKEN` / `ITEM_PRICE` / `ITEM_DATES` / `ITEM_ICON…`</td><td>admin items</td><td>key missing or taken / not whole shillings / dates / picture (as the design picture codes)</td></tr></tbody></table>

---

# Part 12 — Screens checklist

<table id="bkmrk-screen-calls-wallet-"><thead><tr><th>Screen</th><th>Calls</th></tr></thead><tbody><tr><td>Wallet</td><td>`/wallet/my-wallet` (Wallet) + `GET /wallet/gift` (Gift balance) · Gift history → `GET /wallet/gift/history`</td></tr><tr><td>Gift menu</td><td>tabs Received (6) · Sent (7) · My codes (8), chips from `counts` · **Buy a gift** · **Redeem a code** (14)</td></tr><tr><td>Buy a gift</td><td>`GET /gifts/designs` (1) → pick kind, design, amount, person / phone / quantity, message → open (2) → confirm (total, wallet balance) → pay (4)</td></tr><tr><td>After paying codes</td><td>the codes list from (4) with Copy / Share; "You can see them again in My codes"</td></tr><tr><td>One gift</td><td>`GET /gifts/{id}` (9) with buttons by the table in 9</td></tr><tr><td>Profile / chat "Send a gift"</td><td>`can-send` (30) first, then open (2) with `recipientId` (+ `conversationId` from a one-to-one chat)</td></tr><tr><td>Settings → Privacy</td><td>**Who can send me gifts** (31, 32)</td></tr><tr><td>Checkout pay screen</td><td>toggle **Use gift balance** (7.1), split from the balance check (7.2), `giftPaid` / `walletPaid` on the receipt (7.3)</td></tr><tr><td>Admin: Gifts</td><td>find (22), one (23), person (24), freeze / unfreeze (25, 27), return (26), needs decision (28), report (29)</td></tr><tr><td>Admin: Gift designs + settings</td><td>17–21</td></tr></tbody></table>

---

# Part 13 — Moment gifts (new in v1.1)

Spec: [`GIFT_SYSTEM_SPEC.md`](GIFT_SYSTEM_SPEC.md) §1a and §4.7.

## 13.0 How it works

```
                 ┌──────────── 🎁 GIFTS ────────────┐
     🎉 Moment gifts (this part)            💳 Gift cards (Parts 1–12)
     admin list: 🔥 Fire 1,000 · 🦁 Lion…   amount + design + message
     one tap, instant, no claim            claimed, 14-day return
                 └──────────► 💰 GIFT BALANCE ◄──────┘

```

- **A moment gift** is one item from an admin-made list (key, name, icon, price, size), sent in **one tap** to **one person**, from a **place**: `LIVE` (a live that is on; the receiver is the host), `CHAT` (a one-to-one chat; the receiver is the other person), `MEETING` (an open meeting you are in; the host, co-hosts and speakers receive, listeners only send) or `CALL` (a call that is on and you are in; the others in the call receive). Meetings and calls: the sender must be 18 or older, else the catalogue has no `receivers`. The money goes **straight from the sender's wallet into the receiver's gift balance**. Nothing to claim, never refunded, never cash.
- **Two switches.** Moment gifts have their own switch on top of the gift switch: with moments off, the catalogue lists no items and sending answers **404**. With gifts off, everything here answers 404.
- **The app plays the animation for `key`** (e.g. `fire`). An unknown key (a new admin item, an old app): show `icon`with a simple fly-up. `size` says how big to play it.
- **Ask the server what to show:** `GET /gifts/catalogue?place=&contextId=` (33) returns the items allowed here, whether the 💳 gift card tab shows, who can receive and what is left today. If `canSend` is false, grey the picker out and show `reason`.
- **Every tap gets its own `idempotencyKey`** (a UUID made by the app). A retry of the same tap sends the **same** key: the server returns the first gift and moves no money twice.
- **No PIN.** Prices are set by the admin; the daily limit (100,000 by default) caps the risk.
- **The price is kept.** A sent gift keeps the name and price it was sent at, even if the admin changes the item later.
- **No push per moment gift.** In a live the room sees it (13.6); in a chat the gift message is the notice.

**Example (live).** Juma is live, Neema watches.

1. Neema taps 🎁 → `GET /gifts/catalogue?place=LIVE&contextId=<streamId>` → 🔥 1,000 · 🌹 2,000 · 🦁 50,000 + 💳 tab; receiver Juma.
2. She taps 🔥 → `POST /gifts/moments` → her wallet −1,000, Juma's gift balance +1,000.
3. Everyone in the live gets a system comment `GIFT_MOMENT` with the gift's id → reads it (37) → plays 🔥 "Neema → Juma".

**Refused** (one answer, never which reason): Juma doesn't take gifts from Neema (his setting, a block, his gifts on hold) → `GIFT_NOT_ACCEPTED`; the live ended / Rose isn't the host / not your chat → `GIFT_NOT_HERE`.

## 33. What can I send here (catalogue)

**Purpose**: Everything the gift picker needs for one live or one chat.

**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}/gifts/catalogue`

**Access Level**: 🔒 Protected

**Authentication**: Bearer token

**Query Parameters**:

<table id="bkmrk-parameter-type-requi-15"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th><th>Default</th></tr></thead><tbody><tr><td>place</td><td>string</td><td>Yes</td><td>Where the picker is open</td><td>`LIVE`, `CHAT`, `MEETING`, `CALL` (`POST` refused for now)</td><td>—</td></tr><tr><td>contextId</td><td>UUID</td><td>Yes</td><td>`LIVE`: the streamId. `CHAT`: the conversationId of a one-to-one chat. `MEETING`: the meetingId. `CALL`: the callId</td><td>—</td><td>—</td></tr></tbody></table>

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Gifts here", "action_time": "2026-11-24T20:15:02",
  "data": {
    "place": "LIVE", "contextId": "7c1e…",
    "items": [
      { "id": "a1…", "key": "fire", "name": "Fire", "icon": { "fileId": "…", "status": "READY", "variants": { "thumb": "https://…" }, "mimeType": "image/webp" }, "price": 1000, "size": "SMALL" },
      { "id": "a2…", "key": "lion", "name": "Lion", "icon": { … }, "price": 50000, "size": "BIG" }
    ],
    "giftCards": true,
    "receivers": [ { "accountId": "3213…", "name": "Juma", "userProfileMedia": { … } } ],
    "leftToday": 99000,
    "canSend": true, "code": null, "reason": null
  }
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-it"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`items`</td><td>Moment gifts allowed here, in the admin's order. Empty when moment gifts are switched off</td></tr><tr><td>`giftCards`</td><td>Show the 💳 Gift card tab (opens checkout 2 with `place` + `contextId`, see 13.5)</td></tr><tr><td>`receivers`</td><td>Who can get a gift here; the first is the default. Only people who accept gifts from you</td></tr><tr><td>`leftToday`</td><td>TZS of moment gifts you can still send today</td></tr><tr><td>`canSend` / `code` / `reason`</td><td>`false` with a refusal code (`GIFT_ACCOUNT_NEW`, `GIFTS_ON_HOLD`, `GIFT_NOT_HERE`) when nothing can be sent; then `giftCards` is false too</td></tr></tbody></table>

## 34. Send a moment gift

**Purpose**: One tap: the money moves at once.

**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}/gifts/moments`

**Access Level**: 🔒 Protected

**Authentication**: Bearer token

**Request JSON Sample**:

```json
{ "itemId": "a1…", "receiverId": "3213…", "place": "LIVE", "contextId": "7c1e…", "idempotencyKey": "5b0e2c7a-…" }

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi-16"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>itemId</td><td>UUID</td><td>Yes</td><td>From the catalogue</td><td>—</td></tr><tr><td>receiverId</td><td>UUID</td><td>Yes</td><td>One of the catalogue's `receivers`</td><td>—</td></tr><tr><td>place</td><td>string</td><td>Yes</td><td>`LIVE`, `CHAT`, `MEETING` or `CALL`</td><td>—</td></tr><tr><td>contextId</td><td>UUID</td><td>Yes</td><td>streamId, conversationId, meetingId or callId</td><td>—</td></tr><tr><td>idempotencyKey</td><td>string</td><td>Yes</td><td>New for every tap; the same for a retry of that tap</td><td>≤ 64 chars</td></tr></tbody></table>

**Success Response JSON Sample** (the `GiftMoment` object):

```json
{
  "success": true, "httpStatus": "OK", "message": "Gift sent", "action_time": "2026-11-24T20:15:09",
  "data": {
    "id": "m9…", "itemKey": "fire", "itemName": "Fire", "icon": { … }, "size": "SMALL",
    "price": 1000, "quantity": 1, "amount": 1000,
    "from": { "accountId": "304e…", "name": "Neema", "userProfileMedia": { … } },
    "to":   { "accountId": "3213…", "name": "Juma",  "userProfileMedia": { … } },
    "place": "LIVE", "contextId": "7c1e…", "at": "2026-11-24T20:15:09"
  }
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-it-1"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`itemKey`, `itemName`, `price`, `amount`</td><td>As sent (kept even if the admin changes the item)</td></tr><tr><td>`icon`, `size`</td><td>From the item as it is now, for drawing</td></tr><tr><td>`quantity`</td><td>Always 1 for now (combos later)</td></tr></tbody></table>

**Refusals (409)**: `GIFT_SELF`, `GIFT_ITEM_UNAVAILABLE`, `GIFT_NOT_HERE`, `GIFT_NOT_ACCEPTED`, `GIFTS_ON_HOLD`, `GIFT_ACCOUNT_NEW`, `GIFT_DAILY_LIMIT`, `INSUFFICIENT_BALANCE`, `GIFT_KEY_REUSED`, `GIFT_PLACE` (Part 11).

## 35. Moment gifts I sent

**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}/gifts/moments/sent?page=0&size=20`

**Access Level**: 🔒 Protected

**Success Response JSON Sample**:

```json
{ "success": true, "httpStatus": "OK", "message": "Gifts sent", "action_time": "…",
  "data": { "moments": [ { "id": "m9…", "itemKey": "fire", "amount": 1000, "to": { … }, "place": "LIVE", "at": "…" } ],
            "count": 12, "total": 18000, "page": 0, "size": 20, "hasNext": false } }

```

`count` and `total` cover every gift sent, not only this page. `size` 1–100.

## 36. Moment gifts I received

**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}/gifts/moments/received?page=0&size=20`. Same shape as 35, with `from` filled.

## 37. One moment gift

**Purpose**: What the live overlay reads after a `GIFT_MOMENT` system comment (13.6), and what a chat card opens.

**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}/gifts/moments/{momentId}`

**Access Level**: 🔒 Protected. Anyone signed in for a gift sent in a live; only sender and receiver for a chat gift (others get 404).

**Success Response**: the `GiftMoment` object (34).

## 38–41. Admin: the moment gift list (super admin)

<table id="bkmrk-%23-method-endpoint-pu"><thead><tr><th>\#</th><th>Method</th><th>Endpoint</th><th>Purpose</th></tr></thead><tbody><tr><td>38</td><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span></td><td>`/admin/gifts/items`</td><td>All items, any state, in order</td></tr><tr><td>39</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span></td><td>`/admin/gifts/items`</td><td>Add an item</td></tr><tr><td>40</td><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span></td><td>`/admin/gifts/items/{itemId}`</td><td>Edit (the key never changes)</td></tr><tr><td>41</td><td><span style="background-color: #fd7e14; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span></td><td>`/admin/gifts/items/{itemId}/state`</td><td>`{ "active": false, "sortOrder": 3, "reason": "…" }` switch off / on, reorder</td></tr></tbody></table>

**Request JSON Sample (39, 40)**:

```json
{ "key": "fire", "name": "Fire", "iconFileId": "f1…", "price": 1000, "places": ["LIVE", "CHAT"], "size": "SMALL",
  "showFrom": null, "showUntil": null, "sortOrder": 1, "reason": "first gifts" }

```

<table id="bkmrk-parameter-type-requi-17"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>key</td><td>string</td><td>create only</td><td>What the app plays the animation for; fixed once created</td><td>`[a-z0-9_]{2,40}`, unique</td></tr><tr><td>name</td><td>string</td><td>Yes</td><td>Shown in the picker</td><td>≤ 60</td></tr><tr><td>iconFileId</td><td>UUID</td><td>create</td><td>Picture uploaded with context **`GIFT_DESIGN`**, processed (`READY`)</td><td>—</td></tr><tr><td>price</td><td>number</td><td>Yes</td><td>TZS</td><td>whole shillings, &gt; 0</td></tr><tr><td>places</td><td>array</td><td>No</td><td>Where it shows</td><td>`LIVE`, `CHAT`, `MEETING`, `CALL` (`POST` refused). **Create:** empty or left out = every place that works today. **Edit:** empty or left out = unchanged. To take an item out of meetings or calls, send the list without them</td></tr><tr><td>size</td><td>string</td><td>Yes</td><td>Animation size</td><td>`SMALL`, `MEDIUM`, `BIG`</td></tr><tr><td>showFrom / showUntil</td><td>datetime</td><td>No</td><td>Seasonal items</td><td>until after from</td></tr><tr><td>sortOrder, reason</td><td>—</td><td>No</td><td>Order; the reason goes into the admin audit</td><td>—</td></tr></tbody></table>

**Success Response**: the item `{ id, key, name, icon, price, places, size, active, showFrom, showUntil, sortOrder, createdAt, updatedAt }`. Items are **never deleted**, only switched off. Every change is in the admin audit (`GIFT_ITEM_CREATED`, `GIFT_ITEM_EDITED`, `GIFT_ITEM_STATE`).

**Refusals (409)**: `ITEM_KEY`, `ITEM_KEY_TAKEN`, `ITEM_ICON` (+ `_NOT_READY`, `_TYPE`, `_CONTEXT`), `ITEM_PRICE`, `ITEM_DATES`, `GIFT_PLACE`.

## 13.5 Changes to existing gift endpoints (fields only added)

<table id="bkmrk-endpoint-change-post"><thead><tr><th>Endpoint</th><th>Change</th></tr></thead><tbody><tr><td>`POST /gifts/checkout-sessions` (2)</td><td>+ optional `place` (`LIVE` / `CHAT`, or `MEETING` / `CALL` if the admin added them to `cardPlaces`) and `contextId`: a **private** card sent from a live (to the host, while it's on) or a chat. A `conversationId` alone still means "from that chat". Refusals: `GIFT_PLACE` (not private, or cards don't show in this place), `GIFT_NOT_HERE`</td></tr><tr><td>`GET /wallet/gift/history` (16)</td><td>+ `entries[].giftType`: `MOMENT` (type `GIFT_MOMENT`, a moment gift received), `CARD` (`GIFT_CLAIM`, `GIFT_LOAD`), empty for spending and refunds</td></tr><tr><td>`GET/PUT /admin/gifts/settings` (21)</td><td>+ `momentDailyTotal` (100,000), `momentMinAccountAgeDays` (3), `cardPlaces` (`["LIVE","CHAT"]`, where the 💳 tab shows; `MEETING` and `CALL` may be added)</td></tr><tr><td>`GET /admin/gifts/report` (29)</td><td>+ `moments`: `{ count, total, byItem: [{ key, name, count, total }], topReceivers: [{ person, count, total }] }` since `from`</td></tr><tr><td>`GET /admin/gifts/people/{accountId}` (24)</td><td>+ `moments`: `{ sentCount, sentTotal, receivedCount, receivedTotal, recent: [GiftMoment…] }`</td></tr><tr><td>Wallet transaction history</td><td>new types `GIFT_MOMENT_SENT` (debit) and `GIFT_MOMENT_RECEIVED` (credit)</td></tr></tbody></table>

## 13.6 In a live, a chat, a meeting and a call

- **Live:** after a moment gift or a gift card bought in a live, every viewer's comment stream gets a **system comment**: `{ "system": true, "event": "GIFT_MOMENT", "refId": "<momentId>" }` (read it with 37) or `{ "system": true, "event": "GIFT_CARD", "refId": "<giftId>" }` ("Juma sent Mama Yoyo a gift card 💳"; the host claims it as usual). Today through the 2-second comment read; through Centrifugo after the live revamp.
- **Chat:** a new message type **`GIFT_MOMENT`** in the one-to-one chat, written as the sender, metadata `{ momentId, amountMinor, currency, itemKey, itemName }`. Its card: `kind GIFT`, `labelKey "card.gift_moment"`, title = item name, amount, `status "RECEIVED"`, target `GIFT_MOMENT` + momentId, details `{ momentId, itemKey, size, forMe }`. Nothing to answer: the money is already in the receiver's gift balance. The chat list preview is "🎁 Gift".
- **Meeting / call:** everyone in the room gets the room message `GIFT_MOMENT` with `itemId` = the momentId (read it with 37, play the animation for `itemKey`). No chat message, no push. Details in the calls &amp; meetings doc, F12.

## 13.7 Screens checklist (moment gifts)

<table id="bkmrk-screen-calls-live%3A-%F0%9F%8E%81"><thead><tr><th>Screen</th><th>Calls</th></tr></thead><tbody><tr><td>Live: 🎁 button</td><td>`GET /gifts/catalogue?place=LIVE&contextId=<streamId>` → tap an item → `POST /gifts/moments` (new key per tap) · 💳 tab → checkout 2 with `place=LIVE`</td></tr><tr><td>Live: overlay</td><td>on a `GIFT_MOMENT` system comment → `GET /gifts/moments/{id}` → play the animation for `itemKey` · `GIFT_CARD` → "💳 gift card" line</td></tr><tr><td>Chat: 🎁 button</td><td>`GET /gifts/catalogue?place=CHAT&contextId=<conversationId>` → moment items + 💳 tab (checkout 2 with `conversationId`)</td></tr><tr><td>Meeting / call: 🎁 button</td><td>`GET /gifts/catalogue?place=MEETING&contextId=<meetingId>` (or `place=CALL&contextId=<callId>`) → tap an item → `POST /gifts/moments` · on the room message `GIFT_MOMENT {itemId: momentId}` → `GET /gifts/moments/{id}` → play the animation (calls &amp; meetings doc, F12)</td></tr><tr><td>Gift menu</td><td>new tabs **Moments sent** (35) / **Moments received** (36)</td></tr><tr><td>Admin: Moment gifts</td><td>38–41; settings (21) for the daily limit, account age and card places</td></tr></tbody></table>

# 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

<table id="bkmrk-juma%27s-first-complet"><thead><tr><th>Juma's first completed order</th><th>Asha gets</th></tr></thead><tbody><tr><td>25,000 of items at Tech Shop, 5 days after joining</td><td>the thank-you coupon 7 days later ✅</td></tr><tr><td>15,000 (the minimum is 20,000)</td><td>nothing: "His first order was under 20,000" ❌</td></tr><tr><td>at Asha's own shop (or a shop where she is staff)</td><td>nothing: "His first order was at your own shop" ❌</td></tr><tr><td>refunded within the 7 days</td><td>nothing: "His first order was refunded or cancelled" ❌</td></tr><tr><td>Asha already earned 10 rewards this month</td><td>nothing: "Monthly limit of 10 rewards reached" ❌</td></tr><tr><td>Juma signed in on Asha's phone</td><td>the code is refused at the code step ❌</td></tr></tbody></table>

---

## 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 }
  }
}

```

<table id="bkmrk-field-description-co"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`code`, `link`</td><td>Always shown (Copy / Share). The code is random and never changes</td></tr><tr><td>`canInvite` / `whyNot`</td><td>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")</td></tr><tr><td>`rewardDiscount`</td><td>What one thank-you coupon is worth: "rewards earned 4 × 5,000 off"</td></tr><tr><td>`numbers`</td><td>`signedUp` friends who used the code; `bought` their first order completed (or later); `rewarded`; `waiting` for a first order; `notRewarded`</td></tr></tbody></table>

---

## 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
}

```

<table id="bkmrk-state-show-signed_up"><thead><tr><th>State</th><th>Show</th></tr></thead><tbody><tr><td>`SIGNED_UP`</td><td>"Waiting for their first order"</td></tr><tr><td>`ORDER_COMPLETED`</td><td>"Bought! Your reward comes on {rewardOn}"</td></tr><tr><td>`IN_REVIEW`</td><td>"Being checked"</td></tr><tr><td>`REWARDED`</td><td>"Reward earned" (the coupon is in My coupons)</td></tr><tr><td>`NOT_REWARDED`</td><td>the `reason`</td></tr></tbody></table>

---

## 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" }

```

<table id="bkmrk-parameter-type-requi"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Validation</th></tr></thead><tbody><tr><td>code</td><td>string</td><td>Yes</td><td>the code or the whole link (`https://nexgate.co/r/K7P2QX4M`); any case</td></tr></tbody></table>

**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": "…"
}

```

<table id="bkmrk-setting-start-with-m"><thead><tr><th>Setting</th><th>Start with</th><th>Meaning</th></tr></thead><tbody><tr><td>`programmeOn`</td><td>false</td><td>the whole programme</td></tr><tr><td>`minFirstOrder`</td><td>20,000</td><td>items of the friend's first order (before coupons)</td></tr><tr><td>`firstOrderDays`</td><td>30</td><td>the first order must be placed within this many days of joining</td></tr><tr><td>`rewardDelayDays`</td><td>7</td><td>days after completion before the reward</td></tr><tr><td>`useCodeDays`</td><td>7</td><td>the code step is open this long after sign-up</td></tr><tr><td>`monthlyCap`</td><td>10</td><td>rewards per inviter per calendar month</td></tr><tr><td>`welcomeValidDays` / `thankYouValidDays`</td><td>14 / 30</td><td>how long each person has to use their coupon</td></tr><tr><td>`welcomeCouponId` / `thankYouCouponId`</td><td>—</td><td>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</td></tr></tbody></table>

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)

<table id="bkmrk-type-when-text-opens"><thead><tr><th>Type</th><th>When</th><th>Text</th><th>Opens</th></tr></thead><tbody><tr><td>`REFERRAL_FRIEND_JOINED`</td><td>a friend used the code</td><td>🎉 Juma joined with your code · You get 5,000 off when they complete their first order</td><td>Invite friends</td></tr><tr><td>`REFERRAL_FRIEND_BOUGHT`</td><td>the friend's first order completed</td><td>Juma bought! · Your reward comes on 5 Dec</td><td>Invite friends</td></tr><tr><td>`REFERRAL_REWARD_EARNED`</td><td>reward given (instead of `COUPON_RECEIVED`)</td><td>🎁 You earned 5,000 off for inviting Juma · Use by 4 Jan</td><td>My coupons</td></tr><tr><td>`REFERRAL_REWARD_HELD`</td><td>a warning sign (in-app only)</td><td>Your reward for inviting Juma is being checked · We'll let you know</td><td>Invite friends</td></tr><tr><td>`REFERRAL_REWARD_MISSED`</td><td>no reward (in-app only)</td><td>No reward for inviting Juma · {the reason}</td><td>Invite friends</td></tr><tr><td>`REFERRAL_CODE_REMOVED`</td><td>removed by an admin</td><td>Your invite code has been switched off · {reason}. Contact support if this is a mistake.</td><td>Invite friends</td></tr><tr><td>`REFERRAL_REVIEW_WAITING`</td><td>08:00 daily while rewards wait (admins)</td><td>4 referral rewards are waiting for review · Oldest waiting 2 days</td><td>admin review</td></tr></tbody></table>

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)

<table id="bkmrk-code-when-referral_p"><thead><tr><th>Code</th><th>When</th></tr></thead><tbody><tr><td>`REFERRAL_PAUSED`</td><td>the programme is off</td></tr><tr><td>`REFERRAL_CODE_NOT_FOUND`</td><td>no such code, or it was switched off</td></tr><tr><td>`REFERRAL_TRIES_PAUSED`</td><td>5 wrong codes: paused</td></tr><tr><td>`REFERRAL_OWN_CODE`</td><td>your own code</td></tr><tr><td>`REFERRAL_TOO_LATE`</td><td>more than 7 days after sign-up, or after the first order</td></tr><tr><td>`REFERRAL_INVITER_NOT_READY`</td><td>the inviter has no completed order yet</td></tr><tr><td>`REFERRAL_SAME_DEVICE`</td><td>used on the inviter's own phone</td></tr><tr><td>`REFERRAL_ALREADY_USED`</td><td>a different code was used before (one inviter, never changed)</td></tr><tr><td>`REFERRAL_COUPON_INVALID`</td><td>admin: the reward must be a NexGate coupon</td></tr></tbody></table>

---

# Part 6 — Web page and installs (not backend)

- `nexgate.co/r/` (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

<table id="bkmrk-screen-calls-me-%E2%86%92-in"><thead><tr><th>Screen</th><th>Calls</th></tr></thead><tbody><tr><td>Me → Invite friends</td><td>1 (code, link, Copy, Share, numbers or why not yet) · friends list 2</td></tr><tr><td>After sign-up</td><td>link code → 4 then 3 automatically; else "Have an invite code?" (type → 4 → 3, or skip); hide after 7 days or the first order</td></tr><tr><td>My coupons</td><td>the welcome / thank-you coupons (coupon API)</td></tr><tr><td>Admin → Referrals</td><td>settings 5–6, report 7, review 8–10, person 11, remove / restore 12–13</td></tr></tbody></table>