# Frontend Change Log — 2026-11-28

**Author**: Josh S. Sakweli, Backend Lead Team  
**Last Updated**: 2026-11-28  
**Version**: v1.0 (covers 2026-11-17 to 2026-11-27: the ten change logs of those days in one file, in date order)

**Short Description**: Everything the apps see change since 2026-11-17, one Part per change log, oldest first. Each Part keeps
its own version line. Later Parts win where two disagree (e.g. a field added in Part 3 and changed in Part 5). Full shapes
are in each feature's API doc.

## Contents

| Part | Date | What |
|---|---|---|
| [1](#part-1) | 2026-11-17 | Calls about a parcel, who is bringing it |
| [2](#part-2) | 2026-11-19 | Team pictures as media objects |
| [3](#part-3) | 2026-11-21 | Gift, coupons, referral, contact discovery |
| [4](#part-4) | 2026-11-24 | Moment gifts, tickets in posts, meeting and call fixes |
| [5](#part-5) | 2026-11-25 | Live revamp |
| [6](#part-6) | 2026-11-25 | No more SSE: everything on Centrifugo |
| [7](#part-7) | 2026-11-26 | Calls & meetings revamp |
| [8](#part-8) | 2026-11-26 | Where an online event happens |
| [9](#part-9) | 2026-11-27 | Night build: events, live fan-out, volume pricing, sale origins |
| [10](#part-10) | 2026-11-27 | Voice OTP |

---

<a id="part-1"></a>
# Part 1 — 2026-11-17 · Calls about a parcel, who is bringing it

**Author**: Josh S. Sakweli, Backend Lead Team  
**Version**: v1.0

**Short Description**: Who is bringing the parcel, and voice calls about a parcel between the buyer, the shop and whoever
delivers it. **Nothing here is breaking**: fields were only added, no field changed shape or was removed.

---

### 1. Order details: who is bringing it

**ADDED** `fulfillment.shippers[].assignedTo`, on every order response that already carries `fulfillment`.

```json
"shippers": [
  { "leg": 0, "businessId": "…", "name": "EMS Courier", "phone": "+255…",
    "assignedTo": { "accountId": "…", "name": "Mama Yoyo", "userProfileMedia": { "fileId": "8c2e…", "status": "COMPLETED", "thumbUrl": "https://…/thumb.jpg", "mimeType": "image/jpeg" } } }
]
```

- The person the shipper assigned to that leg; **absent** while nobody is assigned (the shipper itself is delivering).
  It follows the job: moved to Juma → Juma.
- Buyer: "Mama Yoyo · EMS Courier is delivering". Shop: "Mama Yoyo · EMS Courier is coming to collect".
- **Never the assigned person's phone number.** To reach them, use the NexGate call (section 2). `phone` is still the
  business's.
- Pictures follow the standard: `userProfileMedia` (`fileId`, `status`, `thumbUrl`, `mimeType`), never a bare URL.

### 2. Calls about a parcel (new)

Voice calls between the **buyer**, the **shop** and **whoever delivers** one order, open from the moment a shipper
accepts until the order is **completed or cancelled**. Full API: `docs/team/api/nexgate_app_team_api.md` Part 8.

**NexGate app (buyer):** on the order page show **two buttons**:
- **Call shop**: unchanged, `POST /calls` with `targetShopId` (any time).
- **Call delivery** (only while the delivery is going on): `POST /work-calls` with `{ "orderId": "…", "to": "DELIVERY" }`.
  It rings the shipper: the person assigned to the job now, or the shipper itself. The answer carries the room token and `calling` (who is
  being rung) and `allLinesBusy` ("Everyone is on another call. Please wait, or call back later").

**NexGate app (shop owner):** the same **Call delivery** with `"shopId"` added, to call as the shop.

**Who is on the other side** (`calling`, `other`, `caller` in every call response):

```json
{ "role": "SHIPPER", "name": "EMS Courier", "businessLogoMedia": { … },
  "assignedTo": { "accountId": "3213…", "name": "Mama Yoyo", "userProfileMedia": { "fileId": "8c2e…", "status": "COMPLETED", "thumbUrl": "https://…/thumb.jpg", "mimeType": "image/jpeg" } },
  "orderNumber": "ORD-2026-23424", "parcelNumber": "NX-SQAW-ZL", "orderId": "0f05…" }
```

`role` is `BUYER`, `SHOP` or `SHIPPER`. A shipper is always the business; `assignedTo` is the person it assigned to the
job (absent when the business itself is on the call). Pictures: `userProfileMedia`, `shopLogoMedia`, `businessLogoMedia`.

**Calls list:** `GET /work-calls` (my calls as a buyer) or `GET /work-calls?shopId=` (the shop's). Each row has `other`
(who), `missed`, and `callBack` (what to send as `to` to call back; absent once the order's calls are closed).
**Work calls do not appear in `GET /calls`**, which stays chat calls only: show both lists, or merge them by time.

**Answer / hang up:** `POST /work-calls/{callId}/join` and `/end` (`?shopId=` when acting as the shop).

### 3. Caller identification on rings

**ADDED, all optional,** to the `CALL_INCOMING` / `CALL_ENDED` pushes and the `call.incoming` live event
(`docs/notifications/push_contracts_api_doc.md` v1.3 §4.2, §4.3, §4.8). Ordinary chat calls look exactly as before.

| Key | Meaning |
|---|---|
| `work` | `"true"` = a call about a parcel (no chat behind it, no `conversationId`) |
| `answerAs` | `ME` (token included, answer at once), `SHOP` or `BUSINESS` (no token: answer with the join endpoint, first one wins) |
| `shopId`, `shopName` | a call to the shop; now also reach the owner's phone (they were dropped before) |
| `callerRole` | `BUYER`, `SHOP`, `SHIPPER` (the delivery business) |
| `callerName`, `callerAvatar` | the buyer, the shop, or the shipper (business name and logo) |
| `assignedToAccountId`, `assignedToName`, `assignedToAvatar` | `SHIPPER` only: the person the shipper assigned to the job, who is calling |
| `parcelNumber` | always on a work call |
| `orderNumber`, `orderId` | **only to the buyer and the shop**, never to a shipper |

Draw the line yourselves, e.g. "EMS Courier · Mama Yoyo · order ORD-2026-23424". The server sends fields,
never a sentence.

### 4. New notifications

- `ORDER_MISSED_CALL` (bell + push, opens the order): "Missed call about order ORD-…", with `caller.name`, `call.time`,
  `orderNumber`, `parcelNumber`.
- Shipper app only: `WORK_CALL_INCOMING`, `WORK_CALL_ENDED`, `WORK_CALL_MISSED`.

### 5. Errors you may see on `POST /work-calls`

All `409` with a `code`: `NO_SHIPPER_YET` (no shipper accepted yet), `CALLS_CLOSED` ("This delivery is finished"),
`BUSY` (they are on another call), `USE_SHOP_CALLS` (buyer ↔ shop goes through `POST /calls`), `SAME_PERSON` /
`OWN_SHOP` / `OWN_BUSINESS` (nobody else would answer: e.g. buying from your own shop), `NOT_ON_THIS_ORDER`.

---

<a id="part-2"></a>
# Part 2 — 2026-11-19 · Team pictures as media objects

**Author**: Josh S. Sakweli, Backend Lead Team  
**Version**: v1.0

**Short Description**: Team screens now send people's pictures as the standard media object, like the rest of the
platform, instead of a bare link. **This is breaking** for the responses below: the old field is gone.

---

### 1. Pictures in team responses

**CHANGED** `avatarUrl` (a bare link) → `userProfileMedia`; on missed shop calls `customerAvatar` → `customerProfileMedia`.

```json
"userProfileMedia": { "fileId": "8c2e…", "status": "COMPLETED", "thumbUrl": "https://…/thumb.jpg", "mimeType": "image/jpeg" }
```

`null` when the person has no picture (or, on a phone invite, before it is accepted).

| Where | Old field | New field |
|---|---|---|
| Team members: `GET /team/shops/{shopId}/members`, `GET /team/businesses/{businessId}/members`, invites, `GET /team/me` | `avatarUrl` | `userProfileMedia` |
| Who's working? (faces): `GET /team/terminal/faces`, the faces on a computer's details, the person greeted after a PIN | `avatarUrl` | `userProfileMedia` |
| Who can carry it: `GET /shipping/businesses/{businessId}/riders` | `avatarUrl` | `userProfileMedia` |
| A job's `assignee` (`GET /shipping/jobs/{id}` and job lists) | `avatarUrl` | `userProfileMedia` |
| Missed calls to the shop: `GET /team/shops/{shopId}/calls/missed` | `customerAvatar` | `customerProfileMedia` |

Show the picture from `thumbUrl` while `status` is `COMPLETED`; otherwise show the initials, as everywhere else.

Full shapes: `docs/team/api/` (NexGate app, shipper app, terminal app docs).

---

<a id="part-3"></a>
# Part 3 — 2026-11-21 · Gift, coupons, referral, contact discovery

**Author**: Josh S. Sakweli, Backend Lead Team  
**Version**: v1.0

**Short Description**: Everything built since 2026-11-19 that **touches something that already existed**: endpoints,
responses, notifications, refusals, chat. Four new features: **Gift**, **Coupons**, **Referral**, **Contact discovery**.
Each is behind its own switch, **off by default**. With a switch off, nothing in its section appears or changes.
**Nothing here is breaking**: every change adds an optional field or a new endpoint; no field was removed or renamed in
anything the apps already use.

| Feature | Switch | Full API doc |
|---|---|---|
| Gift | `app.gift.enabled` | `docs/gift/gift_api_doc.md` |
| Coupons | `app.coupons.enabled` | `docs/coupons/coupon_api_doc.md` |
| Referral | `app.referral.enabled` + the programme's own on/off (admin) | `docs/referral/referral_api_doc.md` |
| Contact discovery | `app.contacts.enabled` | `docs/contacts/contact_api_doc.md` |

Backend detail of each change: `commerce_logistics_changes.md` §15–§18.

---

### 1. Checkout (products and events)

**ADDED** optional request fields. Leave them out and checkout works exactly as before.

| Endpoint | New optional fields | Feature |
|---|---|---|
| `POST /e-commerce/checkout-sessions` (buy now, cart, group buy, chat offer) | `useGiftBalance` (missing = on), `nexgateCouponId`, `shopCouponIds` (buy now and cart) | Gift, Coupons |
| `PATCH /e-commerce/checkout-sessions/{id}` | `useGiftBalance`, `nexgateCouponId`, `removeCoupon`, `shopCouponIds` (`[]` removes) | Gift, Coupons |
| `POST /e-events/checkout` | `useGiftBalance`, `nexgateCouponId`, `eventCouponId` | Gift, Coupons |

**ADDED** response fields on the checkout session:

```json
"pricing": { "subtotal": 50000, "shopDiscount": 5000, "total": 47000 },
"shopCoupons": [ { "couponId": "…", "shopId": "…", "discount": 5000, "byPart": [ … ] } ],
"nexgateCouponId": "…", "couponDiscount": 3000, "amountToPay": 44000
```

- `pricing.shopDiscount` is **already taken off** `pricing.total` (the shop pays it).
- `couponDiscount` (NexGate coupon) is paid by NexGate: `amountToPay` = total − NexGate coupon.
- Instalments ignore gift and coupons (wallet only).

**CHANGED** the balance check at checkout creation (`INSUFFICIENT_BALANCE`): wallet **+ gift balance** ≥ total **−
NexGate coupon** (the shop / organiser coupon is already off the total).

---

### 2. Wallet and payment

| Where | Added |
|---|---|
| `GET /wallet/checkout-balance-check` | `giftBalance`, `giftPart` (what the gift will pay), `couponDiscount`; `shortfall` counts both |
| Payment response (`process-payment`, event `payment`) | `giftPaid`, `couponDiscount`, `walletPaid` (= total − gift − coupon: what left the wallet) |
| Transaction history | new types `GIFT_SPENT`, `GIFT_REFUNDED` |
| **New** | `GET /wallet/gift` (gift balance), `GET /wallet/gift/history` |

`/wallet/my-wallet` keeps its shape. A coupon that no longer applies at payment refuses the payment (409 with its code:
see §6).

---

### 3. Orders and refunds

| Where | Before | After |
|---|---|---|
| `GET /e-commerce/orders/{id}` | … | + `discount` (shop coupon), `coupon` (NexGate coupon: code, title, discount, returnedToCoupon) |
| Order amounts with a shop coupon | total = items + delivery + tax | total = items − `discount` + delivery + tax |
| `ESCROW_REFUNDED` notification data | `amount` = back to the wallet | + `refund.total`, `refund.toGift`, `refund.toWallet`, `refund.coupon`; body adds "· The TZS X coupon used on this order is not returned" |

A refund paid partly from a gift goes back to the gift balance for that part; a refund that is all gift now notifies too.

---

### 4. Notifications

| Type | Change |
|---|---|
| `COUPON_RECEIVED` | text is now the ready-made `{{coupon.headline}}` (same words as before by default; the referral welcome has its own) |
| `ESCROW_REFUNDED` | see §3 |
| **New** gift types | `GIFT_*` (received, claimed, reminders, refunds …): see the gift API doc |
| **New** coupon types | `COUPON_*` (received, ending, ended, ran out, pot low, new for followers) |
| **New** referral types | `REFERRAL_FRIEND_JOINED`, `REFERRAL_FRIEND_BOUGHT`, `REFERRAL_REWARD_EARNED`, `REFERRAL_REWARD_HELD`, `REFERRAL_REWARD_MISSED`, `REFERRAL_CODE_REMOVED`, `REFERRAL_REVIEW_WAITING` (admins) |
| **New** contact types | `CONTACT_JOINED` (text `{{joined.headline}}`, single or grouped), `ADMIN_CONTACT_ABUSE` (admins) |
| **New** chat type | `CHAT_MESSAGE_REQUEST` (never the message text) |
| **New** deep-link targets | `MY_COUPONS`, `INVITE_FRIENDS`, `ADMIN_COUPON`, `ADMIN_REFERRAL_REVIEW`, `ADMIN_CONTACTS_STOPPED`, `MESSAGE_REQUESTS` (+ the gift targets); unknown target → bell list, as always |

---

### 5. Chat (contact discovery)

**CHANGED** (switch on only) what "contacts" means in chat: **follow each other OR both saved each other's number**.

| Where | Before | After |
|---|---|---|
| Chat contact list / presence | follow each other | + both saved each other's number |
| Group setting "Only my contacts can add me" | follow each other | + both saved each other's number |
| Blocks | win | still win over everything |

**Message requests** (switch `app.message-requests.enabled`): private chat and private calls only between chat contacts
(follow each other, both saved each other's number, or an accepted request); everyone else sends a message request.
Business chat with shops and work calls are unchanged. Full doc: `docs/contacts/message_requests_api_doc.md`.

| Where | Before | After (switch on) |
|---|---|---|
| A one-to-one XMPP message to someone who isn't a chat contact | delivered | not kept; the existing `DELIVERY_FAILED` system message arrives with **new reason `NOT_A_CONTACT`**: mark the bubble failed, offer "Send as a message request" |
| `POST /calls` to a person who isn't a chat contact | rings | 409 `CALL_NOT_CONTACT` |
| Adding someone to a private call | the initiator can add anyone | only the initiator's chat contacts (409 `CALL_NOT_CONTACT`) |
| Personal chats where both had already written | — | keep working ("You've chatted before") |

**New:** `GET /chat/message-to/{accountId}` (what to do when Message is tapped), `/chat/message-requests…` (send, list,
sent, open, accept, delete, settings), `GET /chat/contacts` (the new-chat list ready to show), notification
`CHAT_MESSAGE_REQUEST` (target `MESSAGE_REQUESTS`, never the message text).

---

### 6. New refusal codes (HTTP 409, `data.code` + `data.reason`; show the reason)

| Feature | Codes |
|---|---|
| Gift | `GIFT_NOT_ACCEPTED` (the receiver doesn't take gifts from you), `GIFT_MESSAGE_LINK` (no links in the message), `GIFT_DAILY_CODE_LIMIT`, `GIFTS_ON_HOLD`, … (gift API doc) |
| Coupons | `COUPON_RAN_OUT` and the `COUPON_*` codes (coupon API doc) |
| Referral | `REFERRAL_PAUSED`, `REFERRAL_CODE_NOT_FOUND`, `REFERRAL_TRIES_PAUSED`, `REFERRAL_OWN_CODE`, `REFERRAL_TOO_LATE`, `REFERRAL_INVITER_NOT_READY`, `REFERRAL_SAME_DEVICE`, `REFERRAL_ALREADY_USED` |
| Contacts | `CONTACTS_DAILY_LIMIT`, `CONTACTS_SYNC_OFF`, `CONTACTS_STOPPED` |
| Message requests / calls | `MESSAGE_REQUEST_NOT_NEEDED`, `MESSAGE_REQUEST_FROM_THEM`, `MESSAGE_REQUEST_NOT_ALLOWED`, `MESSAGE_REQUEST_FULL`, `MESSAGE_REQUEST_DAILY_LIMIT`, `CALL_NOT_CONTACT` |

---

### 7. New endpoints (full shapes in each API doc)

| Feature | Endpoints |
|---|---|
| Gift | `/gifts/…` buy, send, claim, my gifts, `GET /gifts/can-send`, `GET/PUT /gifts/me/preferences` ("Who can send me gifts": Everyone / People I follow / Nobody); admin `/admin/gifts/…` |
| Coupons | `/coupons/…` (shown, collect, redeem code, mine), `/shops/{shopId}/coupons/…`, `/events/{eventId}/coupons/…`; admin `/admin/coupons/…` |
| Referral | `GET /referrals/me`, `GET /referrals/me/friends`, `GET /referrals/codes/{code}`, `POST /referrals/use-code`; admin `/admin/referrals/…` |
| Contacts | `POST/PATCH /contacts/sync`, `GET /contacts/on-nexgate`, `DELETE /contacts`, `GET/PUT /contacts/settings`, `GET /feed/people/suggested?page&size` (also the whole Find friends page), `POST /feed/people/suggested/follow-all`, `POST /feed/people/suggested/{id}/dismiss`; admin `/admin/contacts/…` |
| Chat | `GET /chat/message-to/{accountId}`, `/chat/message-requests…`, `GET /chat/contacts` |

---

### 8. Media

Gift design pictures follow the media standard (`fileId`, `status`, `thumbUrl`, `mimeType`), assembled at response
time. They are uploaded to File Thunder with the new context **`GIFT_DESIGN`**.

---

### 9. Privacy notes for the apps

- **Gift to a typed phone number:** the owner's name is **never shown** before the gift is claimed (only the masked number).
- **Contacts:** send numbers only, never names; normalise to `+255…` on the phone; never log numbers in app analytics.
- **Referral and contacts:** toward other people, only first names / the person's own NexGate name are shown.

---

<a id="part-4"></a>
# Part 4 — 2026-11-24 · Moment gifts, tickets in posts, meeting and call fixes

**Author**: Josh S. Sakweli, Backend Lead Team  
**Version**: v1.0

**Short Description**: Everything built since the 2026-11-21 change log. Two areas:
1. **Moment gifts**: small animated gifts (🔥, 🌹, 🦁…) sent in one tap in a **live** or a **one-to-one chat**, straight into
   the receiver's gift balance, next to the gift cards that already exist. Behind **two switches**, both **off by
   default**: `app.gift.enabled` and `app.gift.moments.enabled`. With either off, nothing in §1–§4 appears.
2. **Posts and clips**: a post can now show **ticket groups** and **ticket types** (like products and product groups),
   and only things people can still act on can be attached. **No switch**: this is live as soon as it's deployed.

**Nothing here removes or renames anything the apps already read.** One behaviour change: attaching a product group
that is full or has ended is now **refused** (§5.3); before, it was accepted.

| Area | Switch | Full API doc |
|---|---|---|
| Moment gifts | `app.gift.enabled` + `app.gift.moments.enabled` | `docs/gift/gift_api_doc.md` **Part 13** (endpoints 33–41) |
| Posts and clips | none | this file (§5) |

Backend detail: `commerce_logistics_changes.md` §15a (moment gifts). Design: `docs/gift/GIFT_SYSTEM_SPEC.md` §1a, §4.7.

---

### 1. Moment gifts: how it works (new)

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

- **Places:** `LIVE` (a live that is on; the receiver is the host) and `CHAT` (a one-to-one chat; the receiver is the
  other person). `POST` and `MEETING` exist in the enum but are refused for now.
- **Ask the server what to show** before drawing the gift picker: `GET /gifts/catalogue?place=&contextId=` (items allowed
  here, whether the 💳 gift card tab shows, who can receive, what's left today). If `canSend` is `false`, grey the picker
  out and show `reason`.
- **One tap = one `idempotencyKey`** (a new 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.
- **The app plays the animation for `itemKey`** (e.g. `fire`); `size` says how big (`SMALL`, `MEDIUM`, `BIG`). Unknown key
  (a new admin item, an old app) → show `icon` with a simple fly-up.
- **No push per moment gift.** In a live the room sees it (§3); in a chat the gift message is the notice.

---

### 2. Moment gifts: new endpoints

| # | Method | Endpoint | Purpose |
|---|---|---|---|
| 33 | `GET` | `/gifts/catalogue?place=LIVE\|CHAT&contextId=` | What the picker shows here |
| 34 | `POST` | `/gifts/moments` | Send: `{ itemId, receiverId, place, contextId, idempotencyKey }` |
| 35 | `GET` | `/gifts/moments/sent?page&size` | My moment gifts sent (+ `count`, `total` over all) |
| 36 | `GET` | `/gifts/moments/received?page&size` | Received |
| 37 | `GET` | `/gifts/moments/{momentId}` | One gift (the live overlay reads it; chat cards open it) |
| 38–41 | `GET/POST/PUT/PATCH` | `/admin/gifts/items`, `/{itemId}`, `/{itemId}/state` | Admin: the moment gift list (super admin) |

Full request and response samples: gift API doc Part 13.

**Before → after: sending from a live**

```mermaid
sequenceDiagram
    participant App as Neema's app
    participant API as Backend
    participant Room as Live comments
    App->>API: GET /gifts/catalogue?place=LIVE&contextId=<streamId>
    API-->>App: items (fire, lion), giftCards true, receivers [Juma], leftToday
    App->>API: POST /gifts/moments {itemId, receiverId: Juma, place LIVE, contextId, idempotencyKey}
    API-->>App: GiftMoment (money moved: Neema's wallet −1000, Juma's gift balance +1000)
    API->>Room: system comment {event: GIFT_MOMENT, refId: momentId}
    Room-->>App: every viewer reads it, GET /gifts/moments/{id}, plays 🔥
```

---

### 3. Moment gifts: changes to existing things

| Where | Before | After (switches on) |
|---|---|---|
| `POST /gifts/checkout-sessions` | `conversationId` for a card from a chat | **ADDED** optional `place` (`LIVE` / `CHAT`) + `contextId`: a **private** gift card sent from a live (to the host, while the live is on) or a chat. A `conversationId` alone still works as before |
| `GET /wallet/gift/history` | `entries[]` `{ entryId, type, amount, description, at }` | **ADDED** `entries[].giftType`: `MOMENT` (type `GIFT_MOMENT`, a moment gift received), `CARD` (`GIFT_CLAIM`, `GIFT_LOAD`), empty for spending and refunds |
| Transaction history | — | **ADDED** types `GIFT_MOMENT_SENT` (debit), `GIFT_MOMENT_RECEIVED` (credit) |
| Live comments (the 2-second read) | system events | **ADDED** events `GIFT_MOMENT` (refId = momentId) and `GIFT_CARD` (refId = giftId: "Juma sent Mama Yoyo a gift card 💳") |
| Chat message types | … `GIFT_REF` … | **ADDED** `GIFT_MOMENT` (see §4) |
| `GET/PUT /admin/gifts/settings` | card limits | **ADDED** `momentDailyTotal` (100,000), `momentMinAccountAgeDays` (3), `cardPlaces` (`["LIVE","CHAT"]`: where the 💳 tab shows) |
| `GET /admin/gifts/report` | cards | **ADDED** `moments`: `{ count, total, byItem[], topReceivers[] }` |
| `GET /admin/gifts/people/{accountId}` | balance, history | **ADDED** `moments`: `{ sentCount, sentTotal, receivedCount, receivedTotal, recent[] }` |

---

### 4. Moment gifts in a chat

**ADDED** message type **`GIFT_MOMENT`** in a one-to-one chat, written as the sender.

- Metadata: `{ momentId, amountMinor, currency, itemKey, itemName }`.
- 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.
- Chat list preview: **"🎁 Gift"**.
- Apps that don't know the type yet: show it like any unknown message type.

**New refusal codes (409)** for moment gifts: `GIFT_NOT_HERE`, `GIFT_PLACE`, `GIFT_ITEM_UNAVAILABLE`, `GIFT_ACCOUNT_NEW`,
`GIFT_KEY_REUSED`, `GIFT_SELF`, `GIFT_DAILY_LIMIT`; admin `ITEM_KEY`, `ITEM_KEY_TAKEN`, `ITEM_PRICE`, `ITEM_DATES`,
`ITEM_ICON…`. Meanings: gift API doc Part 11.

---

### 5. Posts and clips: ticket groups and tickets (no switch)

#### 5.1 NEW: attach a ticket group

A post can show a **ticket group** (people buying seats for one ticket type together), as it already shows product
groups.

| Where | Added |
|---|---|
| Create post / quote post `attachments` | `ticketGroupIds: [UUID]` |
| Edit attachments | `ticketGroupIds` (null = no change, `[]` = remove all, list = replace) |
| Draft | `POST /posts/draft/attach-ticket-group/{ticketGroupId}`, `DELETE /posts/draft/remove-ticket-group/{ticketGroupId}` |
| Post and clip responses, `attachments` | **ADDED** `ticketGroups: [AttachedTicketGroup]` |

```json
"ticketGroups": [{
  "id": "…", "eventId": "…", "eventTitle": "DJ Mike Live", "ticketTypeName": "VIP",
  "eventDate": "2026-12-20T20:00:00", "bannerMedia": { … },
  "currentCount": 6, "totalSlots": 10, "remainingSlots": 4,
  "originalPrice": 50000, "discountPrice": 40000, "savingsAmount": 10000, "savingsPercentage": 20.00,
  "expiresAt": "2026-11-26T09:00:00", "status": "OPEN"
}]
```
**Join** opens the existing ticket group checkout for that group.

#### 5.2 NEW: attach a ticket type (like a product)

A post can show **one ticket type** of an event (e.g. "VIP · 50,000"), the way it shows a product.

| Where | Added |
|---|---|
| Create post / quote post `attachments` | `ticketIds: [UUID]` |
| Edit attachments | `ticketIds` (same rules as other lists) |
| Draft | `POST /posts/draft/attach-ticket/{ticketId}`, `DELETE /posts/draft/remove-ticket/{ticketId}` |
| Post and clip responses, `attachments` | **ADDED** `tickets: [AttachedTicket]` |

```json
"tickets": [{
  "id": "…", "eventId": "…", "eventTitle": "DJ Mike Live", "eventDate": "2026-12-20T20:00:00", "bannerMedia": { … },
  "name": "VIP", "price": 50000, "pricingType": "PAID", "attendanceMode": "IN_PERSON", "status": "ACTIVE",
  "onSale": true, "soldOut": false, "salesStartAt": null, "salesEndAt": "2026-12-20T18:00:00",
  "groupBuying": true, "groupPrice": 40000, "groupSize": 10
}]
```
- `onSale` false + `salesStartAt` in the future → show "Sales open on …"; `soldOut` → show "Sold out".
- `groupBuying` true → a ticket group can be started for it (group price and size given).
- **Buy** opens the normal ticket checkout.

#### 5.3 CHANGED: only things people can still act on can be attached

| Attaching | Before | After |
|---|---|---|
| A product group (`buyTogetherGroupIds`, `/draft/attach-group/{id}`) | any group, even full, ended or refunded; an unknown id → an error without a code | only **open** groups (OPEN, not expired, not deleted, seats left). Else **409** `GROUP_NOT_OPEN`; unknown id → **409** `GROUP_NOT_FOUND` |
| A ticket group (new) | — | the same: `GROUP_NOT_OPEN` / `GROUP_NOT_FOUND` |
| A ticket type (new) | — | only a ticket of a **published or happening** event, **active**, **visible**, sales not ended. Else **409** `TICKET_NOT_AVAILABLE`; unknown → `TICKET_NOT_FOUND` |
| Attaching the same one twice to a draft | — | `GROUP_ALREADY_ATTACHED` / `TICKET_ALREADY_ATTACHED` (ticket groups and tickets) |

- **Editing a post keeps what is already on it.** A group that filled or ended after the post was made stays when the
  post is edited; only **newly added** groups and tickets are checked. The card shows the current `status`.
- Show `data.reason` on these refusals and let the person pick another.

#### 5.4 Notifications

No new types. The event organiser now also gets the existing **`SOC_EVENT_FEATURED`** when someone else's post shows one
of their **ticket groups** or **tickets** (as for an attached event).

---

### 6. New endpoints, all in one place

| Area | Endpoints |
|---|---|
| Moment gifts | `GET /gifts/catalogue`, `POST /gifts/moments`, `GET /gifts/moments/sent`, `/received`, `/{momentId}` |
| Moment gifts (admin) | `GET/POST /admin/gifts/items`, `PUT /admin/gifts/items/{itemId}`, `PATCH /admin/gifts/items/{itemId}/state` |
| Posts | `POST /posts/draft/attach-ticket-group/{id}`, `DELETE /posts/draft/remove-ticket-group/{id}`, `POST /posts/draft/attach-ticket/{id}`, `DELETE /posts/draft/remove-ticket/{id}` |

---

### 7. Media

Moment gift icons follow the media standard (`fileId`, `status`, `variants` as URLs, `mimeType`), assembled at response
time. Admins upload them to File Thunder with the existing context **`GIFT_DESIGN`** (no new context).

---

### 8. Screens checklist

| Screen | Calls |
|---|---|
| Live: 🎁 button | `GET /gifts/catalogue?place=LIVE&contextId=<streamId>` → tap an item → `POST /gifts/moments` (new key per tap) · 💳 tab → gift checkout with `place=LIVE`, `contextId=<streamId>` |
| Live: overlay | `GIFT_MOMENT` system comment → `GET /gifts/moments/{id}` → play `itemKey` · `GIFT_CARD` → "💳 gift card" line |
| Chat: 🎁 button | `GET /gifts/catalogue?place=CHAT&contextId=<conversationId>` → moment items + 💳 tab |
| Chat: message | type `GIFT_MOMENT` → its card (§4) |
| Gift menu | new tabs **Moments sent** / **Moments received** |
| Wallet → Gift history | show `giftType` (a 🎉 or 💳 icon) on money-in rows |
| Post composer | new pickers: **+ Ticket group**, **+ Ticket** (draft attach endpoints or `ticketGroupIds` / `ticketIds`); handle `GROUP_NOT_OPEN`, `TICKET_NOT_AVAILABLE` |
| Post and clip cards | draw `ticketGroups` (Join → ticket group checkout) and `tickets` (Buy → ticket checkout; on sale / sold out / opens on) |
| Admin: Moment gifts | items list, add, edit, switch on / off; settings: daily limit, account age, card places |

---

### 9. Meetings: five fixes (no switch)

| What | Before | After |
|---|---|---|
| A meeting for **now** | saved `SCHEDULED`, opened up to 30 s later | `OPEN` at once |
| Joining early | any time, even days before | from **10 min before** the start (`NOT_OPEN_YET`); the host any time |
| Role change `PUT /meetings/{id}/participants/role` | `jid=` | **ADDED** `accountId=` (use this); `jid=` still works for now |
| Edit `PATCH /meetings/{id}` | title, start | **ADDED** `description`, `endsAt`; end must be after start (`END_BEFORE_START`); a start in the past is refused (`IN_THE_PAST`) |
| `CHAT_MEETING_UPDATED` notice data | `changed` ("title, start time") | **ADDED** `changedFields`: `TITLE`, `DESCRIPTION`, `START`, `END` |
| Create answer | the meeting | **ADDED** `speakerLimit`, `invitedAsListeners` (accountIds past the speaker limit) |

Details: `calls_meetings_api_doc.md`, "Meeting refusal codes" and "Changes 2026-11-24".

### 10. Calls: BUSY fixed (no switch)

**FIX** A person was answered **`BUSY`** while only **invited** to a meeting (scheduled for later, or open without them
in it), or while a **group call** they never answered was ringing. On staging, 29 of the 40 BUSY calls in 30 days were
this. Now **BUSY** means really on a call: in a call or meeting room right now, or being rung by another 1:1 call. Same
for work calls. No API change.

---

<a id="part-5"></a>
# Part 5 — 2026-11-25 · Live revamp

**Author**: Josh S. Sakweli, Backend Lead Team
**Version**: v1.4 (phases 1–11, all built; auction win = order; `AUDIO_RADIO` → `LIVE_AUDIO`; event lives booked from the event; donation progress on attachments)

**Short Description**: The live revamp, phase by phase (`docs/live/LIVE_REVAMP_BUILD_PLAN.md`). **Endpoints and flows
change on purpose**: the app isn't released yet, so the cleaner design wins over keeping old shapes. Every change below
shows **before → after**. Full API: `docs/live/live_api_doc_v2.md` (it replaces `live_streaming_api_doc.md` Parts 1–3 and 5).

| Phase | What the app must change | Section |
|---|---|---|
| 1 | Watching needs a **play token** · real-time through **Centrifugo** · comments and pins arrive as **room events** · no replays · refusals use the standard error body · broadcast address changed | §1 |
| 3 | **One create form** (me / shop, now / later, banner, booking switch + caption) · the backend makes the booking **post** · **one live card** everywhere with buttons from the backend · edit / cancel / book again · reminders with choices · My lives, someone's lives, Later today, swipe, `kind` filter | §3 |
| 4 | **Safety**: roles on comments (badges, speaks as the shop, replies with a quote, pin), moderators, blocked words, held numbers / links, mute for a time, remove from the live, report, automatic pause, admin end / ban | §4 |
| 5 | **Taking part**: reactions, joins, who's watching, polls, questions, **guests and co-hosts on the screen** (requests, invites, speaker link, LiveKit stage room, host phone mixes), "Who can invite me to a live", co-host / on-stage comment badges | §5 |
| 6 | **Audio live** mixed on the server (the host phone joins a LiveKit room, no SRS address) · 5 speakers with the host · who can ask to speak · mute never unmute · ✋ on stage · who's talking · speak as your shop · send listeners on · **Spaces removed** | §6 |
| 7 | **Selling**: coupon drop, flash price, free delivery from the live, instalments on the pinned card, goals, sales numbers, host toolbar from the backend · tapping a pinned item is remembered for 24 h | §7 |
| 8 | **Bigger money tools**: group buy (start, attach, lower, give through), bargain, auction, gifts on / off and to the shop's owner, ticket lives (only online ticket holders) | §8 |
| 9 | **External camera**: stream from phone or camera, a camera key per live, private preview then Go live, auto-start, switch both ways, health, Guests window for OBS | §9 |
| 10 | **After the live**: summary (end screen + full numbers), viewers per minute with markers, where viewers came from, the viewer's end screen, "From my last live" | §10 |
| 11 | **Shop staff live** (the shop terminal app): both keys, staff tools without money, hand-over, "hosted by" | §11 |
| 2 | Host phone sends **what the backend says** (2–3 qualities) · viewers get **FLV + HLS per quality + listen only**, start quality and player settings from the backend · **data saver** · host **reconnects to the same live** (2 min) · **Continue your live** (10 min) | §2 |

> **v1.2 (2026-11-26): the audio mode is now `LIVE_AUDIO`** (was `AUDIO_RADIO`), everywhere a `mode` is sent or returned.
> Lives already saved are renamed by the backend. Video stays `LIVE_VIDEO`.
>
> **v1.2: the live banner has its own upload type `LIVE_COVER`** (was `SOCIAL_IMAGE`). Any other upload as
> `coverMediaId` is refused with `COVER_CONTEXT`. Banners already on saved lives stay.

---

### 1. Phase 1: Foundation

#### 1.1 Summary of breaking changes

| # | Before | After |
|---|---|---|
| B1 | `StreamResponse.playbackUrl`: anyone with the address could watch | **removed**. Ask `POST /live/streams/{id}/play` for addresses with a 5-minute play token (§1.3) |
| B2 | `LiveNowCard.playbackUrl` | **removed**. Same: ask `/play` when the card is opened |
| B3 | Every live recorded; states `PROCESSING`, `REPLAY_READY`, `FAILED`; `replayMediaId` | **no recording**. A live goes `DRAFT / SCHEDULED → STARTING → LIVE → ENDED` and stops. `replayMediaId` removed; the `LIVE_STREAM_FAILED` notice is gone |
| B4 | `GET /live/streams/{id}/comments` (cached, every 2 s) | **removed**. Comments arrive on Centrifugo; the fallback is `GET /live/streams/{id}/room` (§1.5) |
| B5 | `POST …/comments` answered a `LiveComment` (`seq`, `userId`, `name`, `body`, `at`) | answers a **room event** `{seq, type: COMMENT, streamId, at, data: {accountId, name, userName, userProfileMedia, body}}` |
| B6 | Pin events were comments with `system: true, event: "attachment.pinned"`; gifts `event: "GIFT_MOMENT"` / `"GIFT_CARD"` | room events `PIN`, `UNPIN`, `GIFT_MOMENT`, `GIFT_CARD` with `data` (§1.5) |
| B7 | `AttachmentResponse.streamOffsetMs` (for replays) | **removed** |
| B8 | Refusals: HTTP 409 with a *success* body `{data: {code, reason}}` | HTTP 409 with the **standard failure body** `{success: false, …, data: {code, reason, details}}` (same as gifts, team). "Not found" is now a plain **404** |
| B9 | Ingest: `rtmpUrl = rtmp://…/live/<ingestKey>`; WHIP `…&stream=<ingestKey>` | `rtmp://…/live/<streamId>?key=<ingestKey>`; WHIP `…&stream=<streamId>&key=<ingestKey>`. **Use the URLs exactly as returned** |
| B10 | `PUT …/comments/mute/{userId}` | same, path variable renamed `{accountId}` (no change in the call) |
| B11 | `PUT …/comments/slow-mode` answered `{seconds}` | answers `{streamId, seconds}` |
| B12 | `GET /live/streams/{id}` answered `hostUserId` + `host` | `hostUserId` **removed** (use `host.accountId`); a person blocked either way gets **404** |
| B13 | HLS pieces 4 s (delay 8–12 s) | **1 s** pieces. The host phone (and OBS) must send a **key frame every 1 s** (GOP = 1 s, e.g. 30 fps → keyint 30) |

#### 1.2 Going live (host): flow before → after

```
BEFORE                                         AFTER
1 POST /live/streams                           1 POST /live/streams                      (same)
2 POST /live/streams/{id}/ingest-key           2 POST /live/streams/{id}/ingest-key      (URLs changed, B9)
3 publish to rtmpUrl / whipUrl                 3 publish to rtmpUrl / whipUrl  ← key frame every 1 s (B13)
4 poll GET /live/streams/{id} until LIVE       4 POST /live/streams/{id}/realtime  → room + hosts channels
                                               5 connect Centrifugo, subscribe room (+ hosts)
                                                 LIVE_STARTED arrives in the room when viewers can watch
5 read GET …/comments every 2 s                6 comments etc. arrive as room events (§1.5)
6 POST /live/streams/{id}/end                  7 POST /live/streams/{id}/end  → LIVE_ENDED in the room
```

#### 1.3 Watching (viewer): flow before → after

```
BEFORE                                         AFTER
1 GET /live/streams/{id} → playbackUrl         1 GET /live/streams/{id}                  (no address in it)
2 play playbackUrl                             2 POST /live/streams/{id}/play {deviceId} → addresses[] with ?token=
                                               3 play addresses[0].url within 5 minutes (startBefore)
3 GET …/comments every 2 s                     4 POST /live/streams/{id}/realtime → room channel + token
                                               5 subscribe the room on Centrifugo; on join read GET …/room once
                                                 for the last 100 events (oldest first)
```

- **`deviceId`**: the app's install id for this phone (the same one used for push), max 100 characters.
- **One phone at a time per person:** asking `/play` from a second phone makes the first phone's token stop working
  **for new starts** (a reconnect needs a new `/play`).
- **Player reconnect / token expired** (the player gets 403 from the video server): call `/play` again.
- **Audio live** answers two addresses: `quality: SOURCE` and `quality: AUDIO_32K` (for weak networks).

```json
POST /api/v1/live/streams/{id}/play   {"deviceId": "a1b2c3"}
→ {"streamId": "…", "startBefore": "2026-11-25T10:05:00Z",
   "addresses": [{"format": "HLS", "quality": "SOURCE", "url": "https://…/live/<id>.m3u8?token=…"}]}
```

Refusals: `DEVICE_REQUIRED`, `NOT_LIVE` (409); blocked or unknown live → 404.

#### 1.4 Real time: Centrifugo (new)

```
 Phone ── GET /api/v1/realtime/connection ──► { wsUrl, token, expiresAt, personalChannel: "personal:#<me>" }
 Phone ── connect wsUrl with token (Centrifugo client SDK: centrifuge-js / centrifuge-dart / centrifuge-swift / -java)
 Phone ── POST /live/streams/{id}/realtime ──► { room: {channel, token}, hosts: {channel, token} | null, personalChannel,
                                                 enabled, fallbackPollSeconds: 2 }
 Phone ── subscribe room with its token (and hosts if given); personal channel needs no token
```

- **Three channels:** `live_room:<id>` (everyone watching), `live_hosts:<id>` (the host now; co-hosts and moderators in
  phase 5), `personal:#<accountId>` (only you).
- **Recovery:** subscribe with recovery on; after a short drop Centrifugo hands back what was missed (last 100, 5 min).
- **Tokens expire** (1 h): ask `/realtime/connection` again on `expired` from the SDK; ask `/live/…/realtime` again for
  channel tokens.
- **`enabled: false`** or **can't connect**: ask `GET /live/streams/{id}/room` every `fallbackPollSeconds` (2 s) and show
  events with a `seq` higher than the last one you showed.
- **Sending stays on the API** (comment, pin…). Never send events to Centrifugo from the phone.

#### 1.5 Room events (new shape)

Every event, on Centrifugo or from `GET …/room`:

```json
{"seq": 41, "type": "COMMENT", "streamId": "…", "at": 1764060000000,
 "data": {"accountId": "…", "name": "Juma Ali", "userName": "juma", "userProfileMedia": {…}, "body": "Bei gani?"}}
```

| `type` | `data` | Show |
|---|---|---|
| `COMMENT` | `accountId`, `name`, `userName`, `userProfileMedia`, `body` | the comment |
| `PIN` / `UNPIN` | `attachmentId`, `type`, `targetId` | pinned card shown / hidden (read the card with the normal product / event endpoints) |
| `WATCHING` | `watching`, `watchingText` | "1.2k watching" (every 30 s) |
| `LIVE_STARTED` | `streamId` | viewers can watch now (start the player) |
| `LIVE_ENDED` | `streamId` | end screen |
| `GIFT_MOMENT` / `GIFT_CARD` | `refId` | gift animation (read the gift by id, as before) |

- `seq` grows by one per event in a room; the hosts' room has its own `seq`.
- Events are **keys + ids, never display text** (except a comment's `body` and names).
- `GET /live/streams/{id}/room` → `{streamId, lastSeq, events[]}` (last 100, oldest first, rebuilt at most every 2 s).
- `GET /live/streams/{id}/hosts-room` → the same for the hosts' room (host only, else 409 `NOT_HOST`).

#### 1.6 Unchanged

Create, end, remind me, attach / shelf / pin / unpin / remove / tap, mute, slow mode, `GET /live/now`,
`POST /live/now/open`, `POST /live/streams/{id}/watching` (heartbeat), SSE `live_started` / `live_ended` /
`live_counts` on the feed stream.

#### 1.7 Not yet (later phases)

Banner as a media object (phase 3), 3 qualities + FLV + data saver (phase 2), scheduling / My lives (phase 3), reactions,
joins, polls, guests (phase 5).

---

### 2. Phase 2: Speed, quality, bad network

#### 2.1 Breaking changes

| # | Before | After |
|---|---|---|
| C1 | `POST …/ingest-key` with no body; answer `whipUrl`, `rtmpUrl` | body `{network: WIFI\|MOBILE\|WEAK\|UNKNOWN, weakDevice}` (optional); answer `publish[]`: one target per quality the phone must send. `whipUrl` / `rtmpUrl` at the top level are **gone** |
| C2 | Calling `ingest-key` again made a new key | while the live is on (STARTING / LIVE) it returns the **same key and targets**; a new key only before going live |
| C3 | `PlayResponse.addresses`: HLS `SOURCE` (+ `AUDIO_32K`) | FLV **and** HLS for every quality: video `Q720` / `Q480` / `Q240` (what the host sends) + `LISTEN_ONLY`; audio `AUDIO` + `AUDIO_32K`. New `preferredFormat` (`FLV`), `startQuality`, `player` |
| C4 | `PlayQuality.SOURCE` | removed (`Q720` … or `AUDIO`) |
| C5 | Encoder stops → live **ENDED at once** | live stays `LIVE` with `hostAway: true` for **2 minutes** (`HOST_RECONNECTING` in the room); back in time → `HOST_BACK`; else `ENDED` with `endedReason: HOST_LOST` |
| C6 | — | `StreamResponse` + `hostAway`, `endedReason` (`HOST_ENDED`, `HOST_LOST`, `NEVER_STARTED`), `canContinueUntil` |

#### 2.2 Host: going live (flow)

```
1 Device check on the phone (N1): measure the network; WEAK → suggest Audio live or a new location
2 POST /live/streams/{id}/ingest-key {"network": "MOBILE", "weakDevice": false}
  → publish: [{quality: Q480, width 854, height 480, videoKbps 800, audioKbps 96, fps 30, keyframeSeconds 1, rtmpUrl, whipUrl},
              {quality: Q240, …}]
3 Encode ONE camera into every target at once (simulcast-style), each to its own rtmpUrl / whipUrl, key frame every 1 s
4 Network gets weak (N2): yellow bar "Weak network, try a new location"; the phone may stop the extra targets by itself
```

| Phone says | Backend answers |
|---|---|
| `WIFI` / `UNKNOWN` / no body | Q720 + Q480 + Q240 |
| `MOBILE` | Q480 + Q240 (saves the host's bundle) |
| `weakDevice: true` | Q480 only |
| `WEAK` | Q240 only |

#### 2.3 Host drops and comes back (flow, N4 + N8)

```
Encoder stops ──► room: HOST_RECONNECTING  (viewers: freeze + "Reconnecting…", comments stay open)
   │  within 2 min: publish again to the SAME targets (same key) ──► room: HOST_BACK
   └─ after 2 min ──► LIVE_ENDED, endedReason HOST_LOST, push LIVE_CONTINUE to the host
                        "Your live stopped · Continue it within 10 minutes"
Host taps Continue (from the push or the end screen while canContinueUntil is set)
   POST /live/streams/{id}/continue ──► the SAME live back to DRAFT (same comments, shelf, post)
   POST …/ingest-key ──► publish ──► LIVE again, room: HOST_BACK + LIVE_STARTED (followers are NOT notified again)
```

The host tapping **End** also gets `canContinueUntil` (10 min) on the answer: show "Continue" on the end screen.

#### 2.4 Viewer: watching (flow)

```
1 POST /live/streams/{id}/play {"deviceId": "…", "network": "MOBILE"}
2 Start addresses where format == preferredFormat (FLV) and quality == startQuality; HLS of the same quality if FLV fails
3 Switch quality by itself with the network (pick another address; same token)
4 Keep about player.targetDelayMs (2 s) behind; when further behind play at player.catchUpRate (1.1×);
  more than player.jumpWhenBehindMs (10 s) behind → jump to now
5 Weak network (N9): yellow bar "Weak network, try a new location" + one tap Listen only 🎧 (the LISTEN_ONLY address)
```

`startQuality`: data saver on or `WEAK` → the lowest; `MOBILE` → Q480 when sent; otherwise the best.
iPhone and web need an FLV player library (Android's standard player plays FLV).

#### 2.5 Data saver (new)

| Endpoint | |
|---|---|
| `GET /api/v1/live/settings` | `{dataSaver}` |
| `PUT /api/v1/live/settings` `{"dataSaver": true}` | every live starts in the lowest quality |

#### 2.6 New room events

| `type` | `data` | Show |
|---|---|---|
| `HOST_RECONNECTING` | `streamId` | freeze the picture, "Mama Yoyo is reconnecting…" |
| `HOST_BACK` | `streamId` | "Mama Yoyo is back" |

#### 2.7 New notification

`LIVE_CONTINUE` (push + in-app, to the host): "Your live stopped · {title}: your connection was lost. Continue it within
10 minutes." Target `STREAM` with `streamId` → open the live's end screen with **Continue**.

#### 2.8 Later

N3, N5, N7 (co-host carries on, speaker weak flag) come with Audio live (phase 6); N6 (no new drops while the host is
away) with the selling tools (phases 7–8).

---

### 3. Phase 3: Scheduling, booking, feeds

#### 3.1 Breaking changes

| # | Before | After |
|---|---|---|
| D1 | `POST /live/streams` answered `StreamResponse` | answers a **`LiveCard`** (§3.3). Body gains `as`, `shopId`, `when`, `remindersOpen`, `caption` |
| D2 | `coverMediaId` in answers (a bare id) | **`coverMedia`**: the standard media object (fileId, status, mimeType, variants), like a profile picture. Requests still send `coverMediaId` |
| D3 | Booking pushed "X booked a live" to followers (`LIVE_STREAM_SCHEDULED`) | **no push at booking**; the post is the announcement. `LIVE_STREAM_SCHEDULED` is **gone** |
| D4 | At the booked time everyone got "starting" even if the host wasn't there | **"is live" only when the live really starts** (`LIVE_STREAM_STARTING`), to remind-me people + followers + friends (shop: shop followers), once each |
| D5 | `PUT …/reminder?wanted=` | same, plus an optional body `{"leads": ["DAY_BEFORE","HOUR_BEFORE","MINUTES_15"]}`; answers `{streamId, reminded, myReminder}` (times, §3.6). Only for a **public** booking |
| D6 | `GET /live/now?kind=LIVE_VIDEO\|AUDIO_RADIO` → `items[]` of `LiveNowCard` | `kind=ALL\|VIDEO\|AUDIO\|SHOP`; `items[]` are `{live: LiveCard, reasonKind, reason, sellingLive}`; new `laterToday[]` (page 0 only) |
| D7 | SSE `live_started` data = a `LiveNowCard` | data = a `LiveNowItem` (`{live, reasonKind, reason, sellingLive}`) |
| D8 | `POST …/end` on a live that never started ended it | refused `NOT_STARTED`: use `POST …/cancel` |
| D9 | `StreamState` | + `CANCELLED` |

#### 3.2 Create form (flow)

```
[ Mama Yoyo ▾ ]  → as: ME, or as: SHOP + shopId (only shops she owns; staff come with the shop terminal)
[ 🔴 Now ] [ 📅 Later ]
title · banner (upload as LIVE_COVER, send coverMediaId) · description · [ 🎥 Video ] [ 🎙 Audio ]
Later → When (pills) → Let people get reminded [ ON ] → caption (only while ON, may be empty) → Book
POST /api/v1/live/streams
{"as": "SHOP", "shopId": "…", "when": "LATER", "scheduledFor": "2026-11-28T20:00:00+03:00", "mode": "LIVE_VIDEO",
 "title": "Kanga sale", "description": "…", "coverMediaId": "…", "remindersOpen": true, "caption": "Kanga sale Friday, come!"}
→ LiveCard (state SCHEDULED, buttons [START, EDIT, POST_IT, SHARE, SEE_WAITING, CANCEL])
```

Text under the switch (app): ON *"A post goes to the feed. People can tap Remind me and get told before you start."*
OFF *"Only you get reminded. Nobody sees this live until you start."*

| Refusal | When |
|---|---|
| `TITLE_REQUIRED`, `TITLE_TOO_LONG` (120) | |
| `TIME_REQUIRED`, `BOOKING_TOO_SOON` (< 15 min), `BOOKING_TOO_FAR` (> 30 days) | Later |
| `TOO_MANY_BOOKINGS` | 5 waiting for this person (personal) or this shop |
| `TOO_CLOSE` | another booking of the person **or** her shop within 2 hours |
| `ALREADY_LIVE`, `SHOP_ALREADY_LIVE` | Now, while she or the shop is live (also checked when starting a booking) |
| `SHOP_REQUIRED`, `NOT_SHOP_OWNER` | as SHOP |
| `COVER_NOT_FOUND`, `COVER_NOT_YOURS`, `COVER_CONTEXT`, `COVER_NOT_IMAGE`, `COVER_FAILED`, `COVER_UPLOADING` | banner |
| `ACCOUNT_TOO_NEW`, `AGE_RESTRICTED` | as before |

**Now** → same as before: `ingest-key` → publish. **No post** unless the host taps "Share to my post" (the composer
with the live attached, §3.5).

#### 3.3 `LiveCard`: one card for every list

Used by: the post attachment, My lives, someone's lives, Later today, Live now, swipe, create / edit answers.

| Field | |
|---|---|
| `streamId`, `mode`, `state`, `as` (`ME` / `SHOP`) | |
| `host` | `{accountId, name, userName, userProfileMedia}` (who holds the phone) |
| `shop` | `{shopId, name, logoMedia}` for a shop live, else null: **show the shop** as the live's name |
| `title`, `description`, `coverMedia` | the banner as a media object; null → draw a plain card with the host's / shop's picture |
| `scheduledFor`, `startingSoon` | `startingSoon` true 30 min after the booked time while not started: "starting soon…" |
| `privateBooking` | only the host ever gets this card |
| `startedAt`, `endedAt`, `watching`, `watchingText` | |
| `waitingCount` | number of remind-me people; **null for viewers under 10** |
| `friendsWatching`, `friendsWaiting` | `{people: [up to 2 person cards], others, text}` e.g. "Josh, Eli and 3 friends are watching". Friends who turned off "Show when I join a live" are never named or counted |
| `myReminder` | `null` → show **Remind me**; else `[{lead, at}]`: when I will be reminded (times from the live's current start; past ones left out). **The app writes the sentence**, e.g. "You'll be reminded Thu 8:00 pm, Fri 7:45 pm and when it starts"; tapping it (the `REMINDED` button) opens the pills to change or turn off |
| `buttons` | **draw exactly these**, in this order |

| Button | Does |
|---|---|
| `START` | host: open the device check → `ingest-key` |
| `OPEN`, `END` | host while live |
| `EDIT` | `PATCH /live/streams/{id}` |
| `CANCEL` | `POST /live/streams/{id}/cancel` |
| `POST_IT` | private booking: `PUT …/reminders-open {open: true, caption}`; public: open the composer with the live attached |
| `SHARE` | share link / share into NexGate chats |
| `SEE_WAITING` | `GET /live/streams/{id}/waiting` |
| `CONTINUE` | `POST …/continue` (phase 2) |
| `BOOK_AGAIN` | `POST …/book-again` |
| `REMIND_ME` / `REMINDED` | `PUT …/reminder` (pills, §3.6) |
| `WATCH` | `POST …/play` |
| `VIEW_HOST` | open the host's profile or the shop |

#### 3.4 After booking (host)

| Endpoint | |
|---|---|
| `PATCH /live/streams/{id}` `{title?, description?, coverMediaId?, removeCover?, scheduledFor?}` | time locked 30 min before (`TIME_LOCKED`), same rules as booking; a **move** sends **one** `LIVE_MOVED` to remind-me people and re-arms their reminders; title / banner changes send nothing |
| `POST /live/streams/{id}/cancel` | a booking or a draft; remind-me people get `LIVE_CANCELLED`; the post stays and its card shows `CANCELLED` |
| `PUT /live/streams/{id}/reminders-open` `{open, caption}` | off → on makes the post now; on → off only while nobody waits (`PEOPLE_WAITING`), and deletes the post. **v1.2:** the host deleting the post herself leaves the live booked (reminders kept); off → on makes a fresh post. Caption > 5,000 → `CAPTION_TOO_LONG` (create, switch, book again) |
| `GET /live/streams/{id}/waiting?page&size` | `{streamId, count, people[], page, size, hasNext}` (host or the shop's owner) |
| `POST /live/streams/{id}/book-again` `{scheduledFor?, remindersOpen?, caption?}` | a new booking copying title, description, banner, mode, shop; default time = same time next week |

The host gets `LIVE_BOOK_AGAIN` ("Book again? · Kanga sale · Friday 8 pm") right after ending; `data.suggestedAt` is the time
to prefill.

#### 3.5 Lives in posts

```
Booking with the switch ON ──► the backend posts: caption + the live attached (author = the host)
Composer [+ Live]: POST /e-social/posts/draft/attach-live/{streamId}  ·  DELETE …/draft/remove-live/{streamId}
Create post body: "attachments": {"streamIds": ["…"]}   (one live per post: ONE_LIVE_PER_POST)
Post answers: attachments.live = LiveCard (read from the live when served: scheduled → live → ended / cancelled)
```

- Anyone can attach anyone's live, **only** a public booking or a live that is on; refused `LIVE_NOT_AVAILABLE`
  (private booking, ended, cancelled) or `LIVE_NOT_FOUND` (blocked either way).
- Caption sits above the card like any post text; title / banner / description are the live's.

#### 3.6 Remind me (viewer)

```
Tap 🔔 Remind me → pills [ 24 h ✓ ] [ 1 h ] [ 15 min ✓ ] · "and when it starts"
PUT /live/streams/{id}/reminder  {"leads": ["DAY_BEFORE","MINUTES_15"]}   (no body = 24 h + 15 min)
→ {streamId, reminded: true, myReminder: [{lead: "DAY_BEFORE", at: "…"}, {lead: "MINUTES_15", at: "…"}, {lead: "AT_START", at: "…"}]}
PUT /live/streams/{id}/reminder?wanted=false  → removes it
```

| Notification | When | To |
|---|---|---|
| `LIVE_REMINDER` (`data.lead`) | 24 h / 1 h / 15 min before (each once; moves with the time) | remind-me people who picked that lead |
| `LIVE_HOST_GET_READY` | 15 min before | the host (private bookings too) → open the device check |
| `LIVE_STREAM_STARTING` | when the live really starts | remind-me people + followers + friends (shop: shop followers), each once |
| `LIVE_MOVED`, `LIVE_CANCELLED` | host moves / cancels | remind-me people |
| `LIVE_BOOK_AGAIN` | host ends | the host |

A booking made less than a lead away skips that lead (booked 45 min ahead → only the 15-min reminder).

#### 3.7 Lists

| Endpoint | |
|---|---|
| `GET /live/mine?status=UPCOMING\|LIVE\|ENDED&page&size` | the host's lives **and** her shops' lives → `{items: LiveCard[], page, size, hasNext}` |
| `GET /live/people/{accountId}` | `{liveNow: LiveCard \| null, upcoming: LiveCard[]}` personal lives only (public bookings) |
| `GET /live/shops/{shopId}` | same for a shop |
| `GET /live/now?page&size&kind=` | + `laterToday[]`: public bookings later today + up to 3 tomorrow |
| `GET /live/swipe?after={streamId}&size=3&kind=&deviceId=&network=` | `{items: [{item: LiveNowItem, play: PlayResponse \| null}], hasNext}`: the next lives in ranked order **with play addresses**, so the app preloads the next one while you watch. `play` is null without `deviceId` |
| Live row above the home feed | `GET /live/now?size=10` (only lives on now) |

New reasons on Live now items (`reasonKind`): `FOLLOWING_SHOP` ("Duka la Mama is live"), `BOUGHT_HERE` ("You bought
here before"), `FRIENDS_WATCHING` (reason = the friends line). Your own shop's live never shows on your list.
`kind=SHOP` = shop lives that are selling.

#### 3.8 Settings

`GET / PUT /live/settings` gains **`showWhenIJoin`** (default true): off → you are never named or counted in "friends
are watching".

#### 3.9 Feed and live real time: SSE removed, Centrifugo instead (step 3.8)

| # | Before | After |
|---|---|---|
| E1 | `GET /api/v1/e-social/feed/stream` (SSE) with event `new_posts` `{type: new_post, postId}` | **removed**. The same news arrives on the **personal channel** `personal:#<me>` as `{type: "NEW_POST", at, data: {postId}}` |
| E2 | Feed SSE events `live_started` / `live_counts` / `live_ended` | personal channel `LIVE_STARTED` `{item: LiveNowItem, bubble}`; shared channel **`live_list:all`**: `LIVE_COUNTS` `{streams: [{streamId, watching, watchingText}]}` and `LIVE_ENDED` `{streamId}` |
| E3 | `POST /live/now/open` every 60 s while Live now was open | **removed**: subscribe to `live_list:all` while Live now (or the live row) is on screen, unsubscribe when it leaves |
| E4 | — | **"is live" bubble** on the home feed: show it when `LIVE_STARTED` has `bubble: true` ("🔴 Juma is live"); `bubble: false` (another live started within 3 minutes) → add it to the bubble's count ("Juma + 2 others are live"), don't pop a new one. Tap → `GET /live/swipe` |

**Flow (app open)**

```
1 App start: GET /api/v1/realtime/connection → connect Centrifugo (token) → subscribe personal:#<me> (no token needed)
2 While the app is in front: GET /api/v1/e-social/feed/heartbeat every 45 s (marks you online; bubbles only go to
  people online, as before)
3 NEW_POST → show the "new posts" bubble (as before with SSE)
4 LIVE_STARTED → the live bubble (E4) and, if Live now is open, add the card
5 Live now on screen → subscribe live_list:all → update counts in place, drop ended cards
6 Can't connect → poll GET /api/v1/feed/home/has-new?since= (feed) and GET /live/now (lives) as before
```

Only the feed and live moved. **Chat events and ringing calls still use the chat SSE** for now; they move to Centrifugo
with the calls work.

---

### 4. Phase 4: Safety

#### 4.1 Breaking changes

| # | Before | After |
|---|---|---|
| F1 | `POST …/comments` answered the room event | answers **`PostedComment`** `{visibility, seq, heldId, comment}` (§4.2) |
| F2 | A filtered comment was refused (409 `FILTERED`) | **accepted but `visibility: ONLY_YOU`**: show it to the writer only, like everyone else sees it posted; nobody else gets it |
| F3 | Comment data `{accountId, name, userName, userProfileMedia, body}` | + `role` (`HOST`, `MODERATOR`, `VIEWER`), `speaksAs` (`{shopId, name, logoMedia}` when a shop live's host talks), `replyTo` (`{seq, accountId, name, body}`) |
| F4 | `PUT …/comments/mute/{accountId}?muted=` (whole live) | + `for=ONE_MINUTE\|FIVE_MINUTES\|WHOLE_LIVE` (default whole live). Host **or moderator** |
| F5 | Slow mode: host only | host or moderator |
| F6 | `StreamState` | + **`PAUSED`** ("This live is being reviewed"): `play` refused `PAUSED`, comments refused `NOT_LIVE` |
| F7 | `EndedReason` | + `ADMIN_ENDED` |

#### 4.2 Comments

```
POST /live/streams/{id}/comments {"body": "15,000 only", "replyToSeq": 41}
→ {visibility: "ROOM",     seq: 52, comment: {…, role: "HOST", speaksAs: {shop…}, replyTo: {seq: 41, name: "Juma", body: "how much…"}}}
→ {visibility: "ONLY_YOU", comment: {…}}            word filter: show it to the writer only
→ {visibility: "HELD",     heldId: "…", comment: {…}} a viewer's phone number or link: "Waiting for the host to approve"
```

| Show | How |
|---|---|
| Badges | `role` HOST → highlighted row + "Host"; MODERATOR → 🛡; a shop live's host shows `speaksAs` (shop logo + name) |
| Reply | `replyTo` above the comment; the person replied to gets `COMMENT_REPLY` `{seq, byAccountId, byName}` on **their personal channel** → play a ding |
| Host / moderators | skip slow mode and the 3-per-2-s limit; numbers and links allowed for them |

Host and moderators also have:

| Endpoint | |
|---|---|
| `DELETE …/comments/{seq}` | room event `COMMENT_REMOVED {seq}` → hide it |
| `PUT …/comments/{seq}/pin`, `DELETE …/comments/pin` | `COMMENT_PINNED` (data = the comment event) / `COMMENT_UNPINNED` |
| `GET …/comments/held` | `[{heldId, comment, at}]`; new ones also arrive in the **hosts' room** as `HELD_COMMENT` |
| `POST …/comments/held/{heldId}/approve`, `DELETE …/comments/held/{heldId}` | approve → posted for everyone; both send `HELD_RESOLVED` to the hosts' room |

Refusals: `MUTED`, `TOO_FAST`, `SLOW_MODE`, `TOO_LONG`, `EMPTY`, `REMOVED_FROM_LIVE`, `REPLY_NOT_FOUND`, `NOT_HOST_TEAM`.

#### 4.3 Moderators and blocked words (settings screens)

| Endpoint | |
|---|---|
| `GET /live/moderators?shopId=` | `{ownerId, moderators: [person], max: 10}` (no shopId = my personal lives) |
| `PUT /live/moderators/{accountId}?shopId=`, `DELETE …` | add / remove (`TOO_MANY_MODERATORS`, `CANT_MODERATE_SELF`) |
| `GET /live/words?shopId=`, `PUT /live/words?shopId=` `{"words": [...]}` | the whole list, up to 100 (`TOO_MANY_WORDS`, `WORD_TOO_LONG`); case doesn't matter |

Moderators count for **every** live of that person (or shop). They get the hosts' room channel on `/realtime`.

#### 4.4 Remove someone from the live

`POST /live/streams/{id}/people/{accountId}/remove` (host or moderator) → they can't play, comment, open the room or get
channels for this live any more; they get `REMOVED_FROM_LIVE` on their personal channel and are unsubscribed from the
live's channels at once. "Block" = the normal block (`POST` block endpoint), never watches this host again.

#### 4.5 Report (flow)

```
⋯ → Report → reason (same list as posts: SPAM, HARASSMENT, NUDITY, SCAM, …) + optional details
POST /live/streams/{id}/report {"reason": "SCAM", "details": "asks for money"} → {streamId, received: true}
   backend keeps: the last 5 minutes of comments + one picture from the video
5 reports from accounts older than 3 days within 2 minutes (more in big rooms) →
   room: LIVE_PAUSED  ("This live is being reviewed": stop the player)
   host: LIVE_PAUSED_BY_NEXGATE
NexGate continues → room: LIVE_RESUMED (start the player again)   ·   NexGate ends → LIVE_ENDED + LIVE_ENDED_BY_NEXGATE to the host
```

Reporting twice is fine (counted once). The host can't report their own live (`CANT_REPORT_OWN`).

#### 4.6 New notifications

| Type | To | Text |
|---|---|---|
| `LIVE_PAUSED_BY_NEXGATE` | host | "Your live is being reviewed" |
| `LIVE_ENDED_BY_NEXGATE` | host | "NexGate ended your live" (+ `data.reason`) |
| `LIVE_BANNED` | the person | "You can't go live for now · until …" |

Going live while banned: `BANNED_FROM_LIVE` (`details` = until, or "forever").

#### 4.7 Under 18

Can watch and comment; **the gift picker in a live shows nothing to send** (the catalogue answers no receiver).

#### 4.8 Admin (web dashboard)

`GET /api/v1/admin/live/reports?status=OPEN|CONTINUED|ENDED|DISMISSED`, `GET …/reports/{id}/snapshot` (PNG),
`POST /api/v1/admin/live/streams/{id}/continue|end` `{reason}`, `POST /api/v1/admin/live/bans`
`{accountId, days: 1|7|30|null (forever), reason}`, `DELETE /api/v1/admin/live/bans/{accountId}`. SUPER_ADMIN / STAFF_ADMIN;
every action is in the admin audit log.

---

### 5. Phase 5: Taking part (video)

Everything here is **new**; nothing old is removed. The few changes to existing things are in §5.1.

#### 5.1 Changes to existing things

| # | Before | After |
|---|---|---|
| P1 | Comment `role`: `HOST`, `MODERATOR`, `VIEWER` | + **`CO_HOST`** (lighter highlight + "Co-host"; `speaksAs` = their shop when they joined as a shop) and **`ON_STAGE`** ("On stage") |
| P2 | Numbers / links held for everyone but host and moderators | also allowed for **co-hosts**; still held for guests on stage and viewers |
| P3 | `POST /live/streams/{id}/watching` (heartbeat) | same call; the **first** heartbeat in a live is now the join ("Juma joined") |
| P4 | `GET /live/settings` `{dataSaver, showWhenIJoin}` | + `whoCanInvite`: `EVERYONE`, `CONTACTS` (default), `NOBODY`; `PUT` takes it too |
| P5 | `POST /live/streams` (create form) | + `stageInvites: [{accountId, role: GUEST\|CO_HOST}]` (up to 10): invites sent when the live is created (Book or Go live). Someone the picker would hide is skipped quietly |
| P6 | Live gifts went to the host only | the host **and everyone on the screen** can receive (the gift picker lists them) |
| P7 | Host team (hosts' room, viewer list, moderation) = host + moderators | + co-hosts |

#### 5.2 Reactions (❤️ 😂 🔥 😍 👏)

```
tap → count locally → every 2–3 s:
POST /live/streams/{id}/reactions {"taps":[{"reaction":"FIRE","count":12},{"reaction":"LAUGH","count":3}]}
→ {counted: 15}            at most 15 a second per person are counted (the rest are dropped quietly)
room, every 2 s: REACTIONS {mix: [{reaction: "FIRE", emoji: "🔥", count: 50}, …]}  → float that many, no names, no numbers
host only: GET /live/streams/{id}/reactions → {total: 2100, most: "FIRE", byReaction: [...]}   ("2.1K reactions · most 🔥")
```

Reactions: `HEART` ❤️, `LAUGH` 😂, `FIRE` 🔥, `LOVE` 😍, `CLAP` 👏 (the backend sends `emoji` with each).

#### 5.3 "Juma joined"

Room event every 2 s: `JOINS {named: [{person, hostFollows, topFanRank}], joinedCount}`. At most 10 named, most
important first (top fans → people the host follows → newest); `joinedCount` counts everyone, also people who turned
"Show when I join" off (never named). **The app decides the look** (a line, a bigger entrance for `topFanRank` 1–3,
"+43 joined"). Friends of the joiner who are watching also get **`FRIEND_JOINED {friend: person}`** on their personal
channel → "your friend Juma joined".

#### 5.4 Who's watching

| Endpoint | Who | Answer |
|---|---|---|
| `GET /live/streams/{id}/viewers/top` | everyone | `{streamId, watching, topFans: [{person, rank}]}` (top 3 gift givers watching now) |
| `GET /live/streams/{id}/viewers?page&size` | host, co-hosts, moderators | `{streamId, watching, viewers: [{person, watchingSince, followsYou, topFanRank, boughtHere}], page, size, hasMore}` (order: top fans → people the host follows → newest). `boughtHere` comes with phase 7 (always false now) |

From the list: Invite to join (§5.7), mute, remove from the live (existing endpoints).

#### 5.5 Polls

```
host / co-host: POST /live/streams/{id}/polls {"question":"Which colour?","options":[{"text":"Red"},{"text":"Blue"},{"productId":"…"}],"seconds":120}
   seconds: 60 | 120 | 300 | null (until ended) · 2–4 options · an option is words, a product on the shelf, or both
room: POLL_STARTED {pollId, question, options:[{index, text, productId, votes, percent}], totalVotes, endsAt, ended:false}
viewer: POST …/polls/{pollId}/votes {"option":1}  → the poll with myVote: 1   (again → ALREADY_VOTED)
room, every 2 s while votes come in: POLL_RESULTS {pollId, options, totalVotes, ended:false}
end (timer or POST …/polls/{pollId}/end): POLL_ENDED {pollId, options, totalVotes, ended:true, winner: 1}   winner null = tie / no votes
joining mid-poll: GET …/polls/current (null = none) · host team after: GET …/polls (finished polls, for the summary)
```

Refusals: `POLL_RUNNING` (one at a time), `POLL_TIMER`, `POLL_OPTION`, `POLL_PRODUCT` (not on the shelf), `POLL_ENDED`,
`ALREADY_VOTED`, `NOT_HOST`.

#### 5.6 Questions

```
Ask: POST /live/streams/{id}/questions {"text":"Does this come in XL?","productId":null}
     150 characters, one every 30 s (TOO_FAST), muted people can't (MUTED); no productId = linked to what is pinned now
     → QuestionView {questionId, asker, text, productId, meToo, meTooByMe, state, askedAt}; hosts' room gets QUESTION_ASKED
🙋 Me too: POST …/questions/{questionId}/me-too   (not your own: OWN_QUESTION)
List: GET …/questions → {questions (on screen → most 🙋 → oldest; done last), notAnswered}
Host / co-host: POST …/questions/{id}/answer → room QUESTION_ON_SCREEN (the big card, Buy when productId) · the card
     that was up goes away (QUESTION_DONE) · POST …/questions/{id}/done → QUESTION_DONE {questionId}
```

`state`: `OPEN`, `ON_SCREEN`, `DONE`, `HIDDEN` (the word filter: only the asker sees it, like comments). Kept 6 hours:
after the live the host still opens the list and sees `notAnswered` ("6 questions not answered" → reply in chat).

#### 5.7 Guests and co-hosts on the screen

**Seats** come from the backend: `GET /live/streams/{id}/stage` →
`{seatsNow: 2, seatsMax: 5, seatsTaken, coHostsMax: 2, requestsOpen, members: [{person, role: GUEST|CO_HOST, asShop, voiceOnly, joinedAt}], me: ON_STAGE|REQUESTED|INVITED|NONE, myInviteId}`.
`seatsNow` = how many next to the host now (host + 2); it can grow without an app update. The room gets
`STAGE_CHANGED {members, seatsNow, seatsTaken}` on every change → redraw the split screen.

**Ask to join (viewer)**

```
POST …/stage/requests {"voiceOnly": true}  → stage view, me: REQUESTED   (cancel: DELETE …/stage/requests/me)
host team: hosts' room STAGE_REQUEST {person, voiceOnly, askedAt} · list GET …/stage/requests
   accept  POST …/stage/requests/{accountId}/accept   (SCREEN_FULL when full: Accept greyed "Full")
   ignore  POST …/stage/requests/{accountId}/ignore
   block   POST …/stage/requests/{accountId}/block    (can't ask again in this live)
   requests off / on: PUT …/stage/requests-open {"open": false}
```

**Invite (host; co-hosts invite watching people as guests)**

```
picker: GET /live/stage-invites/people?q=   → [{person, contact, pastCoHost}]  only people whose setting allows you
POST …/stage/invites {"accountId":"…","role":"CO_HOST"} → StageInviteView
   {inviteId, streamId, streamTitle, scheduledFor, live, inviter, invitee, role, state, createdAt, expiresAt}
   the invited person: push LIVE_STAGE_INVITE + personal STAGE_INVITE_STATE + in GET /live/stage-invites
   refusals: CANT_INVITE "This user cannot be invited" (block or setting, never which), CO_HOSTS_FULL "Up to 2 co-hosts",
             INVITE_LIMIT (20 a day), ALREADY_ON_STAGE; inviting again returns the same open invite
host's list with states: GET …/stage/invites (⏳ PENDING · ✅ ACCEPTED · ❌ DECLINED · EXPIRED · REVOKED)
withdraw: POST /live/stage-invites/{inviteId}/revoke
```

**The invited person**

```
GET /live/stage-invites → open invites (lives not ended)
POST /live/stage-invites/{inviteId}/respond {"accept": true, "asShopId": "…"}   asShopId: co-host as their own shop
   before the live: ACCEPTED → 15 min before LIVE_STAGE_GET_READY → at the start LIVE_STAGE_LIVE_NOW "join the stage"
   during the live: on the screen at once; SCREEN_FULL → the invite stays open; when a seat frees they get
       STAGE_SEAT_FREE {streamId, inviteId} on their personal channel → "A seat is free · Join now"
POST /live/stage-invites/{inviteId}/join {"voiceOnly": false} → on the screen (after "Live now", or after a seat freed)
No thanks: respond {"accept": false} → host sees ❌
```

Invites sent **during** the live last 5 minutes; from the form or My lives until the live ends. Moved / cancelled lives
tell invited people (`LIVE_MOVED` / `LIVE_CANCELLED`, like remind-me people).

**Speaker link (host, after the live is created)**: `POST …/stage/link` → `{streamId, code}` (same code every time
for this live) → share as a link. **Opening it is the yes**: `POST /live/stage-links/{code}` `{"voiceOnly": false}` →
on the screen now if the live is on (seat checked), or an accepted invite for the start. Blocked people and ended lives:
`LINK_ENDED`.

**Leaving / removing**: `POST …/stage/leave` (back to watching) · host team `POST …/stage/members/{accountId}/remove`
(a co-host only by the host) → the person gets `STAGE_REMOVED` on their personal channel. A guest whose phone drops out of the
stage room (LiveKit gives up after its reconnect time) is taken off the screen; the room gets `STAGE_CHANGED`.

**Who can't go on the screen**: accounts under 3 days (`ACCOUNT_TOO_NEW`), under 18 (`AGE_RESTRICTED`), removed from
the live, in their own live (`IN_OWN_LIVE` "End your live to join"), anyone who blocked or is blocked by someone on
the screen (`CANT_JOIN`).

**Video / sound between host and stage (LiveKit)**: host and everyone on the screen call
`POST …/stage/token` → `{streamId, url, room, identity, token, camera}` and join that LiveKit room. **The host's phone
draws the guests next to its own camera and keeps sending one picture to SRS** as today; viewers' players don't change.
`camera: false` = voice only (or an audio live). Others: `NOT_ON_STAGE`.

#### 5.8 "Who can invite me to a live" (privacy screen, next to "Who can add me to groups")

`PUT /live/settings {"whoCanInvite": "EVERYONE" | "CONTACTS" | "NOBODY"}` · default **CONTACTS** (people who follow
each other). Nobody can still open a speaker link themselves. Blocks always win.

#### 5.9 New events and notifications

| Where | Event | Data |
|---|---|---|
| room | `REACTIONS` | `{mix}` |
| room | `JOINS` | `{named, joinedCount}` |
| room | `POLL_STARTED` · `POLL_RESULTS` · `POLL_ENDED` | poll view / results |
| room | `QUESTION_ON_SCREEN` · `QUESTION_DONE` | question / `{questionId}` |
| room | `STAGE_CHANGED` | `{members, seatsNow, seatsTaken}` |
| hosts' room | `QUESTION_ASKED`, `STAGE_REQUEST`, `STAGE_REQUEST_GONE {accountId}`, `STAGE_INVITE_STATE` | |
| personal | `FRIEND_JOINED`, `STAGE_INVITE_STATE`, `STAGE_SEAT_FREE`, `STAGE_REMOVED` | |

| Notification | To | Text (workbook) |
|---|---|---|
| `LIVE_STAGE_INVITE` | the invited person | "{inviter} invites you to their live · {title}" (`data.role` GUEST / CO_HOST) |
| `LIVE_STAGE_GET_READY` | people who accepted | "{host}'s live starts in 15 min · get ready" |
| `LIVE_STAGE_LIVE_NOW` | people who accepted | "🔴 {host} is live · join the stage" |

---

### 6. Phase 6: Audio live (radio + Spaces merged)

#### 6.1 Breaking changes

| # | Before | After |
|---|---|---|
| A1 | **Spaces**: `/api/v1/live/spaces…`, notifications `CHAT_SPACE_SCHEDULED`, `CHAT_SPACE_LIVE`, `CHAT_SPACE_SPEAKER_INVITE`, `CHAT_SPACE_HAND_RAISED`, `CHAT_SPACE_DEMOTED`, `CHAT_SPACE_ENDED`, deep link target `SPACE` | **all removed**. A public audio room is now an **Audio live** (`mode: LIVE_AUDIO`); private talk = group call |
| A2 | Audio live: the host phone published sound to SRS (`publish[0].rtmpUrl` with app `radio`) | the host phone **sends nothing to SRS**. `ingest-key` answers `serverMix: true` and `publish: []`; the host **joins the LiveKit stage room** and the server mixes the voices to SRS (§6.2) |
| A3 | `IngestKeyResponse` `{streamId, ingestKey, expiresAt, publish}` | + `serverMix` (true for audio, false for video) |
| A4 | `StageView` (phase 5) | + `whoCanAsk`, `hands` (accountIds in the order raised); `seatsNow` / `seatsMax` depend on the kind: **video 2 / 5, audio 4 / 7** (people next to the host) |
| A5 | `StageMemberView` | + `newHere` (🎉 first week on NexGate) |
| A6 | `StageTokenResponse` | + `startMuted` (true for everyone but the host: join with the mic off) |
| A7 | `asShopId` only for co-hosts | **anyone on the stage** can speak as their own shop: `POST …/stage/requests {voiceOnly, asShopId}`, respond / join / speaker link take `asShopId`; their comments get `speaksAs` = the shop |
| A8 | `LiveCard` | + `onStage: [person]` for an **audio live on air** (the photos on the card), null otherwise |
| A9 | Report on an audio live kept a picture | keeps **the last 30 s of sound** and who was on the stage (admin: `hasSound`, `onStage`, `GET /api/v1/admin/live/reports/{id}/sound` → `video/mp2t`) |

#### 6.2 Going live with sound (flow)

```
Create form: mode LIVE_AUDIO (+ whoCanAsk: EVERYONE | FOLLOWED | INVITED, default EVERYONE)
Go live → POST /live/streams/{id}/ingest-key        → {serverMix: true, publish: []}
       → POST /live/streams/{id}/stage/token        → {url, room, token, camera: false, startMuted: false}
       → connect to LiveKit with the mic on
backend: host in the room → LiveKit mixes everyone on the stage → SRS → LIVE_STARTED as before
listeners: play exactly as before (POST …/play, the audio addresses); they are never in LiveKit
host's network drops: speakers keep talking, listeners keep hearing; when the room is empty → "host reconnecting" → continue (as phase 2)
end: the mix stops and the stage room closes (video stage rooms close at the end too)
```

#### 6.3 The stage in an audio live

| Want | Call | Notes |
|---|---|---|
| Who can ask to speak | `PUT …/stage/who-can-ask {"who": "EVERYONE"\|"FOLLOWED"\|"INVITED"}` | host / co-host, any time; video lives use it too. Refusals for viewers: `ASK_FOLLOWED_ONLY`, `ASK_INVITED_ONLY` |
| Mute a speaker | `POST …/stage/members/{accountId}/mute` | host team; LiveKit mutes their mic; room `STAGE_MUTED {accountId}`. **Nobody can unmute someone else**: only the speaker turns their mic back on in the app (`CANT_MUTE_HOST`) |
| ✋ "I want to talk next" | `PUT …/stage/hand {"raised": true}` | people on the stage; room `STAGE_HANDS {hands}` in order; leaving the stage drops the hand |
| Who's talking (the glow) | `POST …/stage/speaking {"speaking": [accountId…]}` | the **host's phone** sends LiveKit's active speakers when they change (counted at most once a second); room `SPEAKING {speaking}` arrives live but is **not** in `GET …/room` |
| Send listeners on | `POST …/stage/send-on {"toStreamId": "…"}` | host, before ending; room `LIVE_SEND_ON {toStreamId, title, mode, host}` → "Mama Yoyo sent you to Duka la Asha's live" → open it |
| Seats | `GET …/stage` | audio: 4 next to the host now (5 with the host), 7 allowed; co-hosts at most 2 |

Everything else (requests, invites, speaker link, co-hosts, remove, gifts to anyone on the stage) is phase 5 (§5.7).

#### 6.4 Live now

An audio live with **nobody listening** shows only to people who know the host (following, friends, bought there…);
it never appears as "Live now" / trending for strangers.

#### 6.5 Workbook

Remove rows `CHAT_SPACE_SCHEDULED`, `CHAT_SPACE_LIVE`, `CHAT_SPACE_SPEAKER_INVITE`, `CHAT_SPACE_HAND_RAISED`,
`CHAT_SPACE_DEMOTED`, `CHAT_SPACE_ENDED`.

---

### 7. Phase 7: Selling basics

#### 7.1 Changes to existing things

| # | Before | After |
|---|---|---|
| S1 | `POST /live/streams/{id}/attachments/{attachmentId}/tap` counted a tap | also **remembers** "this person tapped this product / ticket in this live" for **24 h** (last place tapped wins). Call it whenever a viewer taps a pinned or shelf item; it is what links a later purchase to the live |
| S2 | `PIN` room event `{attachmentId, type, targetId}` | + `card` for a product: `{productId, price, flash, instalments: [{planId, planName, payments, frequency, downPaymentPercent, payNow, apr}], freeDelivery}`. Show "or Pay in 3 · 100,000 now" from `instalments`; never with a flash price (empty then) |
| S3 | Checkout (buy now / cart) prices | a flash price from a live is applied by the backend at checkout for a buyer it is meant for; the session item carries `liveDealId`. **A coupon on a flash-priced item is refused** (`NO_COUPON_ON_FLASH`) |
| S4 | Delivery offers | a "free delivery from this live" offer appears only for parcels whose items the buyer tapped in that live (24 h) |
| S5 | `POST /live/streams` | goals can be set before Go live (`POST …/goals` on a booked / draft live); they start at Go live |

#### 7.2 Host toolbar

`GET /live/streams/{id}/tools` (host team) → `{main, drop, more}`, each a list of `LiveTool`:
`PIN`, `DROP`, `STAGE`, `COMMENTS`, `MORE` · Drop sheet: `COUPON_DROP`, `FLASH_PRICE`, `FREE_DELIVERY`, `GOAL` · More:
`POLL`, `QUESTIONS`, `MODERATORS`, `SAFETY`, `SHARE`, `END`. Show exactly these; the backend leaves out what this person
can't use (shop tools only for the shop's owner, or a co-host / speaker who joined as their own shop; coupon drop only
when coupons are on). Group buy, auction and bargain join the Drop sheet in phase 8.

#### 7.3 Coupon drop (flow)

```
host (shop owner): POST …/drops {"couponId","people":20,"seconds":60,"validFor":"HOURS_24","watchersOnly":true}
   validFor: HOUR_1 | HOURS_6 | HOURS_24 (default) | DAYS_3 | DAYS_7 — counted from the grab, never past the coupon's end
room: DROP_STARTED {dropId, couponId, title, kind, value, cap, minOrder, shopId, eventId, people, left, endsAt, validFor, watchersOnly, ended}
viewer: POST …/drops/{dropId}/grab → {dropId, couponId, usableUntil}    the coupon is in My coupons
   refusals: DROP_ALL_TAKEN "All taken. Stay for the next drop!", DROP_ENDED, ALREADY_GRABBED, ACCOUNT_TOO_NEW (3 days),
             WATCH_FIRST (watched less than 30 s), plus the coupon's own (COUPON_NOT_FOR_YOU, COUPON_USED_UP…)
room every 2 s while people grab: DROP_LEFT {dropId, left} · at the end: DROP_ENDED {dropId, grabbed}
host: PATCH …/drops/{dropId} {"addPeople":10,"addSeconds":30} · POST …/drops/{dropId}/stop · GET …/drops (running) · GET …/drops/report (grabbed → used)
```

A grabbed drop coupon links that buyer's orders in the shop to the live while it can be used.

#### 7.4 Flash price (flow, products)

```
host (shop owner): POST …/flash {"productId","price":18000,"minutes":5,"pieces":10,"watchersOnly":true}
   minutes 1 | 3 | 5 | 10; the product must be on the live's shelf; one deal per product (DEAL_RUNNING)
room: FLASH_STARTED {flashId, productId, price, originalPrice, pieces, left, endsAt, watchersOnly, ended}
buyer taps Buy → checkout as usual; the backend gives the flash price and holds the piece 10 minutes (pay within 10 min)
   not watching (watchersOnly) or no piece left → the normal price ("Sold out at flash price, still 25,000")
room: FLASH_LEFT {flashId, left} every 2 s when it changes · FLASH_ENDED {flashId, sold}
host: PATCH …/flash/{flashId} {"price":17000,"addPieces":5} (never higher: FLASH_PRICE_UP) · POST …/flash/{flashId}/stop
```

Colours with a price difference keep it: the same amount comes off every colour.

#### 7.5 Free delivery from the live

`POST …/free-delivery {"half":false,"cap":5000,"areas":[AreaInput…] or null for everywhere}` (shop live, owner) → room
`FREE_DELIVERY_ON {campaignId, half, cap, running}`; `POST …/free-delivery/{campaignId}/stop` → `FREE_DELIVERY_OFF`.
Applies to orders from the live only (items tapped there within 24 h), also after the live ends for those 24 h. Paid
from the shop's spending limit like other delivery campaigns.

#### 7.6 Goals

```
POST …/goals {"type":"ORDERS|PIECES|REVENUE|FOLLOWERS|WATCHING|GIFTS","target":20,"productId":(PIECES),"timerMinutes":5|10|15|30|null,
              "reward":{"kind":"COUPON_DROP|FLASH_PRICE|FREE_DELIVERY|TEXT","drop":{…},"flash":{…},"freeDelivery":{…},"text":"I'll sing"}}
   host / co-host; up to 2 open (GOALS_FULL), never two of a type (GOAL_SAME_TYPE); REVENUE only for the shop's owner;
   money rewards only on a shop live, prepared and checked now; a personal live promises words (TEXT)
room: GOAL_STARTED / GOAL_PROGRESS / GOAL_REACHED / GOAL_TIME_UP / GOAL_ENDED with
   {goalId, type, productId, target, progress, percent, state, endsAt, reward, rewardText, rewardGiven, reachedAt}
   REVENUE: target and progress are null for everyone; the shop's owner gets the amounts on their personal channel
reached → the backend fires the reward at once (a drop appears as DROP_STARTED, a flash price as FLASH_STARTED, free delivery as FREE_DELIVERY_ON)
time's up → state TIME_UP: host has 1 minute: PATCH …/goals/{id} {"addMinutes":5} · POST …/goals/{id}/reward (give it anyway) · nothing → ENDED, no reward
lower the target: PATCH …/goals/{id} {"target":10} (never raise: GOAL_RAISE) · cancel: POST …/goals/{id}/cancel {"giveReward":true}
the live ends → open goals end quietly, no reward
GET …/goals → all goals of the live (summary later)
```

#### 7.7 Sales numbers

During the live the host team gets `SALES {streamId, orders, pieces}` in the hosts' room ("5 orders so far", no money).
`GET …/sales` (host team) → `{streamId, money, orders, pieces, ticketBookings, paid, refundedOrders, refunded, net,
instalments: {orders, paidNow, total}, products: [{productId, taps, orders, pieces}]}`. Money fields are null unless the
caller owns the shop (or event) that sold: a host pinning another shop's product sees counts only.

#### 7.8 Workbook

No new notifications in phase 7.

---

### 8. Phase 8: Bigger money tools

#### 8.1 Changes to existing things

| # | Before | After |
|---|---|---|
| B1 | Shelf types `PRODUCT`, `SHOP`, `EVENT`, `TICKET`, `POST`, `LINK` | + **`PRODUCT_GROUP`**, **`TICKET_GROUP`** (an existing group; only open ones: `GROUP_NOT_OPEN`) |
| B2 | Deal card `{productId, price, flash, instalments, freeDelivery}` | + `group` `{groupId, productId, groupPrice, regularPrice, seatsOccupied, totalSeats, expiresAt, status, startedHere}`: show **Join group** next to Buy |
| B3 | Product group checkout priced at the product's group price | priced at **the group's** price (a live may have lowered it) |
| B4 | Product groups in group lists | + `originKind` / `originId` on the group (`LIVE` + live id): "🔴 Started in Mama Yoyo's live" |
| B5 | Chat offers | an offer made from a live (bargain, auction) carries `liveStreamId`; **no coupon on top** (`NO_COUPON_ON_LIVE_DEAL`) |
| B6 | Live gifts went to the host, always on | a shop live: gifts go to the **shop's owner** (never a staff host) and are **off until the owner turns them on**; personal lives on by default |
| B7 | `LiveCard` | + `locked` and `eventId`: a ticket live shown to someone without an online ticket → `buttons: [BUY_TICKET]` |
| B8 | Toolbar | Drop sheet + `GROUP_BUY`, `AUCTION`, `BARGAIN`; More + `GIFTS` (owner) |

#### 8.2 Group buy

```
host (shop owner): POST …/group-buys {"productId"} → a normal group, no seat bought, the product's own time limit, pinned by itself
   needs group buying on for the product (GROUP_BUYING_OFF → show [Turn on group buying] = the product edit page); one per product (GROUP_RUNNING); one deal per product (DEAL_RUNNING)
room: PIN (type PRODUCT_GROUP) + GROUP_PROGRESS {groupId, …, seatsOccupied, totalSeats, status} whenever seats change
buyers join with the existing group checkout (anyone, from the live, the post or the product page); the live ending doesn't close it
host: POST …/group-buys/{groupId}/price {"price"} (only lower) · POST …/group-buys/{groupId}/give-through (everyone in gets it now; not with nobody in)
attach an existing group: POST …/attachments {"type":"PRODUCT_GROUP"|"TICKET_GROUP","targetId":groupId}
```

Orders of a group started in a live count for the live's sales numbers without a tap.

#### 8.3 Bargain

```
host (shop owner): POST …/bargain {"productId","lowestPrice":40000 (hidden, optional)} · DELETE …/bargain/{productId}
viewer: POST …/bargain/{productId}/offers {"price"} (3 days, watched 30 s; one open offer; 3 tries per product per live)
   below the hidden lowest → OFFER_TOO_LOW ("Not this time"); room OFFER_ANSWERED without the amount
room: OFFER_MADE {productId, person, price, state:"OPEN"} ("Juma offered 45,000")
host: GET …/bargain/{productId}/offers · POST …/offers/{buyerId}/accept · …/counter {"price"} · …/no
buyer after a counter: POST …/bargain/{productId}/counter/accept
agreed → personal: OFFER_ANSWERED {…, state:"ACCEPTED", chatOfferId, payBy (15 min)} → open the chat offer checkout as today (one piece)
```

#### 8.4 Auction

```
host (shop owner): POST …/auctions {"productId","startPrice","step":500|1000|5000|10000,"seconds":30|60|180|300,"lowestPrice"(hidden),"watchersOnly":true}
room: AUCTION_STARTED {auctionId, productId, startPrice, step, topBid, topBidder, nextBid, bids, lowestReached, endsAt, state, winnerOfferId, winnerOrderId}
viewer: POST …/auctions/{auctionId}/bids  (one tap = nextBid; held from the wallet; TOP_UP_TO_BID; WATCH_FIRST; ACCOUNT_TOO_NEW; ALREADY_TOP)
   room AUCTION_BID (same shape); the outbid money goes back at once; a bid in the last 10 s sets the timer to 10 s
end (own timer, even after the live ends): AUCTION_ENDED (state WON / NO_WINNER) to the room
   WON → THE WIN IS THE ORDER (owner 2026-11-25): the held top bid pays a PICKUP order at the winning price at once, nothing
   more is taken; the winner gets AUCTION_ENDED again with winnerOrderId set (+ the normal order notifications)
   → app: "You won · collect at the shop or Choose delivery"; Choose delivery = the existing order screen:
     POST /shipping/orders/{orderId}/delivery-options {dropoff} → pick a shipper → POST /shipping/orders/{orderId}/switch-to-delivery
     (the buyer pays only the delivery fee there; a live free-delivery campaign applies)
   fallback only if the order can't be made (shop paused, wallet frozen): the hold goes back and winnerOfferId is a
     personal offer, 30 minutes to pay (the old way)
   no winner → nothing; the hold goes back
host: POST …/auctions/{auctionId}/cancel (before the end, money back) · GET …/auctions
```

#### 8.5 Gifts

`GET / PUT …/gifts {"open":true}` (personal live: the host; shop live: the owner). Closed → the gift picker offers no
receiver. Receivers: the host (shop live: the shop's owner) and everyone on the stage. Sending is unchanged (gift spec).

#### 8.6 Ticket live (an online / hybrid event on NexGate Live)

> **v1.3 (2026-11-26): changed.** `POST /live/streams/events/{eventId}` is **removed**. The organiser picks the venue in the
> event form (NexGate Live is the default, or NexGate Meeting, or another link); the live is booked when the event is
> published. Full flow: Part 8.

```
anyone without an online ticket: card locked + BUY_TICKET; play / comments / GET …/room / POST …/realtime → TICKET_REQUIRED; no gifts
ticket holder: watches as usual; the first watch checks the online ticket in (method LIVE_WATCH)
the live's own PATCH time / cancel → EVENT_LIVE: move or cancel the event; the live follows
going on air → EVENT_ONLINE_STARTED to every online ticket holder (not the "is live" notice to followers)
```

#### 8.6a Ticket group in a live (added 2026-11-25)

```
organiser (any of his lives, tool TICKET_GROUP shows on his ticket live): POST …/ticket-groups {"ticketId"}
   → TicketGroupCard {groupId, ticketId, eventId, groupCode, groupPrice, regularPrice, seatsOccupied (0), totalSeats,
     expiresAt, status, startedHere}
   a normal ticket group started WITHOUT buying a seat (the group holds its seats itself); the ticket's own group size,
   price and time limit (ends 2 h before the event at the latest, as all ticket groups); pinned at once (TICKET_GROUP)
   NOT_SELLER (not the event's organiser), GROUP_BUYING_OFF, GROUP_RUNNING (one per ticket per live), GROUP_REFUSED
room: TICKET_GROUP_PROGRESS (same card) whenever seats change
buyers: join from the live, the post or the ticket page with the existing ticket group checkout (several seats each,
   up to the ticket's max per person); full → everyone gets tickets; time out → refunds
```

#### 8.7 New room events

`GROUP_PROGRESS`, `TICKET_GROUP_PROGRESS`, `OFFER_MADE`, `OFFER_ANSWERED`, `AUCTION_STARTED`, `AUCTION_BID`, `AUCTION_ENDED`. No new notifications.

---

### 9. Phase 9: External camera

#### 9.1 Changes to existing things

| # | Before | After |
|---|---|---|
| C1 | `POST /live/streams` | + `source: PHONE (default) | CAMERA`, `autoStart` (camera only). `CAMERA_NOT_ALLOWED` when the person may not |
| C2 | `StreamResponse` | + `source`, `cameraConnected` |
| C3 | `POST …/ingest-key` (phone) | refused with `SOURCE_IS_CAMERA` while the live streams from a camera (offer [Switch to this phone]) |
| C4 | `POST …/play` | the host's team can play a **camera preview** (camera connected, not public yet); everyone else `NOT_LIVE` until Go live |
| C5 | Video stage | + `GET …/stage/window` (Guests window) |

#### 9.2 Who may use a camera

`GET /live/stream-from?shopId=` → `{phone: true, camera}`. Camera: accounts at least 30 days old with a verified phone,
or a verified shop. Show "Stream from" with 📹 only when `camera` is true.

#### 9.3 Camera setup and Go live (flows A and B)

```
create (source CAMERA) or PUT …/source {"source":"CAMERA","autoStart":false}
GET …/camera → {streamId, serverUrl ("rtmp://…/live"), streamKey ("<id>?key=…", this live only), width 720, height 1280,
                fps 30, keyframeSeconds 2, connected, health: EXCELLENT|GOOD|POOR|UNKNOWN, kbps, autoStart}
   ⏳ waiting screen; poll GET …/camera every few seconds or wait for CAMERA_CONNECTED
camera connects → personal CAMERA_CONNECTED {streamId} + push LIVE_CAMERA_CONNECTED ("📷 Your camera is connected · tap to go live")
   → preview: play it with POST …/play (host team only); state STARTING, cameraConnected true; nothing public yet
POST …/go-live → public (LIVE_STARTED as always); a booked live can't go public more than 15 min early (TOO_EARLY)
autoStart true → goes live by itself when the camera connects (never before the booked time)
POST …/camera/reset → a new key; whatever used the old one is dropped (paste the new key in OBS)
```

#### 9.4 Switching (§8B.6)

`PUT …/source {"source":"PHONE"|"CAMERA"}` (host). Before the live: switching to the phone kills the camera key. During
the live: the current sender is dropped and the other source takes over (the phone then calls `ingest-key` and
publishes as usual; the camera is refused while the phone is chosen). Viewers see a short blip; same live, comments,
deals. Room `SOURCE_CHANGED {streamId, source}`. Camera lost and nothing done → the usual `HOST_RECONNECTING` (2 min) →
show **[Continue on this phone]** = `PUT …/source {"source":"PHONE"}` + `ingest-key`.

#### 9.5 Guests window (OBS)

`GET …/stage/window` (host) → `{streamId, pageUrl, livekitUrl, room, token, connected}`. Open `pageUrl` with the
LiveKit address, room and token (the web page that draws the guests: frontend), copy it into OBS as a browser source.
`connected` is true while the window is open, so the panel can warn "Neema is on stage but your OBS isn't showing
guests". The host's phone joins the stage room with its mic as before (earphones).

#### 9.6 Not in this phase

Sound from a mixer through LiveKit Ingress (E10) waits for the Ingress infra OK. One camera quality (720p) + listen
only for now (E7).

#### 9.7 New notification

| Type | To | Text |
|---|---|---|
| `LIVE_CAMERA_CONNECTED` | host | "📷 Your camera is connected · tap to go live" |

---

### 10. Phase 10: After the live

#### 10.1 Changes to existing things

| # | Before | After |
|---|---|---|
| D1 | `POST /live/streams/{id}/watching` | + `?from=LIVE_FEED|SWIPE|NOTIFICATION|POST|PROFILE|SHARE_LINK|CHAT|OTHER`: where this person opened the live from (counted once, on their first heartbeat). Send it on every heartbeat or just the first |

#### 10.2 Host: summary (end screen and full numbers)

Push `LIVE_SUMMARY_READY` a few seconds after the end. `GET /live/streams/{id}/summary` (host team) →
`{streamId, money, data, sales, builtAt}`:
- `data`: `startedAt`, `endedAt`, `durationSeconds`, `peakViewers`, `watched`, `averageWatchSeconds`, `newFollowers`,
  `reactions {total, most}`, `gifts {count, amount, topFan}`, `drops {drops, grabbed, used}`, `auctions [{auctionId,
  productId, state, soldFor}]`, `groups [GroupCard]`, `polls [results]`, `questionsNotAnswered`, `goals [GoalView]`,
  `sources [{source, people}]`, `viewers [{minute, watching}]` (one per minute: the graph), `markers [{kind, refId, at,
  viewersBefore, viewersAfter, ordersAfter}]` (`kind`: `COUPON_DROP`, `FLASH_PRICE`, `AUCTION`, `GROUP_BUY`, `POLL`,
  `GOAL_REACHED`; the app writes "8:20 coupon drop → +80 viewers")
- `sales`: the §7.7 sales numbers, read fresh (refunds show up later)
- money (`gifts.amount`, `auctions.soldFor`, revenue goals, `sales` money) only when `money` is true; else null

"Reply in chat" for questions not answered: `GET …/questions` still works for 6 hours after the live.

#### 10.3 Viewer: when the live ends

`GET /live/streams/{id}/after` → `{streamId, host, followsHost, nextLive (LiveCard or null), liveNow [LiveNowItem ×3]}`:
show [Follow] when `followsHost` is false, the next booked public live with Remind me, and 3 lives on now.

#### 10.4 "From my last live"

`GET /live/last-live?accountId=` or `?shopId=` → `{streamId, endedAt, until, productIds}` or null: the products of the
last live that ended in the last 24 h, for a row on the profile / shop. Tapping one: call the live's tap endpoint
(`POST /live/streams/{streamId}/attachments/{attachmentId}/tap` with the shelf item) so a buy still counts for the live.

#### 10.5 New notification

| Type | To | Text |
|---|---|---|
| `LIVE_SUMMARY_READY` | host | "Your live's numbers are ready" |

---

### 11. Phase 11: Shop staff live (backend for the NexGate Shop terminal app)

#### 11.1 Changes to existing things

| # | Before | After |
|---|---|---|
| T1 | Shop rights `SEE_ORDERS … STOCK` | + **`GO_LIVE`** ("Go live for the shop") and **`LIVE_DROPS`** ("Use prepared live drops"), given in a shop role |
| T2 | Terminal permissions | + **`GO_LIVE`** (on the shop counter set); a person's rights ∩ the terminal's give `GO_LIVE` / `LIVE_DROPS` |
| T3 | `POST /live/streams` with `as: SHOP` | the owner from any phone; **staff only from a shop terminal session with both keys** (else `NOT_SHOP_OWNER`); staff can't pick an external camera yet (`STAFF_CAMERA_LATER`) |
| T4 | `LiveCard` | + `staffHost`: show "Duka la Mama · live · hosted by Neema" (`host` is Neema, `shop` is the shop) |
| T5 | `POST …/end` | the shop's owner can also end a shop live a staff member is hosting |
| T6 | Team activity | + `LIVE_HOSTED`, `LIVE_HANDED_OVER` |

#### 11.2 The terminal app (NexGate Shop, Android)

Linked and unlocked as today (terminal key + member session). On a terminal with the **Go live** permission, a staff
member whose role has **Go live for the shop** sees Go live as the shop. The terminal calls the same live endpoints as the
phone app (the allow-list covers create, ingest key, end, pin / shelf, comments and moderation, stage requests, polls,
questions, tools, viewers, sales counts, summary, hand-over; drops need `LIVE_DROPS`). `GET …/tools` decides the
buttons: staff get **Group buy** and, with `LIVE_DROPS`, **Coupon drop** (coupons the owner made); never flash price,
auction, bargain, free delivery, lowering a group price or giving it through; never money (sales and goals show counts
and percentages).

#### 11.3 Hand over (shift change)

`POST /live/streams/{id}/hand-over {"accountId"}` (the host or the owner) → `{streamId, host}`; the target must be the
owner or an active staff member whose role has Go live for the shop (`CANT_HOST`). Same live, same viewers, same deals;
the next person unlocks the terminal and carries on. Room `HOST_CHANGED {streamId, host}`.

#### 11.4 Not in this phase

Staff with an external camera from a shop computer waits for the desktop terminal (no desktop work until the owner's
guide). The terminal app itself is app work.


---

### 12. Donation tickets show their target where they're attached (v1.4, 2026-11-26)

A DONATION ticket's progress `donation: {target, raised, donations}` (as on the event page) now rides with the ticket
wherever it is attached. PAID and FREE tickets: `donation` is `null`.

| # | Where | Before | After |
|---|---|---|---|
| D1 | Post: `attachments.tickets[]` | name, price, `pricingType` | + `donation` |
| D2 | Live: `PIN` room event (`PinData`) for a `TICKET` | ids only | + `donation` |
| D3 | Live room | — | **`DONATION_PROGRESS`** `{ticketId, donation}` after each donation, to every live with that ticket pinned (on air only) |
| D4 | Meeting: `GET /meetings/{id}/pins` (`pinned`, `items[]`) | `{type, itemId, pinnedAt}` | + `donation` for tickets |
| D5 | Meeting data message (`nexgate.meeting`) | — | **`DONATION_PROGRESS`** `itemId` = the ticket; re-read the shelf for the numbers |

A donation is one booking, so it updates at once (no batching).

---

<a id="part-6"></a>
# Part 6 — 2026-11-25 · No more SSE: everything on Centrifugo

**For:** the NexGate app (Android, iOS, web), the shop / office terminal app.
**Why:** the app holds one live connection (Centrifugo) instead of several SSE streams. It reconnects on its own and
catches up after short drops. It already carries live rooms, the live list and the feed bubble (see
Part 5, step 3.8).
**Not changed:** chat messages still arrive over XMPP (ejabberd). Event names and their `data` fields are the same as
before; only the way they arrive changed.

### 1. Endpoints, before → after

| Before | After |
|---|---|
| `GET /api/v1/events` (SSE: calls, chat side events, notifications, shipper changes, feed bubble) | **removed**. Use `GET /api/v1/realtime/connection` (already there) and your `personal:#<accountId>` channel |
| — | **new** `GET /api/v1/realtime/shops` → tickets for every shop you act for: `[ { channel: "shop:<shopId>", token, expiresAt } ]` |
| — | **new** `GET /api/v1/realtime/shops/{shopId}` → one ticket (same shape); `403` if you can't act for that shop |
| `GET /api/v1/files/progress/{fileId}` (SSE) | **removed**. Progress arrives as `file.progress` on your personal channel; `GET /api/v1/files/status/{fileId}` unchanged |
| `GET /api/v1/team/terminal/stream` (SSE, terminal key) | **removed**. Use **new** `GET /api/v1/team/terminal/realtime` (terminal key) → connection with `personalChannel: "terminal:#<terminalId>"` |
| `POST /api/v1/team/terminal/heartbeat` "every few minutes" | **every 20 seconds** now; it is what makes the computer count as open |

`realtime/connection` response (unchanged shape): `{ enabled, wsUrl, token, expiresAt, personalChannel }`. Tokens now
live **10 minutes** (was 1 hour). The Centrifugo client asks for a new one by itself; answer it by calling the same
endpoint again.

### 2. What every event looks like now

Before (SSE): `event: call.incoming` + `data: { callId, … }`.
After (Centrifugo publication): `{ "type": "call.incoming", "at": 1764061200000, "data": { callId, … } }`.
`type` is the old SSE event name and `data` is the old SSE data.

### 3. Flows, before → after

#### 3.1 App opens (person)
Before: open `GET /api/v1/events` with `Last-Event-ID`; the server replayed missed shop messages on connect.
After:
1. `GET /api/v1/realtime/connection` → connect to `wsUrl` with `token`, subscribe `personalChannel`.
2. If you own or work for shops: `GET /api/v1/realtime/shops` → subscribe each `channel` with its `token`. For a
   ticket refresh, call `GET /api/v1/realtime/shops/{shopId}`.
3. On a resubscribe that comes back **not recovered** (gap longer than the 5-minute history), call `/chat/sync` for
   each context, as on a fresh start. The server no longer replays on connect.

#### 3.2 Where each event now arrives

| Event(s) | Before | After |
|---|---|---|
| `call.incoming` / `call.updated` / `call.ended` to a person | `/events` | `personal:#<accountId>` (person's ring still carries `token`) |
| the same for a shop | `/events` of the owner | `shop:<shopId>` **without `token`**: answer through the join endpoint, first to answer wins (as terminals already did) |
| `message.created` (shops only), `message.updated`, `unread.changed`, `conversation.created`, `conversation.updated` | `/events` | person side → `personal:#…`; shop side → `shop:<shopId>` |
| `shop.typing` | `/events` | `shop:<shopId>` |
| `meeting.scheduled`, `meeting.starting` | `/events` | `personal:#<accountId>` |
| `notification.added` | `/events` | `personal:#<accountId>` |
| `shipper.changed` | `/events` | `personal:#<accountId>` of the shipping business owner |
| `feed.new` | `/events` | `personal:#<accountId>` |
| `file.progress` (new name) | `/files/progress/{fileId}` stream, data `{ status, failureReason?, failureMessage? }` | `personal:#<uploader>`: `data: { fileId, status, failureReason, failureMessage }` |

#### 3.3 Upload progress
Before: upload → open `/files/progress/{fileId}` → events until READY or FAILED, then the stream closed.
After: upload → watch your personal channel for `file.progress` with that `fileId` (statuses as before:
`PROCESSING`, `LIVE_PARTIAL`, `READY`, `FAILED`). If the app was closed in between, `GET /files/status/{fileId}` once.

#### 3.4 Losing access to a shop
Before: the stream was closed within about 2 minutes, then reconnected without that shop.
After: the shop ticket refresh is refused (`403`) at the next refresh (tickets live 10 minutes). Unsubscribe that shop.

#### 3.5 Terminal app
Before: `GET /team/terminal/stream` held open; first event `READY`; "open" while the stream was connected.
After:
1. `GET /team/terminal/realtime` (terminal key) → connect, subscribe `terminal:#<terminalId>`.
2. `POST /team/terminal/heartbeat` every 20 s, locked or not. No heartbeat for 60 s = nobody at this computer: calls and
   offers go to the owner's phone instead.
3. Events and their data are the same as before (settings / faces / removed, order alerts, chat, calls, offers). There
   is no `READY` event: the Centrifugo client's "subscribed" callback is the same moment.
4. `TERMINAL_REMOVED`: as before, wipe the key. The server also drops the subscription.

### 4. For the server team (not the app)
- `centrifugo/config.json`: new namespaces `shop` (ticket needed, history 50 / 5 min) and `terminal` (own channel only,
  history 50 / 5 min). Local config only, not deployed.
- "In the app" for the feed bubble now means "fetched a realtime token in the last 11 minutes" (was "holds an SSE
  stream").
- Deleted: `ChatEventsController`, `ChatSse*` (7 classes), `FileProgressRegistry`, the terminal SSE streams and
  heartbeat thread. There is no `SseEmitter` left in the backend.

---

<a id="part-7"></a>
# Part 7 — 2026-11-26 · Calls & meetings revamp

**Version**: v1.2 (phases 1–9, all built; meeting banner upload type `MEETING_COVER`; §12 the 2026-11-27 review fixes and K33)
**Plan**: `docs/calls/CALLS_MEETINGS_BUILD_PLAN.md` · **Design**: `docs/calls/CALLS_MEETINGS_REVAMP_REQUIREMENTS.md` v0.4
**API doc**: `docs/calls/calls_meetings_api_doc.md` (v3.0, the full doc)

The app is not released, so changes are allowed; every change is listed here as **before → after**. Nothing is on
staging yet (owner's go needed).

---

### 1. Phase 1: network + settings

#### 1.1 Changes to existing things

| # | Before | After |
|---|---|---|
| N1 | Every join answer (`POST /calls`, `POST /calls/{id}/join`, `POST /meetings/{id}/join`, `POST /meetings/join/{token}`, work calls) = `{callId, roomName, token, url, kind, state}` | **+ `media`** `{simulcast, adaptiveStream, dynacast, audioRed, audioDtx, maxCameraQuality: P360/P540/P720, camerasOffAbove}`. The app switches these on in the LiveKit SDK exactly as given; nothing old changes |
| N2 | 8 people per call, cameras off above 4, 8 speakers per meeting: fixed in server config | the same numbers, now from **admin settings** (changed without a release) |
| N3 | Listeners in a meeting: no limit | limit from settings (default 300); a link join past it → `409 MEETING_FULL` |
| N4 | A short drop (lift, tunnel, Wi-Fi → data) counted as leaving after ~20 s | the room keeps the person **40 s** (from settings); reconnect as today (`POST …/join` again gives a fresh token) |

#### 1.2 What the app does with `media`

```
connect(url, token, {
  adaptiveStream: media.adaptiveStream, dynacast: media.dynacast,
  publishDefaults: { simulcast: media.simulcast, red: media.audioRed, dtx: media.audioDtx,
                     videoResolution: media.maxCameraQuality  (P360 → 640x360, P540 → 960x540, P720 → 1280x720) } })
```
`maxCameraQuality` is P720 in a 1:1 and P360 in groups by default. `camerasOffAbove` is shown only to explain why the
camera button is off (the token already refuses the camera above it).

#### 1.3 Admin (super admin only)

`GET /admin/calls/settings` · `PUT /admin/calls/settings` with any of `peoplePerCall` (2–50), `camerasOffAbove`,
`speakersPerMeeting`, `listenersPerMeeting`, `callCameraQuality`, `groupCameraQuality`, `departureTimeoutSeconds`
(10–300), `simulcast`, `adaptiveStream`, `dynacast`, `audioRed`, `audioDtx`. Empty fields keep their value.

#### 1.4 Not done here

TURN (calls on networks that block UDP) is **config only** (`livekit/livekit.yaml`): a separate small coturn box waits
for the owner's cost OK. Phone tests: waiting.

---

### 2. Phase 2: who can call me + group calls

#### 2.1 Changes to existing things

| # | Before | After |
|---|---|---|
| G1 | `POST /calls` with a group `conversationId` rang **every** member; a group over 8 couldn't call | **+ `inviteeAccountIds`** (group only): only those ring (`NOT_A_MEMBER` if one isn't in the group). Without it, the whole group rings as before (`CALL_TOO_LARGE` over the limit → show the "pick who to ring" list) |
| G2 | Only people rung could join a group call | **any member** of the group chat joins while there's room (`POST /calls/{id}/join` as today; `CALL_FULL` when full) |
| G3 | `POST /calls/{id}/participants?accountId=` only by whoever started it, 1:1 only | **anyone already in the call** (joined), 1:1 **and group** calls (`NOT_IN_CALL` if you haven't joined); shop calls and meetings still refused |
| G4 | 1:1 calls: chat contacts only | + the callee's **"Who can call me"**: refused → `BLOCKED` "You can't call this person" (looks like a block, on purpose). In a group call, people who don't take calls from the caller simply aren't rung (`NOBODY_TO_RING` if nobody is left) |

#### 2.2 New

```
GET / PUT /calls/settings/me {"whoCanCall": "EVERYONE" | "CONTACTS" | "NOBODY"}   (default CONTACTS = people you can chat with)

GET /calls/conversations/{conversationId}/running   (members only, NOT_A_PARTICIPANT)
  → null, or {callId, conversationId, kind, state, inCall: [person], peopleIn, roomLeft, canJoin, amIn}
     person = {accountId, name, userName, userProfileMedia}
  app: a bar in the group chat "📞 A call is on · 3 in · Join" (Join → POST /calls/{id}/join)
personal channel: call.running {callId, conversationId, kind?, running: true|false} to every group member when a group
  call starts and when it ends (refresh the bar; GET … for the people in it)

whoever started a group call:
  POST /calls/{callId}/participants/{accountId}/mute     (server mutes their mic; they unmute themselves)
  POST /calls/{callId}/participants/{accountId}/remove   (out of the room; joining this call again → REMOVED_FROM_CALL)
  others → NOT_INITIATOR; not a group call → NOT_A_GROUP_CALL
```

Reactions and raise hand in calls stay phone to phone (LiveKit data from the phone, no backend).

---

### 3. Phase 3: meeting create + invites

#### 3.1 Changes to existing things

| # | Before | After |
|---|---|---|
| M1 | `POST /meetings` needed a title and a time (or now); `kind` AUDIO by default (cameras blocked) | **+ `mode`**: `NOW` (one tap: open at once, default title "Asha's meeting", answer has **`link`** (speaker link) and **`hostToken`** → straight into the room) · `LINK` (just a link: no time, no invites, `linkExpiresAt` +30 days, opens when the host joins; others get `WAITING_FOR_HOST` until then; `LINK_IS_JUST_A_LINK` if a time or people are sent) · `SCHEDULED` (the form; missing = SCHEDULED). **`kind` is ignored: every meeting is camera-capable (`VIDEO`)** |
| M2 | Invitees were **put straight in** as speakers / listeners | invitees get an **invite** (waiting) and are **not in** the meeting until they accept. Create answer adds **`invites`** `{invited, cantInvite: [accountId], alreadyInvited}`; `invitedAsListeners` is now always empty (the speaker cap applies when they accept) |
| M3 | — | create + edit: **`coverMediaId`** (banner, optional; checked like a profile picture: yours, an image, uploaded; **upload it with context `MEETING_COVER`**, else `COVER_CONTEXT`) → answer `coverMedia` (standard media object); edit `removeCover: true`; changedFields `BANNER` |
| M4 | — | create + edit: `guestsCanInvite` (default off), `guestsSeeInvited` (default on), `linkJoinsStraightIn` (default off, used in phase 6), `whoCanAskToSpeak` `EVERYONE`/`FOLLOWED`/`INVITED` (used in phase 5) → answer `options {…}`; create + `inviteChatId` (a whole group chat) |
| M5 | Meeting answers had no title / time | `CallResponse` adds (meetings only, nothing removed): `mode`, `title`, `description`, `scheduledAt`, `endsAt`, `access`, `options`, `linkExpiresAt` |
| M6 | `POST /meetings/{id}/join` as an invitee | waiting → `ANSWER_INVITE_FIRST`; removed → `REMOVED_FROM_MEETING` (also by link) |

#### 3.2 New: invites

```
"Who can invite me to lives and meetings": the live setting (PUT /live/settings {"whoCanInvite": EVERYONE|CONTACTS|NOBODY}),
  one setting for both (default CONTACTS = people who follow each other). Refused → in cantInvite (never "blocked" vs "setting")
20 invites a day per person (INVITE_LIMIT); a whole group chat counts as one

POST /meetings/{id}/invites {"accountIds":[…], "chatId"} → {invited, cantInvite, alreadyInvited}
   the host; guests only when guestsCanInvite (CANT_INVITE_HERE)
GET  /meetings/{id}/invites → {accepted, waiting, declined, people: [{person, state, answeredAt}]}
   the host sees everyone; accepted guests see accepted + waiting only when guestsSeeInvited (CANT_SEE_INVITES)
POST /meetings/{id}/invite/accept | /decline → {meetingId, state, role}   (role SPEAKER, or LISTENER once speakers are full)
   a change of mind is allowed until it ends; INVITE_EXPIRED, INVITE_WITHDRAWN, NO_INVITE
GET  /meetings/invites/mine → my waiting invites: [{meetingId, title, description, scheduledAt, endsAt, coverMedia, host, state, invitedAt}]
DELETE /meetings/{id}/invites/{accountId} → take back an unanswered invite (host; NOT_WAITING)
POST /meetings/{id}/participants/{accountId}/remove → remove someone (host; out of the room, can't join again)
states: WAITING · ACCEPTED · DECLINED · WITHDRAWN · REMOVED · EXPIRED (when the meeting ends or is cancelled)
```

#### 3.3 Notices (workbook updated)

| Type | To | When |
|---|---|---|
| `CHAT_MEETING_INVITE` | the invitee | invited (now sent per invite, not at create only) |
| `CHAT_MEETING_INVITE_ANSWERED` (new, LOW) | the host | answers, **grouped**: at most one per meeting per 15 minutes; data `first {name, accountId}`, `answers {accepted, declined, others}` → "Juma and 3 others answered" |
| `CHAT_MEETING_INVITE_WITHDRAWN` (new, in-app) | the invitee | invite taken back |
| `CHAT_MEETING_REMOVED` (new) | the removed person | removed |

---

### 4. Phase 4: My meetings + one Calls tab + reminders

#### 4.1 Changes to existing things

| # | Before | After |
|---|---|---|
| T1 | `GET /calls`, `GET /calls/{id}`, `POST /meetings` answers | + `initiatorAccountId` (who started it; `initiatorJid` stays), **`myRole`** (HOST / SPEAKER / LISTENER, or empty for a plain call), `coverMedia` for meetings, and the meeting fields from §3 (`title`, `scheduledAt`, …) → the **Calls tab** shows meetings with their title and time |
| T2 | Moving or cancelling a meeting told only people in it | people who **haven't answered** are told too (`CHAT_MEETING_UPDATED` with `changedFields`, `CHAT_MEETING_CANCELLED`) |

#### 4.2 New

```
GET /meetings/mine?status=upcoming|ended   (Calls tab "Upcoming" = status=upcoming)
 → [{meetingId, title, description, mode, state, scheduledAt, endsAt, doorsOpenAt (10 min before), linkExpiresAt, coverMedia,
     host: person, myPlace: HOST | ACCEPTED | WAITING, myRole, accepted, waiting,
     buttons: [JOIN, ACCEPT, DECLINE, EDIT, INVITE, COPY_LINK, CANCEL, END]}]
   upcoming: soonest first (links for later at the end); ended: newest first, 50, no buttons
   buttons — host: JOIN, INVITE, COPY_LINK, EDIT, CANCEL (END once open) · accepted: JOIN (doors open), DECLINE · waiting: ACCEPT, DECLINE
```

#### 4.3 Notices (workbook updated)

| Type | To | When |
|---|---|---|
| `CHAT_MEETING_REMINDER` (new) | people who accepted | 24 h and 15 min before (`data.lead` DAY_BEFORE / MINUTES_15); a lead already past when booked or moved is skipped |
| `CHAT_MEETING_HOST_GET_READY` (new, HIGH) | the host | 15 min before |
| `CHAT_MEETING_STARTING` | people in it | at the start (unchanged) |

---

### 5. Phase 5: roles in the room + the server data pipe

#### 5.1 The pipe (requirements §3)

Inside a meeting the **server** sends LiveKit data messages on topic **`nexgate.meeting`**:
`{type, meetingId, accountId?, role?}` — keys and ids only; the phone reads names and pictures from the API.
**Trust only messages from the server** (LiveKit marks them as sent by the server, not by a participant).

| type | to | meaning |
|---|---|---|
| `ROLE_CHANGED` | room | `accountId` is now `role` (CO_HOST / SPEAKER / LISTENER); if it's you, refresh your token with `POST …/join` |
| `HAND_RAISED` / `HAND_LOWERED` | host + co-hosts | refresh `GET …/requests` |
| `MUTED` | the person | the server muted your mic; you can turn it back on yourself |
| `REMOVED` | room | `accountId` was removed (their app leaves) |

#### 5.2 Changes to existing things

| # | Before | After |
|---|---|---|
| R1 | Roles HOST / SPEAKER / LISTENER | + **`CO_HOST`** (up to 2) |
| R2 | `POST /meetings/{id}/participants/{accountId}/remove` host only | host **or co-host** (a co-host can't remove the host or the other co-host: `CANT_REMOVE_HOST`) |
| R3 | Meeting join answer | + **`startMuted`** (true for new speakers when the meeting's option is on, default on); create / edit + `startMuted`; `options.startMuted` |
| R4 | Co-hosts | join any time like the host |

#### 5.3 New

```
PUT / DELETE /meetings/{id}/co-hosts/{accountId}           host only (CO_HOST_LIMIT, IS_HOST)
POST / DELETE /meetings/{id}/hand                          listeners ✋ (ALREADY_SPEAKING; CANT_ASK per "who can ask to speak":
                                                           EVERYONE · FOLLOWED = people the host follows · INVITED = had an invite)
GET  /meetings/{id}/requests → [{person, askedAt}]         host / co-hosts, oldest first
POST /meetings/{id}/requests/{accountId}/accept | /ignore  accept → speaker at once (SPEAKER_LIMIT)
POST /meetings/{id}/participants/{accountId}/mute          host / co-host; never unmutes (CANT_ACT_ON on the host; a co-host
                                                           can't act on the other co-host)
POST /meetings/{id}/participants/{accountId}/listener      back to listener: publishing is taken away in LiveKit at once
```

---

### 6. Phase 6: waiting room, locks, links

#### 6.1 Changes to existing things

| # | Before | After |
|---|---|---|
| W1 | `POST /meetings/join/{token}` let any link holder in | someone **not invited** goes to the **waiting room**: `409 IN_WAITING_ROOM` ("waiting for the host to let you in"). Invited people (waiting or accepted) walk in (their invite counts as accepted). Meeting option **`linkJoinsStraightIn: true`** lets link holders straight in |
| W2 | — | meeting **locked** → new people get `MEETING_LOCKED` (links, accepting an invite, a first join); people already in can rejoin after a drop |
| W3 | Meeting tokens: camera / mic / screen share for every speaker | what a speaker may publish follows the **locks** (host and co-hosts never locked); a speaker whose request was accepted while mics are locked may talk |

#### 6.2 The person waiting

```
POST /meetings/join/{token} → 409 IN_WAITING_ROOM → show "Asking to join…"
personal channel: meeting.admitted {meetingId} → call POST /meetings/join/{token} again → token
                  meeting.denied {meetingId}   → "The host didn't let you in" (they may ask again)
```

#### 6.3 Host and co-hosts

```
GET  /meetings/{id}/waiting → [{person, askedAt, role}]      (data message KNOCK {accountId} in the room; notice CHAT_MEETING_KNOCK)
POST /meetings/{id}/waiting/{accountId}/admit | /deny · POST /meetings/{id}/waiting/admit-all
     admitted with the link's role (a speaker link becomes listener once speakers are full)
PUT  /meetings/{id}/locks {"lockMics","lockCameras","lockChat","lockScreenShare","locked"} → the five flags
     data message LOCKS_CHANGED; speakers' LiveKit permissions change at once (lockChat is used by meeting chat, phase 7)
POST /meetings/{id}/mute-all                                  (every speaker; data message MUTED_ALL)
GET  /meetings/{id}/links → [{token, role, expiresAt, joins, active}]
POST /meetings/{id}/links/{token}/reset → the new link (host only; the old one → LINK_EXPIRED)
```

#### 6.4 Notices (workbook updated)

| Type | To | When |
|---|---|---|
| `CHAT_MEETING_KNOCK` (new, HIGH) | the host | someone asks to join (once per person) |
| `CHAT_MEETING_LINK_JOINED` (new, in-app, grouped 15 min) | the host | people joined by link: `first {name}`, `joins {count, others}` |

---

### 7. Phase 7: meeting chat, polls, questions, reactions (all new)

Kept while the meeting is on (24 h at most), never recorded. Everyone in the meeting (any role) may use them; people who
aren't in get `NOT_IN_MEETING`. Request shapes are the live's (one set of rules).

```
CHAT
POST /meetings/{id}/chat {"text" (≤500), "replyTo": seq?} → {seq, person, role (the badge), text, replyTo {seq, accountId, text ≤80}, at}
GET  /meetings/{id}/chat?after=seq → {lines, pinned, lastSeq, chatLocked}      (after=0 on join = the whole chat, last 500)
PUT  /meetings/{id}/chat/{seq}/pin · DELETE /meetings/{id}/chat/pin           (host / co-host)
chat locked (phase 6 lockChat) → CHAT_LOCKED for everyone but host and co-hosts
data: CHAT {seq, accountId} → GET …/chat?after=<your last seq> · PIN {seq}

POLLS (host / co-host start and end)
POST /meetings/{id}/polls {"question","options":[{"text"} | {"productId"}] (2–4), "seconds"?} → poll
POST /meetings/{id}/polls/{pollId}/votes {"option": 0-3} (once: ALREADY_VOTED; POLL_ENDED) · POST …/polls/{pollId}/end
GET  /meetings/{id}/polls → [{pollId, question, options:[{text, productId, votes}], endsAt, open, votes, myVote}]
data: POLL {itemId: pollId} on start / end, and every 2 s while votes change

QUESTIONS
POST /meetings/{id}/questions {"text" (≤150), "productId"?} · POST …/questions/{id}/me-too (toggle)
POST …/questions/{id}/answered (host / co-host)
GET  /meetings/{id}/questions → [{questionId, person, text, productId, meToo, iMeToo, answered, at}] (open first, most "me too")
data: QUESTION {itemId}

REACTIONS
POST /meetings/{id}/reactions {"taps":[{"reaction": HEART|LAUGH|FIRE|LOVE|CLAP, "count"}]}
data every 2 s: {type: REACTIONS, meetingId, counts:[{reaction, emoji, count}]} — play them as floating reactions
```

---

### 8. Phase 8: selling and gifts in meetings and calls

#### 8.1 Changes to existing things

| # | Before | After |
|---|---|---|
| S1 | A meeting was always the person's | create + **`asShopId`** (the shop's owner only: `NOT_SHOP_OWNER`) → answer `shopId`; only a shop's meeting sells products |
| S2 | Gifts only in lives and chats | moment gifts also in **meetings** (`place: MEETING`, `contextId` = meetingId: receivers = host, co-hosts, speakers; listeners send but don't receive) and **calls** (`place: CALL`, `contextId` = callId: the other people in the call). An admin turns each gift item on for MEETING / CALL in the gift admin (item `places`). In the room: data `GIFT_MOMENT {itemId: momentId}` |
| S3 | **Bug (existing):** calling a shop (`POST /calls {targetShopId}`) crashed before ringing (the shop's member row has no person id) | fixed; found by the phase 8 boot check |

#### 8.2 New

```
MEETINGS (the shelf: what was pinned, the phone draws cards from the product / ticket / group APIs)
POST   /meetings/{id}/pins {"productId"} | {"ticketId"}   host / co-host. Products: shop meetings, the shop's own
       (NOT_A_SHOP_MEETING, NOT_THE_SHOPS). Tickets: the host's own events (NOT_THE_ORGANISERS)
DELETE /meetings/{id}/pins                                unpin
GET    /meetings/{id}/pins → {pinned: {type: PRODUCT|TICKET|GROUP, itemId, pinnedAt}, items: [...], canPin}
POST   /meetings/{id}/pins/{type}/{itemId}/tap            a buyer opens it → an order / booking within 24 h counts for the
                                                          meeting (sale origin MEETING)
POST   /meetings/{id}/group-buys {"productId"}            the shop's owner: a normal group (origin MEETING), pinned
data: PIN_ITEM {itemId}

SHOP CALLS ("this one?")
POST /calls/{callId}/pins?shopId= {"productId"}           the shop side only (403 otherwise)
GET  /calls/{callId}/pins[?shopId=]                       both sides
POST /calls/{callId}/pins/{productId}/tap                 the customer → the sale counts for the call (origin CALL)
```

#### 8.3 Not built in this phase (flagged)

Coupon drop and flash price in meetings: in the live these go through checkout hooks keyed to the live's deals; doing the
same for meetings means widening those money paths, which waits for the owner. Instalments show on the product card as
today.

---

### 9. Phase 9: missed-call actions + call waiting

| # | Before | After |
|---|---|---|
| C7 | Missed-call notice (`CHAT_MISSED_CALL`) was plain | data adds **`actions: ["CALL_BACK", "MESSAGE"]`**, `callerAccountId` (or `callerShopId`), with `callId` / `conversationId` as before → the app draws the buttons (Call back = `POST /calls` to that person; Message = open the conversation) |
| C8 | Calling someone already on a 1:1 call → `409 BUSY` (call recorded as busy) | it **rings as waiting**: the caller's answer adds **`waiting: true`**; the callee's ring (`call.incoming` and the push) adds `waiting: true` → "Ali is calling · End & answer / Decline". Only when they already have a call **and** one waiting → `BUSY` as before. Group calls and shop calls unchanged |

The missed-call notice comes when a ring times out (MISSED), as before; a caller who hangs up first (CANCELLED) sends none.


### 10. Event meetings (v1.1, 2026-11-26)

An online / hybrid event can happen in a NexGate Meeting (the venue is picked in the event form; see
Part 8).

| # | Before | After |
|---|---|---|
| E1 | a meeting is joined by invite or link | **+ an online ticket**: `POST /meetings/{id}/join` lets a ticket holder in as a listener (checked in, `MEETING_JOIN`); others `TICKET_REQUIRED` |
| E2 | the host moves / cancels the meeting | an event's meeting follows the event: its own time change or cancel → `EVENT_MEETING` |
| E3 | host invites become speakers, or listeners when the speaker seats are full | event meeting: invites are **speaker seats only** (`SPEAKERS_FULL`), no whole-chat invite, no "guests can invite", no listener links (`EVENT_MEETING_LINK`, `EVENT_MEETING`) |

### 11. Donation tickets on the shelf (2026-11-26)

| # | Before | After |
|---|---|---|
| S1 | `GET /meetings/{id}/pins` items `{type, itemId, pinnedAt}` | + `donation {target, raised, donations}` for a DONATION ticket (null otherwise) |
| S2 | — | data message `DONATION_PROGRESS` (`itemId` = ticket) after each donation; re-read the shelf |


### 12. Review fixes and K33 (2026-11-27)

| # | Before | After |
|---|---|---|
| V1 | `PUT /meetings/{id}/participants/role` accepted `HOST` / `CO_HOST` (a second host, past the 2-co-host limit); `LISTENER` left the mic open until the person reconnected | only `SPEAKER` · `LISTENER` (`ROLE_NOT_HERE` otherwise; co-hosts with `/co-hosts`); `LISTENER` cuts publishing at once, like `…/participants/{id}/listener` |
| V2 | the shop pinning a product in a shop call told nobody | the customer gets **`call.pinned {callId, productId}`** on the personal channel → read `GET /calls/{id}/pins` |
| V4 | a group call seat was held by everyone with a row until the call ended: people who declined, rang out or left too → `CALL_FULL`, `roomLeft: 0` while only a few talk; the camera rule counted them too | a seat = **still ringing or in the call**; declining, ringing out or leaving frees it at once; coming back takes one again if free (K7). Same rule for Join, Add someone, the bar's `roomLeft` and "cameras off above 4" |
| V5 | above 4 people a video call became **audio only** for everyone; a meeting with 5+ speakers had no cameras at all | cameras for everyone up to the call's limit (8) and for all 8 speakers; default `camerasOffAbove` **8** (the admin can still lower it) |
| V6 | "contacts" meant two things: calls = people you can chat with (everyone while message requests are off); invites = people who follow each other | **one meaning** for "Who can call me" and "Who can invite me": follow each other, each other's number saved, or an accepted message request — also while requests are off (a stranger can't call or invite someone on the default). Group calls: being in the group is the link, only `NOBODY` isn't rung |
| V7 | a gift item worked in meetings / calls only if an admin listed MEETING / CALL on it → empty gift list in meetings at launch | gift items work there **by default**: a new item with no `places` gets every built place (live, chat, meeting, call); an admin can take one out (admin `places` now optional; empty on edit = unchanged) |
| V3 | coupon drop and flash price only in lives (K33) | also in **shop meetings**: `POST/GET /meetings/{id}/flash`, `…/flash/{flashId}/stop`, `POST/GET /meetings/{id}/drops`, `…/drops/{dropId}/grab`, `…/drops/{dropId}/stop`. The live's request / answer shapes and checkout; the host of the shop meeting runs them; the product must be pinned; "watchers only" = joined the meeting; room messages `FLASH` / `DROP {itemId}`; a sale with a grabbed coupon counts for the meeting |

API doc: `docs/calls/calls_meetings_api_doc.md` v3.6 (#29, #62–#63, #68–#74, Part D).

---

<a id="part-8"></a>
# Part 8 — 2026-11-26 · Where an online event happens

**Author**: Josh S. Sakweli, Backend Lead Team
**Version**: v1.1 (§6 the team needs no ticket)

**Short Description**: An online (or hybrid) event now picks **where it happens**: NexGate Live (default), NexGate Meeting
or another link (Zoom, Meet…). Picking a NexGate room books it when the event is published; ticket holders get in with one
button on the event page and their ticket, and a notice when it starts. The separate "Stream on NexGate Live" call is gone.

---

### 1. The event form: Online details

```
Online details › Where will it happen?
  [ 🔴 NexGate Live ]   [ 🎥 NexGate Meeting ]   [ 🔗 Other link ]
     default              up to 300 people         Zoom, Meet…
```

| # | Before | After |
|---|---|---|
| V1 | `PATCH /e-events/drafts/{id}/location` `virtualDetails: {meetingLink, meetingId, passcode}`, link required | **+ `venue`: `NEXGATE_LIVE` (default) \| `NEXGATE_MEETING` \| `LINK`**. The link (and id, passcode) only for `LINK`, where it stays required; for the NexGate rooms it is cleared |
| V2 | event answers `virtualDetails: {meetingLink, meetingId, passcode}` (organiser view) | + `venue`, `roomId` (the booked live's streamId or the meeting's id, after publish) |

An app that still sends only `meetingLink` gets `LINK` (unchanged behaviour). Events saved before today with a link are `LINK`.

| Venue | Good for | Who talks | Size |
|---|---|---|---|
| NexGate Live | concerts, shows, big talks, launches, services | the host + up to 5 on stage; viewers comment, react, vote, ask | no limit |
| NexGate Meeting | workshops, small classes, coaching, Q&A circles | up to 8 speakers; others raise a hand | 300 (admin setting) |

### 2. Publish, move, unpublish, cancel

```
publish  ── NexGate Live    → a live is booked at the event's start (title = event title, no post, no Remind me)
         ── NexGate Meeting → a meeting is booked (start + end, the organiser is the host, no invites)
         ── Other link      → nothing booked
move the event (PATCH /e-events/{id} start / end) → the live / meeting moves with it
unpublish → the live / meeting is cancelled; publishing again books a new one
cancel the event → the live / meeting is cancelled (an open meeting ends; a live already on air is left alone)
```

Refusals on publish (409, standard error body):

| Code | When |
|---|---|
| `MEETING_TOO_SMALL` | NexGate Meeting and the online tickets add up to more than the meeting holds (or a ticket has no limit); `details.meetingSeats` = 300. Also when creating / raising an online ticket later |
| `ACCOUNT_TOO_NEW`, `AGE_RESTRICTED`, … | NexGate Live: the organiser can't go live (the live's own rules) |

The live / meeting itself can't be moved or cancelled on its own: `EVENT_LIVE` / `EVENT_MEETING` ("move or cancel the event").
Banner and description of the live can still be edited (`PATCH /live/streams/{id}`).

**Removed:** `POST /live/streams/events/{eventId}`.

### 3. The button on the event page and the ticket

`GET /api/v1/e-events/{eventId}/online` (signed in) → one answer for the viewer:

```json
{"eventId": "…", "venue": "NEXGATE_LIVE", "roomId": "…", "startsAt": "…", "doorsOpenAt": "…", "endsAt": "…",
 "button": "JOIN", "meetingLink": null, "meetingId": null, "passcode": null}
```

| `button` | Shown when | Tap |
|---|---|---|
| `HOST` | the organiser | open the live (host) / the meeting |
| `STARTS_LATER` | ticket holder, before `doorsOpenAt` (10 min before the start) | nothing; show the start time |
| `JOIN` | ticket holder, doors open until the end | NexGate Live: open the live `roomId` · NexGate Meeting: `POST /meetings/{roomId}/join` |
| `OPEN_LINK` | ticket holder (or organiser) of a `LINK` event | open `meetingLink` (with `meetingId`, `passcode`); only holders get them |
| `BUY_TICKET` | no online ticket | the event's ticket checkout |
| `ENDED` / `CANCELLED` | after the end / event cancelled | nothing |

Not an online event → `NOT_ONLINE_EVENT`.

### 4. Getting in

- **Live:** only online ticket holders (and the team) play, comment, give, **open the room snapshot (`GET …/room`) and get the room channel (`POST …/realtime`)**: `TICKET_REQUIRED` otherwise; the live card still shows title, banner and `BUY_TICKET`.
  The first watch checks the ticket in (`LIVE_WATCH`).
- **Meeting:** `POST /meetings/{id}/join` lets an online ticket holder in as a **listener**, checked in (`MEETING_JOIN`);
  they raise a hand to speak. Others `TICKET_REQUIRED`. Doors open 10 minutes before (`NOT_OPEN_YET`).
- A ticket bought while it is on works at once.

### 5. New notification

| Type | To | When | Data |
|---|---|---|---|
| `EVENT_ONLINE_STARTED` | every online ticket holder | the live goes on air / the meeting opens | `eventId`, `venue`, `roomId`, `event {name, date, time}`; target `EVENT` |

In-app text: "{event} is on now · Tap to join". For an event live it replaces the "is live" notice to followers (the live is
for ticket holders only).

### 6. The team needs no ticket (v1.1)

The ticket is for the audience; the people running the event never pay.

| Room | No ticket needed | Rules |
|---|---|---|
| Live | the organiser · the organiser's moderators · anyone on the stage or invited to it (stage invite, speaker link) | before or during the live, as in any live; co-hosts invite only people watching (who hold tickets) |
| Meeting | the organiser · people the host invites (**free speaker seats**, up to 8 speakers) · speaker-link holders | listener seats are the tickets: `POST /meetings/{id}/links` with `LISTENER` → `EVENT_MEETING_LINK`; invites past the speaker seats → `SPEAKERS_FULL`; a whole-chat invite or "guests can invite" → `EVENT_MEETING`; a listener link someone already holds still needs a ticket (`TICKET_REQUIRED`) |

The host can still bring a ticket holder up during the meeting (listener → speaker → co-host), and in a live take
requests to speak from watchers. An event live's "Let people get reminded" switch stays off (`EVENT_LIVE`).

---

<a id="part-9"></a>
# Part 9 — 2026-11-27 · Night build: events, live fan-out, volume pricing, sale origins

**Author**: Josh S. Sakweli, Backend Lead Team
**Version**: v1.1 (all four plans built; §0 where it stands, §9 the morning list, §10 done before staging)

**Short Description**: The four plans agreed on 2026-11-27, built in order. Each part says what the app sees change.
Plans: `docs/events/EVENT_RULES_PLAN.md` · `docs/live/LIVE_FANOUT_PLAN.md` · `docs/pricing/VOLUME_PRICING_PLAN.md` ·
`docs/analytics/SALE_ORIGINS_PLAN.md`. Everything is local on `fet/team`, not pushed.

---

### 0. Where the build stands

| Batch | What | State | Commit |
|---|---|---|---|
| E1 | Events R1, R8, R9, R10, R14, R15, R16 (+ reveal fixes) | ✅ built, unit tests + real boot | `a86339fe` |
| F | Live fan-out F1–F13 (all) | ✅ built, unit tests + real boot | `7bfb71c1` |
| P1 | Pricing B1, B2 (flash), C (free delivery kept), E4 | ✅ built, unit tests + real boot | `7aaa51e3` |
| P2 | Pricing A (volume pricing), D (bargain quantity), E3, E5, E6 | ✅ built, unit tests + real boot | `30fd918b` |
| S | Sale origins S1–S9 | ✅ built, unit tests + real boot | `0019ae9d` |
| E2 | Events R2, R4, R5, R6, R7, R12, R13, R17, R18 | ✅ built, unit tests + real boot | `dc48f08e` |

**All 4 plans built.** Unit tests: 758 pass. Real-boot checks written / run tonight: `EventRulesBootCheck`, `EventRules2BootCheck`,
`LivePhase3BootCheck`, `LivePhase7BootCheck`, `VolumePricingBootCheck`, `SaleOriginsBootCheck`, `CallsPhase8BootCheck`, `LiveAuctionWinBootCheck`,
`EventVenueBootCheck` — all pass (`-Dlive.boot=true`; Phase 7 also `-Dapp.coupons.enabled=true`). Nothing pushed.

---

### 1. Events — when the organiser gets the money (R1) and buyers' problem reports (R8)

**Rule:** the organiser claims only **24 h after the event ends** (24 h after the last day of a multi-day event), and never
while a ticket holder's problem report is open. Admins are not held by it (as before).

| # | Before | After |
|---|---|---|
| E1.1 | `GET /e-events/claims/event/{eventId}/claimable-amount`: claim allowed from 3 days **before** the start | + **`claimFrom`** (end + 24 h), + **`openProblemReports`**; `eligible` false until `claimFrom` and while reports are open; `refundDeadline` / `pastRefundDeadline` stay (they are the buyers' refund line) |
| E1.2 | `POST /e-events/claims/event/{eventId}` before the end → allowed after "refund deadline" | refused **`CLAIM_TOO_EARLY`** (409) before `claimFrom`, **`CLAIM_HELD`** (409) while a report is open |

**New: report a problem** (ticket holders of any event, from the start until `claimFrom`)

| Endpoint | Who | Body / answer |
|---|---|---|
| `POST /e-events/{eventId}/problem-report` | a ticket holder | `{ "reason": "She left after 20 minutes" }` (≤ 500) → `{ reportId, eventId, reporterId, reason, status: "OPEN", createdAt, resolvedAt, resolutionNote }` |
| `GET /e-events/{eventId}/problem-report` | the reporter | their report (404 if none) |
| `GET /e-events/problem-reports?page&size` | admin | open reports, newest first |
| `GET /e-events/{eventId}/problem-reports` | admin | all reports of an event |
| `POST /e-events/problem-reports/{reportId}/resolve` | admin | `{ "status": "RESOLVED" \| "DISMISSED", "note": "…" }` — lifts the hold |

Refusals (409): `REPORT_TOO_EARLY` (before the start) · `REPORT_CLOSED` (after `claimFrom`, or closing a closed report) ·
`NO_TICKET` · `ALREADY_REPORTED` (one per person per event) · `EVENT_CANCELLED` (cancelled = refunded anyway) · `BAD_STATUS`.

App: show **"Report a problem"** on the ticket of an event that has started, until `claimFrom`.

### 2. Events — online tickets and the gate (R9, R10)

| # | Before | After |
|---|---|---|
| E2.1 | every ticket got a signed QR | **online tickets get no QR** (`jwtToken` empty; the PDF shows no QR). The ticket screen shows the Join button from `GET /e-events/{id}/online` and the ticket number |
| E2.2 | the gate scanner accepted an online ticket's QR | refused: `status: "ONLINE_TICKET"`, "📺 Online ticket: watch in the app, not valid at the gate" (**new status value** for the scanner app) |
| E2.3 | scanner sync (full / delta) listed every ticket | online tickets are **left out**; an offline check-in pushed for an online ticket counts as failed |

### 3. Events — ticket types always fit the event's format (R14, R15, R16)

| # | Before | After |
|---|---|---|
| E3.1 | create ticket type: `attendanceMode` always required | **in person / online events: leave it out, the backend sets it**; hybrid: required ("Choose in person or online for this ticket type"); TBA: may be left out (set at reveal) |
| E3.2 | event responses | + **`allowedTicketModes`**: `["IN_PERSON"]` · `["ONLINE"]` · `["IN_PERSON","ONLINE"]` (hybrid) · `[]` (TBA). One value = don't show the choice |
| E3.3 | a sold ticket type could switch in person ↔ online | refused once any is sold: "create a new ticket type instead" |
| E3.4 | changing a draft's format left ticket types of the wrong kind | they **follow by themselves** (one possible answer, nothing sold); leaving hybrid with types of the other kind → refused with their names; sold ones → refused |
| E3.5 | publish | also refuses ticket types that don't fit the format (hybrid: "Choose in person or online for: …"). Hybrid's "one of each" check was already there |
| E3.6 | reveal a TBA event as online: a meeting link was always required | link only for **Other link** (NexGate Live is the default); a **published** event revealed as online now gets its room booked (it didn't before); ticket types made while TBA get the revealed mode |

---

### 4. Live — finding lives, the bubble, fan-out (live fan-out plan F1–F13)

Live API doc **v4.1** has the details (F14, #17, #18, #143–#146, Part D, Part E).

| # | Before | After |
|---|---|---|
| F.1 | `LIVE_STARTED` on the personal channel with a full `LiveNowItem` card to every follower | **removed**. Connected followers get **`FEED_NEW {what: "LIVE"}`** (no content) and ask `GET /feed/home/has-new` |
| F.2 | `NEW_POST {postId}` (old post fan-out) and `feed.new` (feed hint) | **removed** → one **`FEED_NEW {what: "POST"}`**, at most once a minute |
| F.3 | `GET /feed/home/has-new` → `{count, more, authors, nextPollIn}` | + **`lives`**: `[{streamId, mode, as, host, shop}]` — followed people / shops live now, each live listed once |
| F.4 | — | **`GET /live/row`** (#143): up to 10 circles + `seeAll` |
| F.5 | `GET /live/now` paged by `page` | + **`cursor`** (send empty first) → **`nextCursor`**; `page` still works. 409 `CURSOR_EXPIRED` after 10 min |
| F.6 | `GET /live/swipe` | **removed** (404) |
| F.7 | `GET /feed/reels` items `{position, source, clip}` | + `kind` (`CLIP`); with **`lives=true`** an item may be `kind: "LIVE"`, `clip: null`, `live: {…}` |
| F.8 | — | **`POST /live/streams/{id}/clips-preview?seconds=`** (#146): how long a live preview stayed on screen |
| F.9 | — | **"🔔 All lives"**: `PUT /live/alerts {accountId \| shopId, on}` (#144), `GET /live/alerts?accountId=` (#145) |
| F.10 | "X is live" push to every follower, even of a celebrity | celebrity (10,000+ followers / a shop as big): only Remind me + "🔔 All lives"; others in batches |
| F.11 | the red ring (`live: {streamId, kind}`) only on post and clip authors; a staff-hosted shop live rang the **staff member** | ring also on **profiles** (`UserProfileResponse`, `ProfileSummaryResponse`), **shop page + shop cards** (`ShopResponse`, `ShopSummaryListResponse`, `ShopSearchResponse`), **people / shop suggestions**, **followers / following** (`user.live`), **comment authors**; a shop live rings **the shop** |

App notes: play a clips-feed live **muted, low quality**; it counts as watching only after 3 s or a tap. Show "See all" only
when `seeAll`. The bell (#144) sits next to Follow.

---

### 5. Pricing — flash price fixes, free delivery kept, volume pricing, bargain quantity, the cart (pricing plan)

#### 5.1 Flash price (B1, B2)
| # | Before | After |
|---|---|---|
| P.1 | too few flash pieces → the item silently got the normal price | checkout refused **`FLASH_PIECES_LEFT`** (409) with `details: {left, productId}`; resend the same checkout with **`skipLiveDeal: true`** for the normal price, or with the quantity lowered to `left` |
| P.2 | no limit per buyer | `POST /live/streams/{id}/flash` + **`maxPerPerson`** (1–99, default 2); refused **`FLASH_MAX_PER_PERSON`** with `details: {max, yours}`; `FlashView` + `maxPerPerson` |

#### 5.2 Live free delivery (C, E4)
- A **pickup** order paid while the live's free delivery is on keeps it **24 h**: "Choose delivery" in that time still gets it,
  even after the live ended or the shop stopped it early. Nothing new to send.
- **One item** of a shop's parcel tapped in the live now qualifies the whole parcel (before: every item).

#### 5.3 Volume pricing (A)
| # | Where | What |
|---|---|---|
| P.3 | `POST / PUT /e-commerce/shops/{shopId}/products` | + **`pricingType`** (`FLAT` default · `VOLUME`) + **`volumePrices`**: `[{fromQuantity, price}]`, 1–3 steps. Refusals (409): `VOLUME_STEPS_REQUIRED`, `VOLUME_TOO_MANY_STEPS`, `VOLUME_STEP_NOT_LOWER`, `VOLUME_STEP_NOT_MORE`, `VOLUME_STEP_BELOW_MIN`, `VOLUME_STEP_ABOVE_MAX`, `VOLUME_STEP_INCOMPLETE` |
| P.4 | product detailed / public / summary responses | + `pricingType`, `volumePrices` (reachable steps only), **`bulkFrom`** ("Bulk from 3" badge) |
| P.4b | every other place a product price is shown: marketplace card, search results, wishlist items, products attached to posts and clips | + `pricingType`, `bulkFrom` (`1ea6f6e1`); `price` stays the normal price |
| P.5 | cart items | `unitPrice` is the step price; + **`priceStep`**, **`nextStep`** ("Buy N more": `nextStep.fromQuantity − quantity`) |
| P.6 | checkout items | `unitPrice` the step price; + `priceStep`, `nextStep`; group checkout + **`aloneUnitPrice`** when buying alone is cheaper |
| P.7 | order items | + **`priceStepFrom`** ("4 × 9,000 · bulk price") |
| P.8 | flash vs step | the buyer pays the lower one, never both; no flash piece is held when the step wins |
| P.9 | instalments, coupons, min-order rules, delivery quotes | all use the step price |
| P.9b | instalment plans on the product page | `GET /e-commerce/installments/products/{productId}/plans?quantity=4` → each plan worked out on that quantity's total (4 × the step price); no `quantity` = 1 piece, the normal price (as before). `POST /e-commerce/installments/calculate-preview` now uses the product's own price for the quantity; `productPrice` in the request is no longer needed (ignored) |

#### 5.4 Bargain with quantity (D)
- `POST /live/streams/{id}/bargain/{productId}/offers` + **`quantity`** (default 1). The price is **per piece** and must be below
  the volume step for that quantity; `OFFER_QUANTITY` when not that many can be sold. Offers / answers (`LiveOfferView`)
  carry `quantity`; an accepted one becomes a chat offer for exactly that many.

#### 5.5 The cart with live tools (E3, E5, E6)
| # | What |
|---|---|
| P.10 | cart items + **`liveDeal`** `{flashId, price, endsAt, piecesLeft, maxPerPerson}` — the flash price this line gets at checkout now; nothing held until checkout |
| P.11 | coupons: a shop coupon is refused (`NO_COUPON_ON_FLASH`) only for a shop whose items have a flash price; a NexGate coupon comes off the non-flash items (refused only when every item has a flash price) |
| P.12 | live product card (`ProductDealCard`) + **`volumePrices`** and **`actions`**: the buttons in order — `BUY_NOW`, `ADD_TO_CART`, `JOIN_GROUP`, `BUY_ALONE`, `PAY_IN_PARTS`, `MAKE_OFFER`, `BID`; empty = nothing to buy |

---

### 6. Sale origins — where every sale came from (sale origins plan)

| # | Before | After |
|---|---|---|
| S.1 | taps recorded only in lives, meetings, calls (`…/attachments/{id}/tap`, `…/pins/…/tap`) | **one call for every place: `POST /sale-taps`** `{from, sourceId, item, itemId}` (live API doc #147). The old tap endpoints are **removed** |
| S.2 | a sale had an origin only when a tap was found; one origin for the whole order | **every paid checkout line has one** (`DIRECT` when nothing; `DOOR` for tickets sold at the door), **per item**: one cart can be "kanga from Mama Yoyo's live, bag from Neema's link, shoes from search" |
| S.3 | looked up when the order was made (a group filling days later, the last instalment → lost) | **stamped when paid** on each checkout line (`saleOrigin` inside the line); the order copies it whenever it's made |
| S.4 | — | a person or content who brought the buyer is never replaced by a later search / feed tap within 24 h; your own content / shop never counts |
| S.5 | — | reports: **`GET /sale-origins/shops/{shopId}?days=30`** (owner: orders + money per place, top 5 sources) · **`GET /sale-origins/events/{eventId}?days=30`** (organiser) · **`GET /sale-origins/mine?days=30`** (what your posts / links / lives brought: **counts only**) |

What the app sends: `POST /sale-taps` when the viewer opens an item **from** a live, meeting, call, post, clip, shared link
(the link carries the sharer's accountId), chat card or event page, and with `from: FEED / SEARCH / SHOP_PAGE / CATEGORY /
WISHLIST / NOTIFICATION` (no `sourceId`) from those places. Checkout requests don't change. The `saleOrigin` on checkout lines
is internal (the app can ignore it).

---

### 7. Events — part 2 (R2, R4, R5, R6, R7, R12, R13, R17, R18)

| # | Before | After |
|---|---|---|
| E4.1 | an online event whose organiser never went live: nothing happened | **R4**: 60 min after the start (of the last day), no live ever on air → every **online** ticket refunded; buyer gets `EVENT_BOOKING_CANCELLED` with `cancelledBy: "nexgate"`, `reason: "NO_SHOW"`, `refunded: true` |
| E4.2 | `otherAttendees[]` = name, phone, quantity | + **`accountId`** (online tickets only, quantity 1; `ONLINE_ONLY_GIFT` otherwise): that account holds the ticket, gets the Join button, watches on their own phone and is checked in; name / phone come from the account |
| E4.3 | online check-in once ever | **once per event day** (R12) |
| E4.4 | one fixed reminder ~24 h before | **R2**: `GET / PUT /e-events/booking-orders/{bookingId}/reminders` → `{bookingId, leads, choices, atStart}`; `leads` from `DAY_BEFORE · HOUR_BEFORE · MINUTES_15`; defaults online 24 h + 15 min, in person 24 h + 1 h; reminders already past when bought are never sent; `EVENT_BOOKING_REMINDER` + `lead`. "At start" for online is the existing `EVENT_ONLINE_STARTED` |
| E4.5 | one live for the whole event (the first day) | **R5**: the live is booked for the next day not over; when a day's live ends the next day's is booked and `roomId` (the Join button) moves to it |
| E4.6 | the event's live was always video | **R6**: `virtualDetails.liveMode` `VIDEO` (default) · `AUDIO` (event form, NexGate Live); event responses show it |
| E4.7 | a published event couldn't change where it happens | **R7 / R17**: `PATCH /e-events/{eventId}` + `virtualDetails` (Live ↔ Meeting ↔ Link until 1 h before the start → else `WHERE_LOCKED`; link / ID / passcode any time) and + `venue`; ticket holders get `EVENT_UPDATED` with `changed: where / link / venue` |
| E4.8 | venue = name, address, pin | **R18** + `directions`, `building`; **`shopId`** = "use my shop's location" (a shop you own; `NOT_YOUR_SHOP`, `SHOP_HAS_NO_LOCATION`) |

---

### Docs to refactor (not rewritten tonight — owner shares the old ones)

Filled in at the end of the build: which service's API doc needs which changes.

- **Events / fund claims**: claimable-amount fields (E1.1), claim refusals (E1.2), the 5 problem-report endpoints.
- **Events / check-in (scanner)**: `ONLINE_TICKET` status, sync leaves out online tickets (E2.2, E2.3).
- **Events / tickets + event form**: optional `attendanceMode`, `allowedTicketModes`, mode lock, format-change rules, reveal (E3); `liveMode`, venue `directions` / `building` / `shopId`, the published `PATCH` with `virtualDetails` / `venue` (E4.6–E4.8).
- **Event checkout / bookings**: `otherAttendees[].accountId`, the reminders endpoints, the no-show refund notice (E4.1, E4.2, E4.4).
- **Feed (home)**: `has-new` + `lives` (F.3); realtime `FEED_NEW` replaces `feed.new` / `NEW_POST` (F.1, F.2).
- **Feed (reels / clips)**: `kind`, `live`, `lives=true` (F.7).
- **Profiles, shops, search, suggestions, follow lists, comments**: the `live` ring field (F.11).
- **Realtime changelog 2026-11-25** (§3.2 lists `feed.new`): now `FEED_NEW`.
- **Products**: `pricingType`, `volumePrices`, `bulkFrom`, the `VOLUME_*` refusals (P.3, P.4).
- **Marketplace, search, wishlist, posts, clips**: `pricingType`, `bulkFrom` on their product cards (P.4b).
- **Cart**: `priceStep`, `nextStep`, `liveDeal` (P.5, P.10).
- **Instalments**: `quantity` on the plans list, `productPrice` ignored in the preview (P.9b).
- **Checkout (products)**: `skipLiveDeal`, `FLASH_PIECES_LEFT` / `FLASH_MAX_PER_PERSON`, item `priceStep` / `nextStep` / `aloneUnitPrice`, coupon rules (P.1, P.6, P.11).
- **Orders**: item `priceStepFrom` (P.7).
- **Sale origins** (new service): `/sale-taps` (in the live doc as #147), the three report endpoints (S.5).
- **Meetings / calls shelf docs**: the two `…/tap` endpoints are removed → `/sale-taps` (S.1).
- **Live API doc**: updated to v4.1 (fan-out + #87 card, #95 flash, #112 bargain).

---

### 8. Found while building (pre-existing, not changed tonight)

1. **Cancelling an event refunds nobody.** `EventServiceImpl.cancelEvent` has `// TODO: Trigger bulk refund for all ticket
   purchases`. The money stays in escrow. Biggest finding of the night — needs a decision (refund all at cancel, like R4 does
   for online tickets).
2. The gate's day and check-in-window checks are commented out "TODO: uncomment for production" (`TicketValidationServiceImpl`).
3. A booking's ticket `qrCode` in the booking response is always empty (`getQrCode()` is never set); the QR reaches people
   through the PDF and the notification.
4. Correction to the events plan: hybrid's "one of each" **was** checked at publish (`validateEventHasRequiredTickets`); only
   "every type fits the format" was missing (added).
5. Correction to the fan-out plan: the post nudge already went over Centrifugo; there were **three** "something new" pushes
   (`feed.new`, the old fan-out's `NEW_POST`, `LIVE_STARTED`) — now one `FEED_NEW`.
6. Local config has coupons off (`app.coupons.enabled`); the live tools boot check needs it on.

### 9. Morning list — choices made alone, check these

| # | What I did | Why / what to decide |
|---|---|---|
| M1 | Live fan-out chunks run **in-process** (keyset pages of 1,000 + one pipelined Redis call per chunk), not through Kafka | the nudge is a Redis check + one Centrifugo call per chunk; non-celebrity audiences are under 10,000 by definition. Move to Kafka if you want |
| M2 | The 30-s ranking is kept **in memory per container** (dropped whenever any live starts or ends), not in Redis | each container computes its own; See all paging uses a Redis snapshot so pages work across containers |
| M3 | `has-new.lives` items are `{streamId, mode, as, host, shop}` (the existing host / shop cards), not flat fields | same shapes as everywhere in live |
| M4 | "🔔 All lives" needs the follow / subscription (`NOT_FOLLOWING`), and only counts while it lasts | |
| M5 | Lives in clips: a live preview counts as watching after 3 s; < 2 s = a skip; 4 skips → none for 30 min; gap 25 → between 10 and 60 | plan numbers are mine; the recommendation-engine feedback seam is **not** built (only the per-person rate) |
| M6 | Sale origins: `CHAT` taps credit nobody (in a group, the sender isn't known) | credit the other person in 1:1 chats? |
| M7 | Own content = the person who brought them, or the **owner** of the product's shop / the event's organiser; shop **staff** are not excluded yet | |
| M8 | Sale origin reports: owner / organiser only (staff can't see them); no "taps → orders" rate (taps aren't counted per place) | |
| M9 | R4's job looks back 7 days: on the first run on staging it will refund **old test events** on NexGate Live that never went live | check staging data before deploying |
| M10 | R5: a multi-day event published in the middle of day 1 books tomorrow's live (today's is missed) | rare |
| M11 | R2: timed reminders go to the buyer; people given a ticket (R13) get "it's on now" but not the 24 h / 15 min ones | |
| M12 | R6: `liveMode` is set on the draft / create; a published event can't change it | |
| M13 | R17: a venue change is allowed to any place (the plan said "same city") and holders are told | lock to the same region? |
| M14 | No new notification types: no-show refund reuses `EVENT_BOOKING_CANCELLED` (`cancelledBy: nexgate`, `reason: NO_SHOW`); reminders add `lead`; R8 reports notify nobody (admin sees the list) | **workbook rows** to update / add |
| M15 | Volume pricing refusals use `ShopDeniedException` codes (`VOLUME_*`, 409) | |
| M16 | Flash `maxPerPerson` counts paid pieces per buyer in Redis for 6 h (`live:flash:bought:{id}`) | enough for a 1–10 min flash price |
| M17 | `schema.sql`: `sale_origins` drops its one-row-per-purchase unique constraint and makes `source_id`, `buyer_id` nullable | runs before Hibernate, guarded with `IF EXISTS`; on prod it changes the table — add to the prod deploy checklist |

### 10. Done before staging (2026-11-27 day, owner: "do all")

| # | What changed | What the app sees |
|---|---|---|
| 10.1 | **Cancelling an event refunds every ticket, in the background** (§8.1). The cancel only marks the event; once saved, each confirmed booking is refunded in its own transaction with the booking locked and checked again (never twice, across servers or retries). A safety job every 5 min finishes anything left after a crash. A booking whose money can't go back any more (already paid out) is marked `refund_problem` for an admin, never retried. The no-show refund (R4) uses the same path. | buyers get `EVENT_BOOKING_CANCELLED` with `reason: EVENT_CANCELLED`, `cancelledBy: organiser`, `refunded: true`; the booking becomes `REFUNDED` a few seconds after the cancel, not at once |
| 10.2 | **Claims**: money moves only when an admin approves (as before, now stated in the code). A cancelled event can't be claimed: `CLAIM_EVENT_CANCELLED` (409) on submit, admin-initiate and approve; claimable-amount says not eligible; a waiting claim is rejected at cancel. | new code `CLAIM_EVENT_CANCELLED` |
| 10.3 | Gate: the day and check-in-window checks are **on** again (§8.2). `events.gate.strict` (default true); staging may set it false to scan outside event hours. | scanning on the wrong day / outside the window is refused again |
| 10.4 | M6: a product card tapped in a **1:1 chat with a person** credits that person; groups and shop chats credit nobody. | — |
| 10.5 | M7: the shop's **staff** tapping their own shop's products (or the shop) never counts, like the owner. | — |
| 10.6 | M8: taps counted per shop / event, per place, per day (Redis, 400 days). Shop and organiser reports: each `byKind` row gets `taps`; a place with taps and no orders shows with `orders: 0`. | new field `byKind[].taps` on `/sale-origins/shops/{id}` and `/events/{id}` (null on `/mine`) |
| 10.7 | M5: a live preview in clips now feeds the recommendation engine: `VIEW` with `watchMs` (stayed ≥ 3 s) or `SKIP` (< 2 s), on the host's profile or the shop, surface `REELS`, source `LIVE`. | — |
| 10.8 | M11: timed ticket reminders also go to the people given an online ticket of the booking (R13), on the buyer's chosen times. | — |
| 10.9 | M13: kept — a venue change is allowed to any place; holders are told. | — |
| 10.10 | M14: workbook rows `EVENT_BOOKING_CANCELLED` (the reasons) and `EVENT_BOOKING_REMINDER` (chosen times, given-ticket holders, `lead`) updated. `FEED_NEW` is a realtime nudge, not a notification: it has no workbook row (it's in the live API doc Part D). | — |

Before staging: **M9** (the no-show job's 7-day look-back on old test events) and **M17** (schema) still stand;
`event_booking_orders.refund_problem` is a new column (Hibernate adds it).

---

<a id="part-10"></a>
# Part 10 — 2026-11-27 · Voice OTP

**Author**: Josh S. Sakweli, Backend Lead Team
**Version**: v1.0

**Short Description**: The app can offer a code by **voice call** next to SMS / WhatsApp / email, and **Resend** can now
switch channel. Plan: `docs/call_center/VOICE_PLAN.md`. The two reminder calls (shop, buyer) need nothing from the app.
Local on `fet/team`, not pushed.

---

### 1. The channel list after check: `VOICE`

`POST /api/v1/auth/passwordless/channels` may now list a fourth option:

```json
{ "channel": "VOICE", "masked": "••• ••• ••250", "isPrimary": false }
```

- Shown only for Tanzanian numbers (`+255…`) and only while voice is switched on for the server.
- Starting with it works like the others: `POST /api/v1/auth/passwordless/start` with `"channel": "VOICE"`.
- What the person hears (English): *"Your code is 4 8 2 · 9 1 3 … I repeat … Press 1 to hear it again."*

### 2. Resend can switch channel

`POST /api/v1/auth/resend-otp`

| Field | Type | Required | Description |
|---|---|---|---|
| `tempToken` | string | Yes | As before |
| `channel` | string | No | **New.** `SMS` · `WHATSAPP` · `SMS_AND_WHATSAPP` · `VOICE`. Absent → the same channel as before |

The answer gets a new field `channel` (the one actually used):

```json
{ "tempToken": "eyJ…", "maskedIdentifier": "••• ••• ••250", "channel": "VOICE", "remainingAttempts": 4, "expiresIn": 900 }
```

Suggested screen: after 60 s, one-tap pills — `[ Resend SMS ] [ WhatsApp ] [ 📞 Call me ]`.

Rules (the backend checks them; show its message):
| Case | Message |
|---|---|
| A code sent by email asks for another channel | "Channel VOICE is not available for this code" |
| VOICE for a number outside Tanzania | "Voice calls reach Tanzanian numbers only" |
| More than 3 voice codes to one number today | "Too many code calls to this number today; use SMS or WhatsApp" |
| Voice switched off on the server | "Voice calls are not available right now" |

### 3. Fixed: the resend limits now hold

Before, each resend returned a new token and the counter started again, so "5 resends, 60 s apart" never applied. Now
it is counted per phone number (or email) and purpose: the 2nd resend within 60 s gets "Please wait before requesting
another OTP", the 6th within 30 min "Maximum resend attempts reached". Show the message; `remainingAttempts` is right now.