# Logistics Service

# Guides (don't use)

# NexGate — Commerce, Location & Logistics Master Guide

> **Purpose.** This is the single reference for how buying, location and shipping work in NexGate.
> It captures every decision made so far and the reasoning behind each one, so that any
> implementer (human or Claude Code) can build from it, and future-you remembers *why*.
>
> **Companion file:** `location-service-spec.md` is the detailed build spec for the Location
> Service. This guide is the wider picture; that spec is the first thing to build.
>
> **Guiding rule for everything here:** simple over clever. No approval workflows, no features
> nobody asked for, no machinery a solo developer can't maintain. Where a simpler rule does the
> job, it wins.

---

## 0. The idea in one picture

NexGate is a social-commerce super app: users open **shops** to sell and **delivery businesses**
to ship, and buyers order and get goods delivered or collect them. NexGate never owns stock or
vehicles — it connects the three sides and holds the money safely in between.

```
            ┌──────────────┐     browse / order / pay      ┌──────────────┐
            │    BUYER     │ ───────────────────────────►  │   NexGate    │
            └──────────────┘ ◄───────────────────────────  │  (platform)  │
                   ▲   collect / receive + confirm (code)   │   + escrow   │
                   │                                        └──────┬───────┘
                   │                                   recommends & books
                   │                                               │
         ┌─────────┴─────────┐                        ┌────────────┴───────────┐
         │   SHOP (seller)   │  hand over + code      │  DELIVERY BUSINESS     │
         │  items, location  │ ─────────────────────► │  (shipper) moves goods │
         └───────────────────┘                        └────────────────────────┘

  Money path:  Buyer → escrow → (on delivery code) → seller wallet + shipper wallet + NexGate fee
```

Everything in this guide hangs off two services:

1. **Location Service** — *where* things are. The foundation. Built first.
2. **Shipping Service** — *how* goods move. Built on top of Location.

---

## 1. Core principles (apply everywhere)

1. **The pin (lat/lng) is the single source of truth** for any place. Text is only a label.
2. **Location is collected only for a stated reason**, never on app open, never as background tracking.
3. **The administrative hierarchy (region/district/ward) comes from NexGate's own data**, computed
   from official NBS ward boundaries. Google is used **only on the client** for the map, place
   search and the live label — never called from the backend, never stored.
4. **Orders freeze a copy** of every address and price. Later edits never change a past order.
5. **Users own businesses; businesses earn into the owner's one wallet.** Shops sell, delivery
   businesses ship. Same ownership model for both.
6. **Money is held in escrow and released on a delivery code.** Proof of handover, not trust.
7. **One shipment = one pickup (one shop) → one shipper → one drop-off.** No multi-stop.
8. **Accept orders 24/7; be honest about timing.** Closed hours delay the work, never the sale.
9. **Shippers describe their own pricing and coverage.** NexGate never forces a pricing model.
10. **Trust is automatic, not a manual queue** — phone verify, limits that grow with good history,
    ratings, and auto-pause on repeated failure.

---

## 2. Location Service (foundation)

> Full build detail is in `location-service-spec.md`. This is the summary.

### 2.1 What it owns
- Tanzania ward boundaries (NBS 2022) and **pin → region / district / ward** resolution
- **Shop locations** (one per shop, mandatory to publish)
- **Buyer saved addresses** (many, optional) and **recent locations**
- **Order address snapshots** (frozen copies)
- **Stations** and future **zones** (same shape-based pattern)
- Privacy rules for who sees which part of a location

### 2.2 How a pin becomes a place

```
          📍 confirmed pin (lat, lng)
         /                           \
  NBS ward shapes (ours)          Google (client only)
  region, district, ward, codes    "Mlimani City, Sinza Mori…"
       │                                │
    STORED (truth)              shown while placing the pin only
                                (never sent to backend, never stored)
```

The lookup is a point-in-polygon test in PostGIS: *which ward shape contains this point?* It runs
in milliseconds thanks to a spatial (GIST) index. If no ward contains the pin (beaches, lakes,
borders), fall back to the **nearest ward within 500 m**; beyond that, the pin is "outside coverage".

### 2.3 The ward data (done)
- Source: **NBS 2022 Population & Housing Census — Tanzania Wards shapefile** (official, ~3 m accuracy).
- Already converted to **GeoJSON WGS84 (EPSG:4326)**, geometries repaired, delivered as
  `tz_wards_2022.geojson.gz`.
- **4,344 wards, 31 regions.** Primary key is `ward_id` (1–4344) because NBS codes are not unique.
- Loaded by a startup **seeder** (no Flyway, no version tracking) into PostgreSQL + PostGIS.
- The data file lives outside Git (`data/geo/`, mounted read-only into the container).

**District and region need no separate data.** Every ward row already carries its council, district
and region names + codes, so one pin lookup returns all levels at once. Coverage checks and reports
just use the stored codes. The only case needing a district/region *shape* is drawing an outline on
a map — build it on demand by dissolving wards (`ST_Union(geom) GROUP BY reg_code[, dist_code]`),
never store a second dataset.

### 2.4 Address capture UX (same pin screen everywhere)
- **Never ask for location on app open.** Ask only when the user taps "Use my location".
- **Fixed centre pin, the map moves** under it (Bolt/Uber pattern). Satellite toggle. Accuracy circle.
- **Confirm disabled until zoomed to street level.** Search only moves the map, never confirms.
- **Shop:** pin + landmark + phone required (+ optional building, official address, photo). Mandatory.
- **Buyer:** pin + optional rider note only. Pin-only, Bolt style. Saving is optional; many saved
  addresses, plus recents.

---

## 3. Shipping Service (built on Location)

### 3.1 The whole shipping picture

```
                          ┌───────────────────────────────┐
                          │   RECOMMENDATION ENGINE        │
   order (items, value,   │   1. read situation            │   ranked options:
   pickup+dropoff wards,  │   2. gather eligible shippers  │   💰 Cheapest
   bulky?) ──────────────►│   3. filter (coverage/limits)  │──►⚡ Fastest
                          │   4. price each                │   ⭐ Recommended
                          │   5. rank & label              │
                          └───────────────┬────────────────┘
                                          │ one standard contract per shipper:
                                          │ covers? · quote · book · cancel · status
                     ┌────────────────────┼─────────────────────┐
                     ▼                                          ▼
          ┌───────────────────┐                     ┌───────────────────────┐
          │ NATIVE shipper    │                     │ INTEGRATED shipper    │
          │ (NexGate business)│                     │ (external API)        │
          │ tables + app/SMS  │                     │ Bolt, DHL… adapters   │
          └───────────────────┘                     └───────────────────────┘
```

### 3.2 Two classifications of every shipper

A shipper is described by **two independent fields**:

**A. Service type — how goods move**

| Type | How it works | Coverage set by | Examples |
|---|---|---|---|
| **🚪 Door-to-door** | Picks up at seller, delivers to buyer | Areas (ward/district/region, or nationwide) + optional max distance | Boda groups, Kibuti Express, **DHL / EMS** (wide area) |
| **🚌 Station** | Seller drops at a station, buyer collects at a station | Stations (pins) + lanes between them | Bus companies, truck offices |

> "Local" vs "intercity" is **not** a separate type — it falls out of how wide the area is.
> DHL is just door-to-door with a nationwide area.

**B. Connection — how NexGate talks to them**

| | **Native** (NexGate business) | **Integrated** (external API) |
|---|---|---|
| Set up by | The owner, in the app | NexGate, once, in code + admin |
| Pricing | Owner's tables | Live from their API |
| Jobs arrive | App notification + SMS/WhatsApp link | NexGate calls their API |
| Status | Owner taps buttons / link | Their webhooks or polling → mapped |
| Money | Into owner's NexGate wallet | NexGate pays them; they invoice NexGate |
| New one | Zero code (user signs up) | One adapter per company |

They combine freely: a native door-to-door rider, a native station bus, integrated Bolt, integrated DHL.

### 3.3 One standard contract (why the engine never changes)

Every shipper, native or integrated, answers the same five questions. That's all the engine knows:

```java
boolean covers(pickupWard, dropoffWard);     // area / lane check
Quote   quote(order);                         // price + ETA
Booking book(order);                          // returns a reference
void    cancel(ref);
Status  status(ref);                          // mapped to NexGate statuses
```

- **Native** answers from the owner's tables and app/link updates.
- **Integrated** answers by calling the company's API.

**Standard status ladder** (every provider's own statuses are translated into this, so the buyer's
tracking screen never changes):

```
CREATED → BOOKED → PICKED_UP → IN_TRANSIT → AT_STATION → OUT_FOR_DELIVERY → DELIVERED
                                                   ↘ FAILED / CANCELLED / RETURNED
```

### 3.4 Adding a provider = data, not code (for native)

```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  Add delivery business
┆ Name:    Shabiby Bus Parcels          ┆
  Type:    ○ Door-to-door  ● Station
┆ Connect: ● Native  ○ Integrated (API) ┆
  Contact: +255 7XX…  (booking line)
┆ ───────────────────────────────────── ┆
  Coverage
┆  Door-to-door → pick areas            ┆
   Station      → add stations + lanes
┆ Pricing method (§3.6)                 ┆
  Limits: max distance / max value
┆ Bulky:  ○ No  ● Yes (+extra)          ┆
  Settlement: ● Wallet  ○ Pay at station
┆ [ ] Enabled                           ┆
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

Integrated providers (Bolt, DHL) enter nothing here; their adapter handles it.

### 3.5 Coverage: picked from what the system already knows

**Door-to-door → areas** (from the region → district → ward list, or nationwide):
```
Mbeya Riders   🚪  area: Mbeya district        → local only
Kibuti Express 🚪  area: Dar + Pwani           → regional
DHL / EMS      🚪  area: nationwide            → intercity door-to-door
```
Offered only when **both** pickup and drop-off pins fall inside its area.

**Station → stations + lanes** (each station is a pin resolved to a ward, like a shop):
```
Shabiby Bus 🚌
  Stations: Mbeya Stand · Magufuli Terminal (Dar) · Dodoma Terminal
  Lanes:    Mbeya ↔ Dar   · Mbeya ↔ Dodoma
```
Offered when it has a station near pickup **and** near drop-off. Buyer sees nearest stations first.
Optionally a station shipper also delivers to the door around a station (then it also picks areas).

**Routes with multiple stops on the way.** A bus line usually stops at several towns in order
(Mbeya → Iringa → Morogoro → Dar). The shipper enters **one route = an ordered list of its stations**,
not every pair of lanes. The system then treats **any earlier stop → any later stop** on that route
as a valid trip (both directions if the route runs both ways):

```
Route "Mbeya–Dar daily"  (both ways)
  1. Mbeya Stand   2. Iringa Office   3. Morogoro Stand   4. Magufuli (Dar)
  → valid trips: Mbeya→Iringa, Mbeya→Morogoro, Mbeya→Dar,
                 Iringa→Morogoro, Iringa→Dar, Morogoro→Dar (+ reverses)
```
4 stops → all pairs auto-derived. Add a 5th stop and its new pairs appear at once.

**Pricing along a route** (shipper's choice):
- **A. Per segment, summed** — one price per gap between neighbours; a longer trip is the sum
  (`Mbeya→Dar = Mbeya→Iringa + Iringa→Moro + Moro→Dar`). Simplest to keep accurate.
- **B. Stop-to-stop table** — a full price per pair, when it isn't a clean sum (e.g. a long-haul discount).

Plus the usual value add-on (insurance) and bulky extra. First/last mile to a buyer not near a stop
is added as a separate local door-to-door leg, each with its own code — unchanged.

> A **lane** is just the special case of a route with two stops. Model everything as routes.

### 3.6 Pricing — the shipper chooses the model, NexGate never forces one

At registration the shipper picks **one** method:

```
How do you charge?
 ○ Flat price
 ○ By distance            (bands: 0–3 km, 3–7 km, …)
 ○ By package value       (ladder: insurance — the shipper carries the risk)
 ○ By distance + value    (added together)
 ○ Combined table         (distance × value grid, each cell a full price)
```

Plus, on top: **bulky extra** (if accepted), **max distance** and **max value** (filters, only when set).

**Why value-based for parcels:** the shipper holds the insurance, so charging by the goods' value
is fair, and "max accepted value" caps their risk. Quantity is handled for free — more items means
a higher order value.

**Distance** is measured from the two pins: start with straight-line × 1.3 (free, instant), switch
to a routing service later if needed without changing shipper tables.

```
Examples (5 km trip, phone worth 800,000):
  Mbeya Riders     distance only      3,500
  Shabiby (lane)   value only        20,000
  Kariakoo courier distance + value   3,500 + 3,000 = 6,500
  Combined table   (3–7km × 500k–2M)             7,000
  Small rider      flat               3,000
```

### 3.7 Package info — minimal

No size or weight. Only:
- **Order value** — from the cart, automatic.
- **Bulky? (yes/no)** — one checkbox on the product (category can pre-tick furniture, fridges).
  Shippers that don't accept bulky are filtered out. A fridge never gets offered a motorbike.

**Vehicle type is not needed** — "bulky vs not" is the only decision it would inform. Shippers may
add a vehicle **badge** for display only (e.g. "Boda", "Pickup"); it drives no logic. Integrated
providers (Bolt) pick the vehicle category inside their adapter.

**Mismatch rule:** if the real package differs (bulky not ticked), the extra cost is the **seller's**
(they chose), the buyer's price never changes after payment, and repeated mismatches auto-correct
the product's bulky flag.

### 3.8 Who enters what

| Party | At setup (once) | Per order |
|---|---|---|
| **Seller** | Shop location, landmark, phone | `[ ] Bulky` (usually none); tap "Ready for pickup" |
| **Shipper** | Coverage + one pricing method + limits + bulky | Tap link; update status |
| **Buyer** | — | Pick a delivery pin; tap one option (Cheapest/Fastest/Recommended) |

The system works out the rest: value, bulky, pickup+drop-off wards, eligible shippers, price, ranking.

### 3.9 The recommendation engine, step by step

```
1. WHERE   pickup ward + drop-off ward → same district / same region / different region
2. WHO     shippers whose coverage (areas / lanes) includes both wards
           + build station + door-to-door combinations where needed
3. FILTER  drop any that fail a hard rule:
             area/lane not covered · over max distance · over max value
             · bulky needed but not accepted · closed & past cut-off (→ ETA shifts, not dropped)
             · provider currently auto-paused (repeated failures)
4. PRICE   live quote (integrated) or the shipper's table (native)
5. RANK    score by price · speed · reliability(history); weight by situation
           (urgent → speed; cheap item → price; expensive → reliability)
           label 💰 Cheapest / ⚡ Fastest / ⭐ Recommended; drop absurd outliers
```

**Backup:** if the chosen shipper fails (no pickup, cancels), auto-offer the next best and tell the buyer.

**Reliability needs history**, so at launch show only **Cheapest** and **Fastest**; add
**Recommended** once real delivery data exists. Reliability is your long-term moat — competitors
can copy features, not your data.

### 3.10 Shipper onboarding: register → KYC → go live

Shippers handle other people's goods and money, so onboarding has three parts. KYC gates **going
live**, not filling the form — let them build the profile, then verify to switch on. Trust then
grows automatically; **no manual approval queue** except on a flagged exception.

```
Register (6-step form) → KYC verify → GO LIVE (low limit) → limits & badge grow with history
```

**Registration form (a short wizard, save-as-draft, admin can fill it for offline shippers):**

| Step | Fields | Feeds the engine as |
|---|---|---|
| 1 Basics | name · service type (DOOR/STATION) · booking phone · WhatsApp? · logo | identity, notify, branches next step |
| 2 Coverage | DOOR: areas (region/district/ward) or radius-from-base · STATION: stations + routes | **coverage check** |
| 3 Pricing | method (flat/distance/value/dist+value/grid; route segment or table) · bulky yes/no (+extra) | **quote** |
| 4 Limits & alerts | max value · max distance · won't-carry list · response window (default 30 min) · advance heads-up (default ON) | **filters**, job alerts (§4.3a) |
| 5 Hours & money | opening hours + cut-off · settlement (wallet / pay-at-station) · payout account | **ETA/availability**, money routing |
| 6 Verify | phone OTP · agree shipper terms (liability up to declared value) | go live |

Minimum to go live = steps 1–3; steps 4–5 have working defaults; step 6 is just verify. A one-man
rider finishes in ~2 min; a bus company takes longer only because it adds stations.

**KYC — fast, tiered, mostly automatic:**

```
Tier 0  phone verified            → register, build profile (not live)
Tier 1  + NIDA + ID photo + selfie match  → GO LIVE, low max value (e.g. 200,000/order)
Tier 2  + payout name matches NIDA → higher limit
Tier 3  good history (N jobs, rating, low failures) → higher limit + "Verified" badge
```
- Auto-checks first (OTP, face-match selfie↔ID, name-match payout↔NIDA). Pass → live, no human.
- The **mobile-money number is itself a KYC signal** (already tied to a real NIDA in TZ).
- Manual review only on a flag (blurry ID, mismatch) — a small queue, not every shipper.
- **Sellers** get a lighter version of the same module (phone + NIDA + payout match before first payout).

**Licences & compliance — collect now, confirm mandatory ones with a professional later.**
Store each as *document type + file + expiry*. Mark required/optional per shipper type & tier once
advised. Non-blocking at launch; uploading the real ones earns a **"Verified business"** badge.

| Group | Documents (collect if the shipper has them) |
|---|---|
| Identity & business | NIDA · TIN (TRA) · BRELA (business name / company) · local-govt **business licence** · VAT (VRN) if over threshold |
| Transport / courier | **LATRA** licence (road carriage of goods/passengers — replaced SUMATRA) · **TCRA** courier/postal licence (door-to-door couriers) · TASAC (if freight-forwarding) |
| Vehicle & driver (own fleet) | vehicle registration · commercial/PSV licence · motor insurance (+ goods-in-transit) · driving licence · inspection/fitness |
| Employees (if any) | NSSF · WCF · OSHA |
| Money / insurance | mobile-money/bank payout · goods-in-transit / cargo insurance |

> ⚖️ **Flag (not legal advice):** which licences are legally mandatory — especially **LATRA** for
> goods carriage and **TCRA** for courier services — and NexGate's own liability as the connecting
> platform, plus KYC/AML and escrow rules (Bank of Tanzania), must be confirmed with a Tanzanian
> lawyer / compliance professional. See §8.

---

## 4. Order & money flow

### 4.1 Checkout — pickup or delivery, per shop

Each shop in the cart is its own shipment, so the choice is per shop:

```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  Deliver to: 🏠 Home, Mbezi Juu
┆ 🏪 Shop A · Kariakoo · 2 items        ┆
   ○ Pickup at shop            Free
┆  ● Delivery 🚪 Kibuti Express 4,000 ▾ ┆
  🏪 Shop B · Sinza · 1 item
┆  ● Pickup at shop            Free     ┆
   ○ Delivery
┆ 🏪 Shop C · Mbeya · 1 item            ┆
   ● Delivery 🚌 Shabiby       20,000 ▾
┆ ─────────────────────────────────────┆
  Delivery total (2 deliveries) 24,000
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

- **One shipment = one shop → one shipper → one drop-off.** No multi-stop, ever.
- A 3-shop cart = 3 shipments, each with its own shipper, price, codes and escrow release.
- **Pickup** also uses escrow + a code (buyer shows code at the shop; seller enters it).

### 4.2 Escrow + delivery codes (proof of handover)

```mermaid
sequenceDiagram
    actor Buyer
    participant NexGate as NexGate (escrow)
    participant Seller
    participant Shipper
    Buyer->>NexGate: pay (item + delivery)
    Note over NexGate: funds held in escrow
    Seller->>Shipper: hand over + SELLER pickup code
    Shipper->>NexGate: enter pickup code (proves shipper has it)
    Shipper->>Buyer: deliver
    Buyer->>Shipper: give DELIVERY code
    Shipper->>NexGate: enter delivery code
    Note over NexGate: release:
    NexGate->>Seller: item price − commission
    NexGate->>Shipper: delivery fee − commission
    NexGate->>NexGate: commissions
```

**Code rules (decided):**
- **Pickup code** (seller → shipper): proves the shipper received the parcel — matters if it's lost.
- **Delivery code** (buyer → shipper): releases the money.
- **Station collection:** buyer gives the code to station staff, who enter it. Same as door-to-door.
- **Multi-leg trips** (rider → bus → rider): **each handover has its own code**, so each leg is paid
  as soon as it's done — the first-mile rider isn't left waiting days for a small fee.

**Open decisions to finalise (see §8):** buyer unreachable / forgets code; item wrong or damaged
after code; return window; cancellation cost.

### 4.3 Switching pickup ↔ delivery after ordering

```
Order placed as PICKUP → "Get it delivered instead"
   → pick drop-off pin → fresh delivery quotes (today's prices)
   → pay delivery fee only → into escrow → shipment created, seller notified
   Allowed until the buyer has collected.

Order placed as DELIVERY → "Collect it myself"
   → allowed only BEFORE the shipper has picked it up
   → delivery fee refunded to the buyer
```

### 4.3a When the shipper is contacted — offer at "Ready", not before

The seller has **two separate actions**, and the shipper is only offered the job at the second one:

```
Order arrives → seller ACCEPTS (yes, I'll fulfil)   ← shipper NOT contacted yet
             → seller PACKS
             → seller taps READY FOR PICKUP          ← NOW the binding offer goes to the shipper
```

Offering at **Ready** (not at Accept) means: no shipper rides over to wait while the shop packs; if
the seller can't fulfil, the order dies before any shipper was bothered; and the ETA/response-window
start from a real ready moment.

**Heads-up (optional, per-shipper setting — default ON, can be disabled).** So shippers can plan
without being booked early, NexGate sends a **non-binding** heads-up when the seller accepts/starts
packing. It commits nothing and starts no timer:

```
On seller accept/pack →  Heads-up (no commitment):  "Order coming from Sinza, ~15 min. Be ready?"
On seller READY       →  Binding OFFER + response window (30 min) starts   ← the one that counts
```

- The heads-up is a shipper **preference**: `Advance heads-up [✓] (default on)`. A shipper who finds
  it noisy turns it off and only sees the binding offer at Ready.
- **Re-check at Ready:** if packing ran long and the chosen shipper has since **closed / passed
  cut-off**, the engine re-evaluates at Ready — same shipper still open → offer it; otherwise fall
  into normal reassignment (§4.4). A slow pack never leaves the order stuck with an offline shipper.

### 4.4 Shipper rejects the job → auto-reassign

A shipper can decline an offered shipment (too far, too busy, bulky they can't carry, value too
high, closed). This must resolve cleanly, because it touches money. Two rules make it safe:

1. **Escrow holds two parts — item money and delivery money.** A rejection only touches the
   **delivery** part. The **item money stays held, and the seller never re-approves** — their job
   ended at "ready".
2. **The buyer's agreed price is protected.** The system can reassign silently only if it holds that
   price or beats it; a *higher* price needs the buyer's yes.

**The flow:**

```
Seller taps READY (§4.3a) → shipment OFFERED to chosen shipper (delivery fee held)
   → shipper has a response window (e.g. 30 min, or until they next open)
        ├─ ACCEPT          → pickup (code) → normal flow
        └─ REJECT (reason) or TIMEOUT
              → that shipper's delivery fee released back in escrow
              → shipment = REASSIGNING, recompute options excluding rejecters
```

```mermaid
flowchart TD
    A[Shipper rejects / times out] --> B{Next-best shipper?}
    B -- none --> C[Buyer: switch to pickup refund, or cancel full refund]
    B -- same price or cheaper --> D[Auto-book next · refund difference to wallet]
    D --> E[Notify buyer: new courier, same price · NO action needed]
    B -- costs more --> F[Delivery money to buyer wallet · show fresh options+prices]
    F --> G[Buyer picks one · pays difference from wallet]
    G --> H[New shipper acts]
    E --> H
```

- **Same or cheaper → auto, buyer does nothing** (just a notification). The system walks **down the
  ranked list on its own** — shipper 1 rejects → shipper 2 auto-assigned → acts, and so on.
- **Dearer → buyer confirms** the new price (pays the difference from wallet, or gets a refund).
- **None left → buyer chooses** pickup (delivery refunded) or cancel (full refund).
- **Reason feeds reliability.** Chronic rejecters sink in the rankings and can auto-pause.
- **Loop guard:** cap auto-reassign at ~3 tries (or the order's handover window); after that, hand
  it to the buyer so a shipment never spins forever.

> There is **no repeated approval** — the seller is out of it after "ready", and the buyer is pulled
> in only when the price would rise or nobody is left. Otherwise the system does the chasing.

---

## 5. Free shipping

Two funders, same mechanism. The shipper is **always paid in full**; the discount is covered by
whoever offered it, deducted at escrow release.

### 5.1 Seller-funded (per shop or per product)

```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  Free delivery (shop setting)
┆ [✓] Offer free delivery              ┆
  Where:  ○ Within [5] km of shop
┆         ● Areas: Ubungo, Kinondoni   ┆
  When:   order over [50,000] (opt.)
┆ I pay up to: [5,000] per delivery    ┆
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
Product override:  ● Use shop setting  ○ Always free  ○ Never free
```
Uses your ward boundaries and pin distance to decide eligibility. The **cheapest qualifying option**
becomes free; a faster choice costs the difference. The **cap** protects the seller (buyer pays the
rest above it). In a mixed shipment, free only if **every** item qualifies.

### 5.2 NexGate-funded (campaigns)

```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  Campaign: Free delivery Dar weekend
┆ Areas: Dar es Salaam · Dates: 10–12 Oct
  Min order: 30,000 · NexGate pays up to 3,000
┆ Who: First order only · Shops: All    ┆
  Total budget: 2,000,000 → auto-stops
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

**Stacking** (seller first, then NexGate):
```
delivery price            7,000
− seller pays (cap 4,000) −4,000
− NexGate pays (cap 3,000) −3,000
= buyer pays                  0
```
A **total budget** auto-stops the campaign — no runaway cost. Each shipment records **who paid what**.

---

## 6. Opening hours & orders outside hours

### 6.1 Hours apply to three things

| Who | Why |
|---|---|
| **Shops** | Pickup availability; when a shipper can collect |
| **Delivery businesses** | Offered as "today" only when working; else ETA shifts |
| **Stations** | Where buyers collect parcels (often different hours from the company) |

### 6.2 Hours editor (same screen everywhere)
```
Mon–Fri  08:00–13:00 · 14:00–18:00      ← several ranges per day (lunch break)
Sat      09:00–15:00
Sun      Closed
Special days: 25 Dec Closed · 9 Dec 10:00–14:00   ← override weekly (holidays, Eid)
[ ] Temporarily closed (one-tap pause)
Same-day cut-off: 16:00 (shippers)       ← after this, pickup = next opening
```
All times **EAT (UTC+3)**. Overnight ranges (18:00–02:00) allowed.

### 6.3 Orders outside hours — accept 24/7, be honest

```
Order at Fri 22:00, shop opens Sat 09:00
  ○ Pickup   → "Ready from Sat 09:00"
  ● Delivery → "Arrives Sat ~12:00–15:00"
```

Rules:
- **Always accept orders.** Blocking a night buyer loses the sale.
- **Seller notified at once, but timers start at opening.** "Accept within 2h / ready within 24h"
  pauses while closed — a 22:00 order isn't overdue at 07:00.
- **Shipper jobs are scheduled, sent at the shipper's opening** (not midnight). Shipper may accept early.
- **Handover time** = first moment the **shop AND shipper are both open** (after "ready", before cut-off).
  **ETA** = handover + the shipper's normal delivery time, skipping their closed hours.
- **Temporarily closed** → seller chooses "still accept (ships when back)" or "stop orders (hide Buy)".
- **Safety net:** if the seller never acts within 24 *opening* hours → auto-cancel + refund from escrow.

---

## 7. What we learned from others (and what to copy / avoid)

| Topic | Jumia / Glovo / Uber / Bolt do… | NexGate decision |
|---|---|---|
| Ordering when closed | Pre-order / scheduled | ✅ Accept 24/7, show real time |
| Delivery choice | Door vs pickup station, options with price+ETA | ✅ Per shop, Cheapest/Fastest/Recommended |
| Money safety | Escrow + 4-digit code | ✅ Have it |
| Seller onboarding | Heavy docs + approval queue | ❌ Avoid — phone verify + auto-limits |
| Surge pricing | Uber/Bolt dynamic | ❌ Avoid — shipper ladders are clearer |
| Separate rider apps | Yes | ❌ Avoid — NexGate deals with the business, not riders |

**To add from others (currently gaps):**
1. **Problem-report window** — buyer can report a problem within ~24h of delivery before escrow releases.
2. **Two-way ratings** — rate the buyer too (bad address / no-show), so shippers aren't stuck with them.
3. **Cancellation policy with cost** — who pays when a buyer cancels after the shipper collected.
4. **Late-handover consequence** — feed seller late handovers into the same reliability score shippers have.
5. **Address quality nudges** — already helped by pin + landmark + ward check.

---

## 8. Open decisions to finalise before building Shipping

| # | Decision | Suggested default |
|---|---|---|
| 1 | Buyer unreachable / forgets delivery code | Shipper marks "Delivered, no code" + photo → buyer 48h to dispute → else auto-release |
| 2 | Item wrong/damaged after code | Short report window (24h) before release, or code = final |
| 3 | Lost / damaged parcel | Shipper liable up to declared value; refund from shipper wallet; pickup code shows who held it |
| 4 | Cash on delivery (COD) | **Prepaid only at launch**; add "accepts COD" per shipper later |
| 5 | Escrow legality | **Check with a lawyer / payment partner** (BoT, National Payment Systems Act) — *not legal advice* |
| 6 | Cancellation cost | Free before pickup; buyer bears shipper's cost after pickup |
| 7 | Bolt for parcels | **RESOLVED (confirmed with Bolt): no parcel/delivery API in Tanzania — passenger rides only.** Bolt is out as a shipper; rely on native shippers. Bolt only relevant if NexGate later adds an in-app passenger-ride feature (separate from shipping). |
| 8 | Mandatory licences & platform liability | Which of LATRA / TCRA / business licence etc. are required per shipper type, and NexGate's liability as connector — **confirm with a Tanzanian lawyer / compliance pro** (§3.10) |
| 9 | KYC / AML level | How much identity NexGate must verify & keep for shippers and sellers holding escrowed money — confirm with payment partner / lawyer |

---

## 9. Note on the Bolt Ride Booker API (reference)

> **Confirmed with Bolt (Oct 2026):** no parcel/delivery API in Tanzania — passenger rides only.
> So Bolt is **not** a NexGate shipper. This section is kept only for a possible future **in-app
> passenger-ride** feature (separate from shipping). Prime Stack already has a Bolt **Business**
> account (ride billing), which is *not* the same as Ride Booker API access.

The API doc shared earlier is a **reseller passenger-ride** API, useful as a model for *integrated*
providers but **not a parcel API**. Key facts if it's ever used (e.g. in-app rides):

- **Auth:** OAuth2 client credentials, 10-minute tokens, backend-only (never in the mobile app).
- **`fare_id` is fragile:** expires in 5 min, single-use, stops must match the estimate exactly.
  On `INVALID_FARE_ID`, re-estimate and retry.
- **Tracking:** poll ride every 10 s / driver every 1 s; webhooks live-only (not sandbox), send just
  `ride_id`/`type`/`state`, whitelist Bolt's 3 IPs.
- **States aren't linear** (can bounce SEARCHING ↔ DRIVER_ON_ROUTE); final price can change for 24h+.
- **Doc quirks:** garbled Cancel section, misspelled `reseler` destroy URL, `Fare_id` capitalised once.
- **Before use:** confirm Ride Booker is enabled for Tanzania, currency and payment setup (samples
  are Tallinn/EUR).

For NexGate's **parcel** shipping, native shippers matter far more than Bolt. Treat any Bolt/DHL
integration as one adapter behind the standard contract (§3.3).

---

## 10. Build order (roadmap)

```
Phase 1 — Location Service  ◄── START HERE (spec + data ready)
  Docker PostGIS · seeder · pin resolution · shop location · buyer addresses · snapshots

Phase 2 — Native Door-to-door shipping, one city
  Delivery business type · coverage (areas) · one pricing method · bulky flag
  Escrow + pickup & delivery codes · prepaid only · status via app/SMS link
  Checkout: pickup/delivery per shop · Cheapest + Fastest only

Phase 3 — Station shipping (intercity)
  Stations + lanes · multi-leg codes · collect-at-station

Phase 4 — Recommendation engine grows
  Reliability scores from history → add "Recommended"
  Free shipping (seller + NexGate campaigns) · opening-hours scheduling

Phase 5 — Integrated providers
  Integrated adapters behind the standard contract — e.g. DHL (confirm parcel APIs first).
  NOT Bolt: confirmed no parcel API in TZ (rides only).

Cross-cutting (fold in as you go): two-way ratings, problem-report window,
cancellation policy, late-handover scoring.
```

**Do first:** sign up your own first shippers (a few boda groups + one bus company) in one city —
recommendations are worthless with no shippers.

---

## 11. Data model sketch (shipping — for when you build it)

> Logical only. Follow the project's ID type, audit and error conventions. All areas/stations point
> to the **ward / district / region codes** from the Location Service — no new map data needed.

```
delivery_businesses   owner_user_id, name, service_type(DOOR|STATION),
                      connection(NATIVE|INTEGRATED), adapter_name?, contact_phone,
                      accepts_bulky, bulky_extra, max_distance?, max_value?,
                      response_window_min(default 30), advance_headsup(default true),
                      settlement(WALLET|PAY_AT_STATION), enabled, rating, reliability

business_areas        business_id → region/district/ward codes it serves   (DOOR)
business_stations     business_id, name, pin(lat,lng), ward_id, phone, hours (STATION)
business_routes       business_id, name, both_ways                          (STATION)
route_stops           route_id, station_id, stop_order                      (ordered list)
                      → valid trip = earlier stop_order → later stop_order on same route
                        (a 2-stop route is just a "lane")
pricing_rules         business_id, method(FLAT|DISTANCE|VALUE|DIST_VALUE|GRID),
                      bands/ladder/grid as JSON
route_pricing         route_id, mode(SEGMENT|TABLE),
                      segment prices between neighbours, or stop-to-stop table (STATION)

opening_hours         owner_type(SHOP|BUSINESS|STATION), owner_id,
                      weekly ranges, special_days, temp_closed, same_day_cutoff

shipments             order_id, shop_id, shipper_business_id, service_type,
                      pickup_snapshot, dropoff_snapshot (frozen),
                      price, who_pays(buyer/seller/nexgate split),
                      status(OFFERED|ACCEPTED|REASSIGNING|PICKED_UP|IN_TRANSIT|
                             AT_STATION|OUT_FOR_DELIVERY|DELIVERED|FAILED|CANCELLED),
                      offer_expires_at, reassign_count,
                      pickup_code, delivery_code, leg_no?
shipment_offers       shipment_id, business_id, state(OFFERED|ACCEPTED|REJECTED|TIMEOUT),
                      reject_reason?, offered_at, responded_at   (one row per attempt)
shipment_legs         shipment_id, from, to, provider, status, cost, code   (multi-leg)

escrow_holds          order_id, item_amount, delivery_amount,
                      state(HELD|RELEASED|REFUNDED), breakdown   (two parts: item + delivery)
campaigns             areas, dates, min_order, cap_per_delivery, budget, audience, active
```

---

## 12. Worked examples (engine walk-throughs)

> Illustrative numbers only. Shows the 5-step engine (WHERE · WHO · FILTER · PRICE · RANK) end to end.
> Reminder of the rules: **value → price + insurance**, **bulky → vehicle/who can carry**,
> **quantity flows into value by itself**, hours & limits filter, area/route decides eligibility.

### The registered shippers (set up once — used by all examples)

```
① Mbezi Boda        🚪 DOOR · Native
   Areas: Kinondoni, Ubungo (Dar)      Pricing: distance
     0–3km 2,000 · 3–7km 3,500 · 7–15km 5,000 · max 15km
   Bulky: NO        Hours: 07:00–20:00

② Dar Cargo         🚪 DOOR · Native
   Areas: whole Dar es Salaam region   Pricing: distance + value
     dist: 0–5km 4,000 · 5–15km 7,000   value add: >500k +2,000
   Bulky: YES (+15,000, car)           Hours: 08:00–18:00

③ Shabiby Parcels   🚌 STATION · Native
   Route: Mbeya–Dar (both ways): Mbeya ▸ Iringa ▸ Morogoro ▸ Dar
     segment: Mbeya–Iringa 8k · Iringa–Moro 6k · Moro–Dar 7k
   value add: >1M +5,000 · Bulky: YES (+10,000)  Hours: 06:00–19:00

④ EMS Courier       🚪 DOOR · Native · nationwide
   Pricing: value ladder   ≤200k 15k · ≤1M 25k · >1M 3%
   Bulky: YES (+5,000)     Hours: 08:00–16:00 Mon–Fri
```

### A — small but many, same city
**20 phone cases**, Sinza (Ubungo) → Mbezi (Kinondoni). Value **120,000**, not bulky, ~6 km, Sun 14:00.
```
1 WHERE   both in Dar region, ~6 km
2 WHO     ① ✓  ② ✓  ③ ✗ (no Dar-local)  ④ ✓
3 FILTER  value ok · not bulky · ④ CLOSED Sun ✗   → candidates ① ②
4 PRICE   ① 6km = 3,500      ② 7,000 + value add 0 = 7,000
5 RANK    💰⚡ ① Mbezi Boda 3,500 ~40min · alt ② 7,000
```
Buyer sees: `🚪 Mbezi Boda — 3,500 · ~40 min`. Quantity raised value, but it still fits a bike.

### B — one but large (bulky, cheap)
**1 mattress**, same shops. Value **85,000**, **Bulky ticked**, ~6 km, Sun 14:00.
```
2 WHO     ① ② ④ cover area
3 FILTER  BULKY required → ① NO ✗ · ④ closed Sun ✗ → only ②
4 PRICE   ② 7,000 + value 0 + bulky 15,000 = 22,000
5 RANK    ⭐ only: ② Dar Cargo (car) 22,000
```
Buyer sees: `🚪 Dar Cargo (car) — 22,000`. Cheap item, but bulky kept it off the bike.

### C — intercity, multi-stop route, first/last mile
**Laptop**, shop in Mbeya → buyer in Morogoro town. Value **1,500,000**, not bulky, Mon 10:00.
```
1 WHERE   different regions (intercity)
2 WHO     ①② don't reach Mbeya ✗ · ③ route: Mbeya(1) before Morogoro(3) ✓ · ④ nationwide ✓
3 FILTER  value ok · not bulky · both open Mon 10:00
4 PRICE   ③ Mbeya→Moro 8k+6k = 14,000 + value>1M 5,000 = 19,000 (collect at Morogoro Stand)
          ④ EMS >1M = 3% of 1.5M = 45,000 door-to-door 2–3 days
5 RANK    💰 ③ Shabiby 19,000 tomorrow · 📦 ④ EMS 45,000 to door 2–3 days
```
Buyer sees two groups:
```
🚌 Collect at station   Shabiby · Morogoro Stand (2 km) · tomorrow · 19,000
📦 To your door         EMS · 2–3 days · 45,000
```
Route matched automatically; priced only the Mbeya→Morogoro segment, not the whole line.

### D — shipper rejects → auto-reassign (from §4.4)
From A, buyer picked **① 3,500**.
```
Seller "Ready" → offer ① → ① TIMEOUT (busy)
  → 3,500 back in escrow · REASSIGNING · exclude ①
  → next = ② 7,000  → DEARER than 3,500
  → delivery money → buyer wallet, ask: "Mbezi Boda unavailable. Dar Cargo 7,000 (+3,500). Continue?"
  → buyer accepts → pays 3,500 from wallet → ② gets the job
  (if next were ≤3,500 → auto-assigned silently, no buyer action)
```

### E — mixed cart, two shops (two shipments)
Cart: **phone** from Shop X (Kariakoo, Ilala, value 400k, not bulky) + **blender** from Shop Y
(Mbezi, Ubungo, value 90k, not bulky). Buyer in Mikocheni (Kinondoni). Sat 11:00.
```
One shipment per shop (§4.1), priced independently:
  Shipment 1  X Kariakoo → Mikocheni (~9 km)
     WHO ② (Dar region) ✓ · ① ✗ (Ilala not in its areas)
     PRICE ② 7,000 + value 0 = 7,000
  Shipment 2  Y Mbezi → Mikocheni (~5 km)
     WHO ① ✓ (Ubungo+Kinondoni) · ② ✓
     PRICE ① 3,500 (cheapest) · ② 4,000
Checkout shows:
  🏪 Shop X · Dar Cargo       7,000
  🏪 Shop Y · Mbezi Boda      3,500
  Delivery total (2 deliveries) 10,500
```
Two shippers, two codes, two escrow releases. One slow shop never blocks the other.

### F — free shipping (seller + NexGate stacked)
**Shoes**, Shop Z in Kinondoni → buyer in Kinondoni. Value **60,000**, ~4 km, Fri 15:00.
Shop Z offers free delivery in Kinondoni, pays up to **4,000**. A NexGate weekend campaign in Dar
pays up to **3,000**.
```
Cheapest qualifying option: ① Mbezi Boda 4km = 3,500
  − seller pays (cap 4,000)  −3,500   → fully covered by seller
  − NexGate not needed
  = buyer pays 0
Shipment records: who_pays = seller 3,500
```
Buyer sees: `🚪 Free delivery · ~35 min` (badge). Shipper still paid 3,500 in full from seller's earnings.
If the trip were 9 km = 5,000: seller 4,000 + NexGate 1,000 = buyer still 0, split recorded.

---

### One-line summary

**Build the Location Service first** (spec + data are ready). Then layer shipping on top:
shippers are businesses with a wallet, described by *service type* × *connection*, answering one
standard contract; they set their own coverage and pricing; money sits in escrow and releases on a
delivery code; orders are accepted 24/7 with honest timing; and free shipping, hours and ratings
slot into the same engine without changing it.

# NexGate Location Service — Implementation Spec

> **For the implementer (Claude Code):** read this whole file before writing code.
> Follow the existing conventions of the NexGate codebase (package layout, REST path style,
> auth/security, error format, ID type, DTO style, tests). Where this spec and the codebase
> conventions differ on *style*, follow the codebase. Where they differ on *behaviour/rules*,
> follow this spec. Keep it simple — no approval workflows, no extra services, no over-engineering.

---

## 0. Summary

The Location Service is a **module inside the existing Spring Boot backend** (not a microservice).
It owns everything about *where* things are:

- Tanzania ward boundaries (official NBS 2022 data) and **pin → region/district/ward** resolution
- **Shop location** (one per shop, mandatory before a shop can be published)
- **Buyer saved addresses** (many per buyer, optional) and **recent locations**
- **Order address snapshots** (frozen copy of pickup/drop-off for an order)
- Privacy rules for who may see which part of a location

Shipping (providers, quotes, tracking) is **out of scope** — it will be built later *on top of* this service.

### 0.1 Where the Location Service is used across NexGate

It is the shared foundation for every feature that cares about *where*. Build the two core calls —
`resolve(pin) → ward/district/region` and `areaMatch(areaSet, pin-or-area) → bool` — as reusable
functions, because all of these call them:

- **Shop setup** — the shop's mandatory pickup location (pin → ward).
- **Buyer addresses & checkout** — saved/recent delivery addresses; the delivery pin.
- **Order snapshots** — frozen pickup + drop-off for every order.
- **Shipping — coverage** *(later)* — is a trip inside a shipper's areas / route stops?
- **Shipping — pricing** *(later)* — pin-to-pin distance for distance-based fees.
- **Shipping — trip type** *(later)* — same district / same region / cross-region, from the two wards.
- **Free-shipping zones** *(later)* — seller or NexGate "free within these areas / X km of shop".
- **"Near me" feed & search** *(later)* — show shops/products by the viewer's rough area.
- **Geo-targeted ads / boosting** *(later)* — show a boosted post only in chosen areas, or only where
  the seller can deliver; match on the viewer's **rough area only**, aggregate counts, no tracking.
- **Reports & analytics** — group orders/activity by ward/district/region codes (never per person).

> Everything above reuses the **same ward data and the same two functions** — no new map work per
> feature. Only the two core calls are in scope now; the rest are listed so the API is designed to
> serve them.

---

## 1. Principles (non-negotiable)

1. **The pin (lat/lng) is the truth.** Every saved location has a pin confirmed by the user on a map.
   No location is ever saved without coordinates.
2. **We take location only for a reason.** No location request on app open, no background tracking
   for buyers or shops, no movement trails. Store only the pin the user *confirmed*.
3. **Hierarchy comes from our own data, not Google.** Region/district/ward are computed on the
   backend from NBS ward shapes. Google is used **only on the client** (map display, place search,
   live label while placing the pin). The backend **never calls Google** and **never stores Google text**.
4. **Orders keep their own frozen copy** of addresses. Editing or deleting a saved address never
   changes past orders.
5. **Simple.** One module, plain SQL for spatial work, no Flyway, no version tracking, no JPA entity
   for the ward table.

---

## 2. Architecture

```
┌──────────────────────── CLIENTS (Android · iOS · Web) ────────────────────────┐
│  Pin screen: Google Map + Places search + live Google label (display only)    │
│  Sends: confirmed lat/lng + user text (landmark/note/phone/label)             │
└───────────────────────────────────────┬───────────────────────────────────────┘
                                        │ REST
┌───────────────────────────────────────▼───────────────────────────────────────┐
│                     NexGate Spring Boot backend                                │
│                                                                                │
│  ┌──────────────────────── location module ───────────────────────────────┐  │
│  │  WardResolver        pin → ward/district/region (PostGIS query)         │  │
│  │  LocationValidator   coverage, nearest-ward snap, device-distance check │  │
│  │  UserAddressService  saved addresses, default, duplicates, limits       │  │
│  │  RecentLocationSvc   last unsaved pins (max 5, 60 days)                 │  │
│  │  ShopLocationService one mandatory location per shop                    │  │
│  │  SnapshotFactory     frozen AddressSnapshot for orders                  │  │
│  │  WardDataSeeder      creates tables/indexes + loads ward file once      │  │
│  └────────────────────────────────┬────────────────────────────────────────┘  │
│                                   │ (internal Java calls)                      │
│  ┌────────────── orders / checkout ─────────┐   ┌──── shipping (FUTURE) ────┐ │
│  │ stores AddressSnapshot on each order      │──►│ reads snapshots only      │ │
│  └───────────────────────────────────────────┘   └───────────────────────────┘ │
└───────────────────────────────────────┬───────────────────────────────────────┘
                                        │ JDBC
┌───────────────────────────────────────▼───────────────────────────────────────┐
│  PostgreSQL + PostGIS (Docker image postgis/postgis)                           │
│  tz_wards · shop_locations · user_addresses · recent_locations                 │
└────────────────────────────────────────────────────────────────────────────────┘

   Ward data file (NOT in Git):  tz_wards_2022.geojson.gz  → mounted read-only into app container
```

### Who decides what

```
              📍 confirmed pin (lat, lng)
             /                          \
   NBS ward shapes (ours, backend)     Google (client only)
   region, district, ward, codes        "Mlimani City, Sinza Mori…"
        │                                    │
     STORED (truth)                    shown on pin screen only, never sent/stored
```

---

## 3. Ward data

### 3.1 Source
- National Bureau of Statistics (NBS) Tanzania — *2022 Population and Housing Census, Tanzania Wards (Shapefiles)*.
- Already converted for us to **GeoJSON, WGS84 lat/lng (EPSG:4326)**, 21 self-intersecting shapes repaired.
- File: **`tz_wards_2022.geojson.gz`** (~6.7 MB gzipped, ~30 MB raw). 4,344 features.
- Attribution required somewhere in the app's legal/about page: *"Ward boundaries © National Bureau of Statistics, Tanzania (2022 PHC)."*

### 3.2 File format (what the seeder reads)

```json
{
  "type": "FeatureCollection",
  "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
  "features": [
    {
      "type": "Feature",
      "properties": {
        "ward_id": 1, "nbs_code": "010111011",
        "reg_code": "01", "reg_name": "Dodoma",
        "dist_code": "01", "dist_name": "Kondoa",
        "counc_code": "11", "counc_name": "Halmashauri ya Wilaya ya Kondoa",
        "ward_code": "011", "ward_name": "Changaa"
      },
      "geometry": { "type": "Polygon", "coordinates": [[[35.6782, -4.736511], ...]] }
    }
  ]
}
```

### 3.3 Data facts the code must respect
| Fact | Consequence |
|---|---|
| Coordinates are **[longitude, latitude]** (GeoJSON order) | `ST_MakePoint(lng, lat)` — longitude first. Most common bug. |
| Geometry is a mix of `Polygon` and `MultiPolygon` | Always store with `ST_Multi(...)` into a `MultiPolygon` column. |
| `ward_code` alone is NOT unique; even `nbs_code` repeats for 5 wards (NBS data issue) | **`ward_id` (1..4344) is the primary key.** `nbs_code` is informational, not unique. |
| Shapes stop at shorelines (sea, Lake Victoria, etc.) | Pins on beaches/jetties may fall outside every ward → nearest-ward fallback (§6). |
| 31 regions, ~4,344 wards. Dar es Salaam has 5 councils (Ilala, Kinondoni, Temeke, Ubungo, Kigamboni) | Expected counts for sanity tests. |

### 3.4 District & region come from the ward rows — no separate files

There is **no separate district or region boundary table**. Every ward row already carries its
council, district and region names and codes, so a single `ST_Contains` lookup returns all levels
at once:

```
pin → ward (Kariakoo) → already has dist_name=Ilala, reg_name=Dar es Salaam, codes included
```

- **Coverage checks** ("shipper serves Dar es Salaam region") match `reg_code`/`dist_code` on the
  resolved ward — no shape needed.
- **Reports** group orders by the stored `reg_code`/`dist_code`.
- **Drawing** a district or region outline on a map (e.g. shipper coverage) is the only case that
  needs a shape. Build it on demand by dissolving wards — do NOT store a second dataset:

```sql
-- district outlines (view or materialized view, optional)
SELECT reg_code, reg_name, dist_code, dist_name, ST_Union(geom) AS geom
FROM tz_wards GROUP BY reg_code, reg_name, dist_code, dist_name;

-- region outlines
SELECT reg_code, reg_name, ST_Union(geom) AS geom
FROM tz_wards GROUP BY reg_code, reg_name;
```

Use `counc_code` as well if councils (halmashauri) matter for coverage; the ward rows carry it too.

---

## 4. Infrastructure

### 4.1 Docker
- Database image must include PostGIS: use **`postgis/postgis:<PG_MAJOR>-<POSTGIS>`** with the **same Postgres major
  version** currently used (e.g. `postgres:16` → `postgis/postgis:16-3.4`). Same major version keeps existing data volumes working.
- App container mounts the data folder read-only:

```yaml
services:
  db:
    image: postgis/postgis:16-3.4        # match current PG major version
  app:
    volumes:
      - /opt/nexgate/geo:/app/geo:ro      # host folder holding tz_wards_2022.geojson.gz
    environment:
      GEO_WARDS_FILE: /app/geo/tz_wards_2022.geojson.gz
```

- Local dev: put the file in `./data/geo/` and add `data/geo/` to **`.gitignore`**. Never commit the data file.

### 4.2 Config
```properties
# path to .geojson or .geojson.gz ; empty/missing → seeder logs WARN and skips
geo.wards-file=${GEO_WARDS_FILE:./data/geo/tz_wards_2022.geojson.gz}
```

### 4.3 No Flyway, no version tracking
Schema for this module is created by the **WardDataSeeder** at startup using idempotent SQL
(`IF NOT EXISTS`). It runs after Hibernate initialises (use `ApplicationRunner` or `ApplicationReadyEvent`).

- `tz_wards` has **no JPA entity** (read via `JdbcTemplate`/native SQL only), so Hibernate never touches it.
- `shop_locations`, `user_addresses`, `recent_locations` may be JPA entities following project conventions,
  with **plain `lat`/`lng` double columns** (no hibernate-spatial needed). Spatial work is done in native SQL
  using `ST_SetSRID(ST_MakePoint(lng, lat), 4326)`. The seeder adds the spatial expression indexes afterwards.

---

## 5. Database

### 5.1 Entity relationships

```mermaid
erDiagram
    TZ_WARDS ||--o{ SHOP_LOCATIONS : "resolved to"
    TZ_WARDS ||--o{ USER_ADDRESSES : "resolved to"
    TZ_WARDS ||--o{ RECENT_LOCATIONS : "resolved to"
    USERS ||--o{ USER_ADDRESSES : owns
    USERS ||--o{ RECENT_LOCATIONS : has
    SHOPS ||--|| SHOP_LOCATIONS : "has exactly one"
    ORDERS ||--|| ADDRESS_SNAPSHOT : "pickup (frozen copy)"
    ORDERS ||--|| ADDRESS_SNAPSHOT : "drop-off (frozen copy)"
```

Addresses store `ward_id` **and** copies of the names/codes (denormalised) so reads never need a join
and display stays stable.

### 5.2 `tz_wards` (created + filled by seeder)

```sql
CREATE EXTENSION IF NOT EXISTS postgis;

CREATE TABLE IF NOT EXISTS tz_wards (
    ward_id     INTEGER PRIMARY KEY,
    nbs_code    VARCHAR(16)  NOT NULL,
    reg_code    VARCHAR(4)   NOT NULL,
    reg_name    VARCHAR(100) NOT NULL,
    dist_code   VARCHAR(4)   NOT NULL,
    dist_name   VARCHAR(100) NOT NULL,
    counc_code  VARCHAR(4)   NOT NULL,
    counc_name  VARCHAR(200) NOT NULL,
    ward_code   VARCHAR(8)   NOT NULL,
    ward_name   VARCHAR(100) NOT NULL,
    geom        geometry(MultiPolygon, 4326) NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_tz_wards_geom ON tz_wards USING GIST (geom);
CREATE INDEX IF NOT EXISTS idx_tz_wards_names ON tz_wards (reg_name, dist_name, ward_name);
```

### 5.3 Location tables (logical schema — use project ID type & audit conventions)

**`shop_locations`** — exactly one per shop
| column | type | rule |
|---|---|---|
| id | project ID type | PK |
| shop_id | FK → shops | **unique** |
| lat, lng | double | required, rounded to 6 decimals |
| ward_id | int | resolved by backend |
| reg_name, dist_name, ward_name, nbs_code | text | copied from ward |
| match_type | enum `CONTAINED` / `NEAREST` | from resolver |
| landmark | text (≤ 300) | **required** ("Near Shekilango stop, above Vodashop, 1st floor") |
| building | text (≤ 100) | optional ("Shop 12") |
| pickup_phone | text | **required**, E.164 (+255…) |
| official_address | text (≤ 100) | optional (Anwani za Makazi) |
| photo_url | text | optional (shop front photo, uses existing media upload) |
| created_at, updated_at | timestamp | |

**`user_addresses`** — buyer's saved addresses (0..10 per user)
| column | type | rule |
|---|---|---|
| id | project ID type | PK |
| user_id | FK → users | |
| label_type | enum `HOME` / `WORK` / `OTHER` | HOME and WORK max **one each** per user |
| custom_label | text (≤ 40) | required when `OTHER` ("Mama's place") |
| lat, lng | double | required, 6 decimals |
| ward_id, reg_name, dist_name, ward_name, nbs_code, match_type | | resolved by backend |
| note | text (≤ 300) | optional note for rider ("Black gate, call on arrival") |
| receiver_name | text | defaults to user's name |
| receiver_phone | text | defaults to user's phone, E.164 |
| is_default | boolean | at most one `true` per user |
| last_used_at | timestamp | updated when used in an order |
| created_at, updated_at | timestamp | |

**`recent_locations`** — unsaved delivery pins (max 5 per user, expire after 60 days)
| column | type | rule |
|---|---|---|
| id | project ID type | PK |
| user_id | FK → users | |
| lat, lng, ward_id, reg_name, dist_name, ward_name, match_type | | as above |
| note, receiver_name, receiver_phone | | as used in that order |
| last_used_at | timestamp | |

Indexes created by seeder after Hibernate (idempotent):
```sql
CREATE UNIQUE INDEX IF NOT EXISTS ux_shop_locations_shop ON shop_locations (shop_id);
CREATE INDEX IF NOT EXISTS idx_shop_locations_geog ON shop_locations
    USING GIST ((ST_SetSRID(ST_MakePoint(lng, lat), 4326)::geography));   -- for future "near me"
CREATE INDEX IF NOT EXISTS idx_user_addresses_user ON user_addresses (user_id);
CREATE UNIQUE INDEX IF NOT EXISTS ux_user_addresses_default ON user_addresses (user_id) WHERE is_default;
CREATE UNIQUE INDEX IF NOT EXISTS ux_user_addresses_home ON user_addresses (user_id) WHERE label_type = 'HOME';
CREATE UNIQUE INDEX IF NOT EXISTS ux_user_addresses_work ON user_addresses (user_id) WHERE label_type = 'WORK';
CREATE INDEX IF NOT EXISTS idx_recent_locations_user ON recent_locations (user_id, last_used_at DESC);
```
(If the project creates these tables itself via its own mechanism, keep the indexes in the seeder anyway.)

### 5.4 `AddressSnapshot` (frozen copy stored on orders)
Not a table owned by this module. The orders module stores it (e.g. a `jsonb` column `pickup_snapshot` /
`dropoff_snapshot`, or embedded columns — follow project convention). **Immutable once stored.**

```json
{
  "lat": -6.774512, "lng": 39.241871,
  "wardId": 1131, "nbsCode": "070113062",
  "regionName": "Dar es Salaam", "districtName": "Kinondoni", "wardName": "Kijitonyama",
  "matchType": "CONTAINED",
  "label": "Home",                         // null if unsaved
  "landmarkOrNote": "Black gate, call on arrival",
  "building": null,
  "contactName": "Kibuti", "contactPhone": "+2557XXXXXXXX",
  "sourceType": "USER_ADDRESS",            // USER_ADDRESS | NEW_PIN | SHOP_LOCATION
  "sourceId": "…",                         // id of saved address/shop location, null for NEW_PIN
  "capturedAt": "2026-10-08T12:30:00Z"
}
```

---

## 6. Pin resolution (core algorithm)

```
 input: lat, lng
   │
   ├─ basic checks: lat ∈ [-90,90], lng ∈ [-180,180], not (0,0) ── fail → 400 INVALID_COORDINATES
   │
   ├─ round to 6 decimals
   │
   ├─ Query A: ward whose shape CONTAINS the point
   │     found → matchType = CONTAINED, distanceM = 0  ───────────────────────► return ward
   │
   ├─ Query B: nearest ward within 500 m (shoreline, beach, jetty, border gaps)
   │     found → matchType = NEAREST, distanceM = n  ─────────────────────────► return ward
   │
   └─ nothing → OUTSIDE_COVERAGE (sea, lake, outside Tanzania)
```

```sql
-- Query A (uses GIST index)
SELECT ward_id, nbs_code, reg_name, dist_name, counc_name, ward_name
FROM tz_wards
WHERE ST_Contains(geom, ST_SetSRID(ST_MakePoint(:lng, :lat), 4326))
LIMIT 1;

-- Query B (only if A returns nothing)
SELECT ward_id, nbs_code, reg_name, dist_name, counc_name, ward_name,
       ST_Distance(geom::geography, ST_SetSRID(ST_MakePoint(:lng, :lat), 4326)::geography) AS distance_m
FROM tz_wards
WHERE ST_DWithin(geom::geography, ST_SetSRID(ST_MakePoint(:lng, :lat), 4326)::geography, 500)
ORDER BY distance_m
LIMIT 1;
```

Point exactly on a border → whichever ward Query A returns is fine.
Constant: `NEAREST_WARD_MAX_METERS = 500`.

### 6.1 Validation rules
| Check | Applies to | Result |
|---|---|---|
| Invalid coordinates | all | **block** `INVALID_COORDINATES` |
| No ward within 500 m | all | **block** `OUTSIDE_COVERAGE` ("We don't deliver here yet") |
| Matched by NEAREST | all | allow, `matchType=NEAREST` (info only) |
| Pin > **1 km** from device position (client sends optional `deviceLat/deviceLng`) | **shop only** | allow, return warning `FAR_FROM_DEVICE` with distance; client asks "Your pin is 3.2 km from where you are. Is this your shop?" |
| Saved address within **50 m** of another saved address of same user | buyer save | `409 NEAR_DUPLICATE` with the existing address; client asks "This looks like 🏠 Home. Use it?"; client may resend with `allowNearDuplicate=true` |
| More than 10 saved addresses | buyer save | block `ADDRESS_LIMIT_REACHED` |
| Second HOME or WORK | buyer save/edit | block `LABEL_ALREADY_USED` |

Client-only checks (not backend): GPS accuracy circle, minimum zoom before confirm, satellite toggle.

---

## 7. Business rules

### 7.1 Shop location
- Exactly **one** location per shop. **Required to publish a shop** — expose `hasLocation(shopId)` for the shop module.
- Required fields: pin, landmark, pickup phone. Optional: building, official address, photo.
- Only the shop owner (and shop admins per existing roles) can set/edit it. No approval step.
- Editing affects **future** orders only (old orders keep snapshots).

### 7.2 Buyer addresses
- Saving is **optional** and the buyer's choice (checkbox "Save for next time").
- Max 10 saved. HOME/WORK at most once each; OTHER needs a custom label.
- First saved address becomes default automatically. Buyer can change default.
  If the default is deleted → no default (client pre-selects most recently used).
- Receiver name/phone default to the buyer's profile; buyer can change ("someone else").
- Edit = change pin (re-resolved), label, note, receiver. Delete = **hard delete**.

### 7.3 Recent locations
- When an order uses a **new pin that was not saved**, store it in `recent_locations`.
- Keep max **5** per user (delete oldest beyond 5 on insert). Ignore and delete entries older than **60 days**
  (on read/insert — no scheduler needed).
- If the new pin is within 50 m of an existing recent, update that one's `last_used_at` instead of inserting.
- Buyer can delete one or clear all. A recent can be promoted to a saved address (client posts a normal create).

### 7.4 Orders / snapshots
- Checkout passes either `addressId` (saved), `recentId`, or a **new pin** payload.
- Location module returns an `AddressSnapshot`; orders module stores it; snapshot never changes.
- Using a saved address updates its `last_used_at`.
- Pickup snapshot comes from the shop location (`sourceType=SHOP_LOCATION`).

### 7.5 Account deletion
Deletes all `user_addresses` and `recent_locations` of that user. Order snapshots remain (order records).

---

## 8. Privacy & visibility

| Data | Buyer | Seller | Rider / delivery provider | Third parties |
|---|---|---|---|---|
| Buyer saved addresses / recents | own only | ❌ | ❌ | ❌ |
| Order drop-off **area** (ward, district, region) | ✅ | ✅ | ✅ | ❌ |
| Order drop-off **exact pin + note + phone** | ✅ | only if seller delivers itself (`sellerDelivers=true`) | ✅ for that shipment only | ❌ |
| Shop location (pin, landmark, ward) | ✅ public | ✅ | ✅ | ❌ |
| Shop pickup phone | after order | ✅ | ✅ | ❌ |

Implement as two snapshot views: `AddressSnapshotPublicView` (area only) and `AddressSnapshotFullView`.
Analytics/reports aggregate by ward/district only — never per person.
Never log full coordinates together with user identifiers at INFO level.

---

## 9. REST API

> Paths shown as examples — adapt prefix/style/auth to the existing project.
> All endpoints require authentication except `GET /shops/{id}/location` (public view).

### 9.1 Resolve (used live by pin screen after the map stops moving — debounce ~400 ms client side)
`GET /api/v1/locations/resolve?lat=-6.8190&lng=39.2768`
```json
200 { "covered": true, "matchType": "CONTAINED", "distanceM": 0,
      "ward": { "wardId": 1146, "nbsCode": "070214112", "wardName": "Kariakoo",
                "districtName": "Ilala", "councilName": "Halmashauri ya Jiji la Dar es Salaam",
                "regionName": "Dar es Salaam" },
      "areaLabel": "Kariakoo, Ilala, Dar es Salaam" }
200 { "covered": false, "reason": "OUTSIDE_COVERAGE" }
```
Nothing is stored by this call.

### 9.2 Buyer addresses
| Method | Path | Notes |
|---|---|---|
| GET | `/api/v1/me/addresses` | list, default first, then `last_used_at` desc |
| POST | `/api/v1/me/addresses` | create (body below) |
| PUT | `/api/v1/me/addresses/{id}` | update (same body) |
| DELETE | `/api/v1/me/addresses/{id}` | hard delete |
| POST | `/api/v1/me/addresses/{id}/default` | make default |
| GET | `/api/v1/me/recent-locations` | max 5, ≤ 60 days |
| DELETE | `/api/v1/me/recent-locations/{id}` | remove one |
| DELETE | `/api/v1/me/recent-locations` | clear all |

```json
POST /api/v1/me/addresses
{ "lat": -6.774512, "lng": 39.241871,
  "labelType": "OTHER", "customLabel": "Mama's place",
  "note": "Black gate, call on arrival",
  "receiverName": null, "receiverPhone": null,      // null → use profile
  "makeDefault": false, "allowNearDuplicate": false }
```

### 9.3 Shop location
| Method | Path | Notes |
|---|---|---|
| GET | `/api/v1/shops/{shopId}/location` | public view (no phone unless authorised) |
| PUT | `/api/v1/shops/{shopId}/location` | create or replace; owner only |

```json
PUT /api/v1/shops/{shopId}/location
{ "lat": -6.770901, "lng": 39.229410,
  "landmark": "Near Shekilango stop, above Vodashop, 1st floor",
  "building": "Shop 12", "pickupPhone": "+2557XXXXXXXX",
  "officialAddress": null, "photoUrl": null,
  "deviceLat": -6.7712, "deviceLng": 39.2291 }       // optional, for FAR_FROM_DEVICE warning
→ 200 { ...location..., "warnings": [ { "code": "FAR_FROM_DEVICE", "distanceM": 3200 } ] }
```

### 9.4 Internal Java API (for orders/shop modules — not REST)
```java
ResolveResult resolve(double lat, double lng);
boolean hasShopLocation(ShopId shopId);
AddressSnapshot snapshotFromShop(ShopId shopId);
AddressSnapshot snapshotFromAddress(UserId userId, AddressId addressId);   // also bumps last_used_at
AddressSnapshot snapshotFromRecent(UserId userId, RecentId recentId);
AddressSnapshot snapshotFromNewPin(UserId userId, NewPinRequest req);      // req.saveForLater → creates address, else records recent
```

### 9.5 Error codes
`INVALID_COORDINATES`, `OUTSIDE_COVERAGE`, `NEAR_DUPLICATE` (409, includes existing address),
`ADDRESS_LIMIT_REACHED`, `LABEL_ALREADY_USED`, `SHOP_LOCATION_REQUIRED` (thrown by shop publish),
`NOT_FOUND`, `FORBIDDEN`. Use the project's existing error response format.

---

## 10. WardDataSeeder (startup)

```
App starts (after Hibernate)
  │
  ├─ 1. CREATE EXTENSION IF NOT EXISTS postgis          (log clear error if not permitted)
  ├─ 2. CREATE TABLE IF NOT EXISTS tz_wards …  + indexes
  ├─ 3. CREATE INDEX IF NOT EXISTS … on location tables (§5.3)
  │
  ├─ 4. BEGIN; SELECT pg_advisory_xact_lock(<constant>)   ← only one container seeds
  │      SELECT count(*) FROM tz_wards
  │        ├─ > 0  → COMMIT, done (normal startup, instant)
  │        └─ = 0  → file exists?
  │                    ├─ no  → WARN "ward file not found at …; ward lookup disabled", COMMIT, continue startup
  │                    └─ yes → stream features (Jackson streaming parser, gzip if *.gz)
  │                             batch insert 200 rows:
  │                             INSERT INTO tz_wards (…, geom)
  │                             VALUES (…, ST_Multi(ST_SetSRID(ST_GeomFromGeoJSON(?), 4326)))
  │                             ON CONFLICT (ward_id) DO NOTHING
  │                             COMMIT; ANALYZE tz_wards
  │                             log "Loaded N wards in X s" (expect 4344)
  │
  └─ 5. If wards were just loaded AND user_addresses/shop_locations/recent_locations already have rows
         → re-resolve all of them (update ward_id + name copies + match_type). Order snapshots untouched.
```

Rules:
- Stream the file — never load all 30 MB into memory.
- Accept both `.geojson` and `.geojson.gz`.
- Seeder failure must not crash the app; resolve endpoint then returns `503 WARD_DATA_UNAVAILABLE`.
- **Updating to new boundaries later:** replace file on server, `TRUNCATE tz_wards;`, restart. Step 5 re-resolves saved locations.

---

## 11. Client behaviour (Android · iOS · Web)

### 11.1 Location permission
- **Never** ask on app open. Ask only when the user taps **"Use my location"** on the pin screen.
- Show our own explainer first; trigger the OS/browser prompt only if the user agrees.
- **Foreground / "While using the app" only.** Never background location for buyers or shops.
- Handle **approximate** location (Android 12+, iOS 14+): use it to centre the map, ask user to drag map to exact spot.
- iOS: purpose string e.g. *"NexGate uses your location to set your shop or delivery address faster."*
- Web: only after a click, HTTPS only. If denied, search + map always still work. Location is a shortcut, never a gate.

```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
┆           📍                  ┆
   Use your location?
┆ We use it once to place your  ┆
   pin faster. You can also
┆ search or move the map.       ┆
  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
┆ ┆   Use my location         ┆ ┆   → OS permission prompt
  └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
┆        Not now              ┆     → stay on map, no prompt
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

### 11.2 Pin screen (shared component — shop, buyer, add-address)
Behaviour:
1. **Fixed centre pin, the map moves** (Bolt/Uber pattern). Pin lifts while dragging, drops when the map stops.
2. Start position: accurate GPS → last used location → centre of user's city. Never whole-country view.
3. **Map / Satellite toggle** (satellite matters — many streets unnamed).
4. GPS **accuracy circle**; if accuracy > 100 m show "Location is approximate — move the map to your exact spot".
5. **Confirm disabled until zoom ≥ 17** (street level). Hint: "Zoom in to place exactly".
6. Search (Google Places) only **moves** the map: "Now move the map to the exact entrance".
7. When map stops (debounce ~400 ms): show Google label + call `/locations/resolve`.
   If `covered=false` → disable Confirm, show "We don't deliver here yet".

```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  ←  Shop location     Step 3/4
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ 🔍 Search place or area   ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
┆ ┆ [Map|Satellite]           ┆ ┆
  ┆                           ┆
┆ ┆        ( ◌ )  ← accuracy  ┆ ┆
  ┆          📍  fixed centre ┆
┆ ┆        move the map       ┆ ┆
  ┆                    [◎]    ┆   [◎] = use my location
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
  ⚠ Zoom in to place exactly
┆   (shown until zoom ≥ 17)     ┆
  📍 Sinza, Ubungo, Dar es Salaam      ← Google label (display only)
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆   Confirm location   →    ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

### 11.3 Shop flow (mandatory, step in shop creation)

```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  ←  Shop location     Step 3/4
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ [mini map 📍]   Change    ┆
┆ ┆ Makurumla, Ubungo, Dar    ┆ ┆   ← from /resolve (NBS)
  └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
┆ Directions / landmark *       ┆
  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
┆ ┆ Near Shekilango stop,     ┆ ┆
  ┆ above Vodashop, 1st floor ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
  Building / shop no. (optional)
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ Shop 12                   ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
  Pickup contact phone *
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ +255 7XX XXX XXX          ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
  Official address (optional)
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ Anwani za Makazi          ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
  📷 Add shop front photo (optional)
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆   Save & continue    →    ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```
If response has `FAR_FROM_DEVICE` → dialog "Your pin is 3.2 km from where you are. Is this your shop?" [Yes, it's correct] [Adjust pin].

### 11.4 Buyer delivery flow (pin only, Bolt style)

**Checkout — choose where**
```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  Deliver to
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ ● 🏠 Home      (default)   ┆
┆ ┆   Mbezi Juu, Ubungo       ┆ ┆
  ┆ ○ 💼 Work                  ┆
┆ ┆   Kivukoni, Ilala         ┆ ┆
  ┆ ○ ⭐ Mama's place          ┆
┆ ┆   Tabata, Ilala           ┆ ┆
  ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤
┆ ┆ Recent                    ┆ ┆
  ┆ ○ 🕘 Kijitonyama   [Save]  ┆
┆ ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤ ┆
  ┆ ＋ New location (pin)      ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
         Manage addresses
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```
First-time buyer with nothing saved → goes straight to the pin screen.

**New location — full map + bottom sheet**
```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  ←  Deliver to       [Sat]
┆                               ┆
          FULL MAP
┆           📍                  ┆
                         [◎]
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ 🔍 Search                 ┆
┆ ┆ 🏠 Home     Mbezi Juu      ┆ ┆   ← tap jumps the pin there
  ┆ 💼 Work     Kivukoni       ┆
┆ ┆ 🕘 Recent   Kijitonyama    ┆ ┆
  ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤
┆ ┆ 📍 Mikocheni, Kinondoni    ┆ ┆
  ┆ [ Deliver here → ]        ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

**Quick confirm sheet**
```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  📍 Mikocheni, Kinondoni
┆                               ┆
  Note for rider (optional)
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ Black gate, call on arrival┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
  Receiver: Me (+255 7XX…)  ✎        ← "Someone else" → name + phone
┆                               ┆
  [ ] Save as  🏠  💼  ✎             ← labels shown only when ticked
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆      Continue  →          ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

**Profile — manage addresses**
```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
  ←  My addresses
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆ 🏠 Home  ✓default     ⋮   ┆
┆ ┆ Mbezi Juu, Ubungo         ┆ ┆
  ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤
┆ ┆ 💼 Work               ⋮   ┆ ┆
  ┆ Kivukoni, Ilala           ┆
┆ ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤ ┆
  ┆ ⭐ Mama's place        ⋮   ┆
┆ ┆ Tabata, Ilala             ┆ ┆
  └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
┆   ⋮ = Edit pin · Rename ·     ┆
    Set default · Delete
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆   ＋ Add address           ┆
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
  🕘 Clear recent locations
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

**Optional secondary onboarding (buyer)**
```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
┆           📦                  ┆
   Faster checkout?
┆  Add your home address now    ┆
   and skip it at checkout.
┆ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┆
  ┆      Add address          ┆      → pin screen → quick confirm (Save always on)
┆ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ ┆
           Maybe later
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```

Area lines shown after saving (lists, checkout) are built from **NBS names** (`ward, district`) plus the
user's label — never from Google text.

---

## 12. Flows

### 12.1 Shop sets location
```mermaid
sequenceDiagram
    actor Owner
    participant App
    participant Google as Google Maps/Places (client)
    participant API as Location module
    participant DB as PostGIS
    Owner->>App: Step 3 "Shop location"
    App->>Owner: Explainer → tap "Use my location"
    App->>App: OS permission (while in use), one GPS reading
    Owner->>App: Move map under fixed pin, zoom ≥ 17
    App->>Google: label for map centre (display only)
    App->>API: GET /locations/resolve?lat&lng
    API->>DB: ST_Contains / nearest ≤ 500 m
    DB-->>API: ward, district, region
    API-->>App: covered=true, areaLabel
    Owner->>App: Confirm → landmark, phone, (building, photo)
    App->>API: PUT /shops/{id}/location (+deviceLat/Lng)
    API->>DB: resolve again, upsert shop_locations
    API-->>App: saved (+ FAR_FROM_DEVICE warning if > 1 km)
```

### 12.2 Buyer checkout with a new pin
```mermaid
sequenceDiagram
    actor Buyer
    participant App
    participant Orders as Orders/Checkout
    participant Loc as Location module
    participant DB as PostGIS
    Buyer->>App: Checkout → "＋ New location"
    Buyer->>App: Place pin, note, receiver, [Save?]
    App->>Loc: GET /locations/resolve (live while moving)
    Buyer->>App: Continue / Pay
    App->>Orders: place order { newPin, saveForLater }
    Orders->>Loc: snapshotFromNewPin(user, req)
    Loc->>DB: resolve ward
    alt saveForLater = true
        Loc->>DB: insert user_addresses (rules §7.2)
    else
        Loc->>DB: upsert recent_locations (max 5, 60 days)
    end
    Loc-->>Orders: AddressSnapshot (frozen)
    Orders->>DB: store order + pickup & drop-off snapshots
```

### 12.3 Shop publish guard
```
Shop "Publish" → shopModule calls location.hasShopLocation(shopId)
   ├─ true  → publish
   └─ false → 400 SHOP_LOCATION_REQUIRED → app opens Shop location step
```

---

## 13. Out of scope (do NOT build now)
- Shipping, providers (Bolt etc.), quotes, tracking, recommendation engine
- Delivery zones and hubs (future: same pattern — shapes table + `ST_Contains`)
- Mtaa/street level (no public shapes; future table identical to `tz_wards` if NBS provides them)
- "Near me" feed (index on shop_locations is prepared; feature later — must use rough area only, not stored)
- Any backend call to Google; storing Google labels

---

## 14. Acceptance tests

### 14.1 Ward resolution (integration test against loaded data — these were verified against the file)
| Place | lat | lng | Expected ward | District | Region |
|---|---|---|---|---|---|
| Kariakoo market | -6.8190 | 39.2768 | Kariakoo | Ilala | Dar es Salaam |
| Ubungo bus terminal | -6.7889 | 39.2083 | Ubungo | Ubungo | Dar es Salaam |
| JNIA airport | -6.8781 | 39.2026 | Kipawa | Ilala | Dar es Salaam |
| Posta / city centre | -6.8160 | 39.2900 | Kivukoni | Ilala | Dar es Salaam |
| Stone Town | -6.1622 | 39.1887 | Shangani | Mjini | Mjini Magharibi |
| Arusha clock tower | -3.3700 | 36.6940 | Sekei | Arusha | Arusha |
| Mwanza centre | -2.5164 | 32.9006 | Nyamagana | Nyamagana | Mwanza |
| Mbeya town | -8.9094 | 33.4608 | Ruanda | Mbeya | Mbeya |
| Dodoma centre | -6.1722 | 35.7395 | Majengo | Dodoma | Dodoma |
| Indian Ocean off Dar | -6.80 | 39.40 | — `OUTSIDE_COVERAGE` | | |
| Nairobi | -1.2864 | 36.8172 | — `OUTSIDE_COVERAGE` | | |

Also: `SELECT count(*) FROM tz_wards` = **4344**; `SELECT count(DISTINCT reg_name)` = **31**.
Use Testcontainers with `postgis/postgis` image if the project already uses Testcontainers; otherwise follow project test setup.

### 14.2 Rules
- Seeder runs twice → still 4344 rows, second run instant.
- Two app instances start together → 4344 rows, no errors (advisory lock).
- Missing ward file → app starts, WARN logged, `/resolve` returns 503.
- Swapped lat/lng (39.2768, -6.8190) → `OUTSIDE_COVERAGE` (guards against order bug).
- 11th saved address → `ADDRESS_LIMIT_REACHED`. Second HOME → `LABEL_ALREADY_USED`.
- Save within 50 m of existing → `409 NEAR_DUPLICATE`; with `allowNearDuplicate=true` → saved.
- Delete default → no default remains. First saved address → becomes default.
- 6th unsaved pin → only 5 recents remain; entries > 60 days not returned.
- Edit saved address after an order → order snapshot unchanged.
- Shop without location cannot publish → `SHOP_LOCATION_REQUIRED`.
- Shop PUT with device 3 km away → saved + `FAR_FROM_DEVICE` warning.
- Seller view of order shows area only unless `sellerDelivers=true`.
- `TRUNCATE tz_wards` + restart → reload + saved addresses re-resolved.

---

## 15. Build order
1. Docker: switch DB to `postgis/postgis` (same PG major), mount `/opt/nexgate/geo`, add config, `.gitignore data/geo/`.
2. `WardDataSeeder` + `WardResolver` + `GET /locations/resolve` + tests §14.1. **← foundation**
3. Shop location (entity, PUT/GET, `hasShopLocation`, publish guard).
4. Buyer addresses + recents (+ rules tests).
5. `AddressSnapshot` + checkout integration + privacy views.
6. Clients: shared pin-screen component, shop step, checkout picker, manage addresses, optional onboarding.

# NexGate Shipping Service — Development guide

**Status:** design agreed in discussion (2026-10-12), **not built yet**. Built on the Location Service
(wards, shop locations, user addresses, frozen places — see `commerce_logistics_changes.md`).
Source specs: doc-hub *Logistics Service* book (location spec + commerce/location/logistics master guide).
Where this document and the master guide differ, **this document wins** (it records our decisions).

Rule of thumb for everything below: **simple over clever.** Shipping prices are placeholders (0) until this
service is built; build what is decided, keep a visible list of what is not.

---

## 1. Principles

1. **Two ways to get an order: PICKUP or DELIVERY**, chosen per shop. The shipping service owns both.
2. **One shop's order = one parcel.** A cart with three shops = three parcels, three fulfillments.
3. **User addresses are places only** (pin, label, directions). Order data — who receives, notes — lives on the
   order, never in the address book.
4. **Everything about places is frozen** on the order when the checkout session is created. Later edits to a shop
   location, an address or a price never change an existing order.
5. **Money sits in escrow** and moves on proof (codes), never on trust.
6. **Shippers describe their own coverage, prices and times.** NexGate never forces one model.
7. **No manual approval queues.** Trust comes from documents, codes, reviews and automatic rules.
8. **Orders are accepted 24/7; timing is honest.** Closed hours delay work, never the sale.
9. **Pickup and delivery are designed together.** Every feature must say what it does for a pickup order.

---

## 2. Big picture

```
MESSAGES (everyone talks only to NexGate; the SHIPPING AGREEMENT is the deal they all sign — §4.8)
  buyer   ── estimation / quotation / agreement / pay ──►┐
  seller  ── accept / ready / verify pickup code ───────►├── NexGate ── escrow: items + legs
  shipper ◄── offers ──  ── accept / status / code ─────►┘   (native: app · integrated: API)

PARCEL (physical, with the code that unlocks each handover)
  pickup:    shop ──[buyer's code]──► buyer
  delivery:  shop ──[pickup code]──► shipper ──[delivery code]──► buyer
  chain:     shop ──► shipper 1 ──[handover code]──► shipper 2 ──► … ──► buyer
```

### Package layout (new top-level `shipping_service/`, next to `location_service/`)

| Package | Owns |
|---|---|
| `fulfillment/` | one record per shop order: PICKUP or DELIVERY, frozen places, receiver, note, status, codes, timers. (Replaces the Step-4 `e_commerce/fulfillment` JSON — the order links to this record.) |
| `business/` | native shippers ("delivery businesses"): KYC, Service Setup, coverage, pricing, hours, stations, reviews |
| `providers/` | integrated shippers: one adapter per provider |
| `engine/` | estimation + quotations: coverage, pricing, ETA, chains, ranking — native and integrated together |
| `jobs/` | offers, accept / reject, reassignment, status steps, handovers |

Shared pieces used across: `opening_hours` (shops, businesses, stations), the area picker and frozen places
from `location_service`.

---

## 3. Fulfillment: pickup and delivery

### 3.1 Pickup
```
placed → accepted → ready → collected → completed
exits: cancelled (buyer before accept, or seller) · expired (14 days)
```
- **accepted** — the seller took the order (the seller's signature, §4.8).
- **ready** — one tap, button **"Packed & ready"** (packing and ready are the same moment; not split) → buyer is
  told "ready at Ubungo, Gate B" (directions, shop phone).
- **collected** — the **seller enters the buyer's 4-digit code** at the counter.
- **completed** — the buyer tapped **"✓ It's what I ordered"** → money released.
- **Pickup time (optional)** — after Ready the buyer sees **"When will you come?"**: a date + time picker offering
  only the **shop's opening hours** inside the window. The seller sees it on the order ("Buyer coming Thu 15:00");
  the buyer gets a reminder that morning; time passed and not collected → the buyer is asked to pick a new time.
  Changeable any time, **not binding**, a field on the order (not a status); it **does not move the window**.
- **Collection window 14 days, counted from Ready**: reminders on the Ready day, day 7, day 12 and day 13 ("last day tomorrow");
  not collected by day 14 → auto-cancel, full refund, stock back.
- **The seller can cancel at once** while only the buyer and the seller are involved — no waiting for the window;
  they talk by phone (damaged, out of stock, the buyer asked…). No reason list: one **pop-up** —
  *"I have already informed the buyer about this cancellation"* → confirm → cancelled, buyer notified, **full
  refund**, stock back (the seller fixes stock by hand if the item is damaged).
  - **Pickup**: any time before *collected*.
  - **Delivery**: only **before Ready** — no shipper has an offer yet (heads-ups and Upcoming cards are not
    commitments; they disappear). After Ready, shippers are involved → open (§15 #13).

### 3.2 Delivery (door-to-door)
`placed → accepted → ready → shipper accepted → heading to the shop → picked up → on the way → delivered → completed`
(the same `accepted` / `ready` / `completed` as pickup; "ready" is when the offers go out)

**Heading to the shop** — the shipper taps it when they set out. It marks when cancelling the shipping starts
to cost the buyer (§3.4a).

### 3.3 Delivery (station)
`placed → accepted → ready → shipper accepted → heading to the shop → dropped at station → in transit → at destination station → collected → completed`
(the parcel always starts with a collection at the shop — by a door shipper, or by the station business itself when
it collects from shops, §7.2a)
(the buyer collects at the station; station staff enter the buyer's code)

### 3.4 Switching (buyer only, many times allowed within the rules)
| From → to | Allowed | Money |
|---|---|---|
| Pickup → delivery | any time **before the buyer collects** | fresh quotes at today's prices; buyer pays the delivery fee from the wallet into new leg part(s); if the order is already *ready*, the offer goes to the shipper at once |
| Delivery → pickup | **before pickup** (same rules as cancelling the shipping, §3.4a) | leg part(s) refunded, minus the wasted-trip fee if a shipper is already heading to the shop |

### 3.4a Cancelling (buyer)
| Situation | Buyer can |
|---|---|
| **Before the seller accepts** | **cancel the whole order** — full refund |
| **After the seller accepts, no shipper accepted yet** | **cancel the shipping** (keep the order): **pickup** (delivery refunded) or a **new delivery proposal** (new quotation → new agreement; pay or get back the difference) |
| **A shipper accepted, not heading to the shop yet** | **cancel the shipping** → pickup or a new proposal; **free** (like Bolt); the shipper is released and told (no reliability effect on them) |
| **A shipper is heading to the shop** | **cancel the shipping** with a **wasted-trip fee** paid by the buyer: native = **50% of that leg's cost**, Bolt = Bolt's own cancellation charge |
| **Parcel picked up** | no cancelling the shipping — only a **destination change** (§4.8) or, in a chain, **stop at the next meeting point** (legs not started are refunded) |
| **Chain failed** — a shipper didn't accept and no replacement was found, or the buyer declined the dearer proposal | drop the shipping → **pickup**, a **new delivery proposal**, **end the chain earlier** — or **cancel the whole order** (full refund, stock back; not the buyer's fault) |

Rule: **whoever causes the cost pays it.** Switching delivery → pickup after the seller signed does **not** need
the seller to sign again (they agreed to hand the order over; who collects is the buyer's choice) — the seller is told.

### 3.5 What every fulfillment record holds
type · pickup place (the shop, frozen) · drop-off place (delivery, frozen) · receiver (name + phone; for pickup =
who collects; default = the buyer) · **parcel number** (§11) · planned pickup time (pickup, optional) · note (this order only) · the agreement (legs, shippers, meeting points, costs, ETAs) · status ·
codes · who paid what (free shipping split) · timestamps of every step.

---

## 4. Choosing: estimation → quotation → agreement

### 4.1 Three stages
| Stage | What | Where | Can change? | Lifetime |
|---|---|---|---|---|
| **Shipping estimation** | a hint: `cost {from,to}`, `eta {from,to}` | product cards and lists | — | cached, not stored |
| **Shipping quotation** | the **proposal**: recommended chain (legs, shippers, meeting points, cost, ETA) + alternatives per leg | add-to-cart / buy-now sheet, the cart | **yes** — destination, shipper per leg, meeting point, pickup ↔ delivery | prices **held 5 days** while the parcel is unchanged |
| **Shipping agreement** | the deal | **created at checkout** from the quotation | editable on the checkout screen **until paid** | **locked once paid** for the order's whole life |

```
card "🚚 20,000 – 35,000 to Mbeya"          ← estimation
 └ sheet / cart: QUOTATION — buyer edits ("collect at Mbeya Bus Stand", "use Abood")
     └ checkout: AGREEMENT — still editable before paying
         └ paid: LOCKED — shippers bound to these prices and legs
```

**Quotation rules**
- Holds its prices **5 days** as long as the parcel is unchanged (same items, quantities, destination, choices).
- Any change → a **new quotation** at current prices (the buyer made the change and sees the new cost).
- Older than 5 days → refreshed at today's prices and shown in the cart **before** checkout.
- A shipper changing its price table never affects quotations it already gave, or agreements.

**Agreement rules**
- Made when the checkout session is created. Edits on the checkout screen (before paying) re-calculate it and
  re-check the wallet; the 30-minute session expiry does not restart.
- Once paid: **the price is locked**; the agreement still needs the seller's and every shipper's signature
  before the parcel moves. After payment it changes only through **agreement changes** (§4.8).

### 4.2 Destination (where the quotation ends)
The start is always **the shop where the product is**. The buyer picks the end — no saved address needed:
saved address · recent pin · "use my location" · **search a known place** (Google Places in the app, e.g.
"Mbeya bus stand") · drop a pin. All end as a **confirmed pin** that we resolve (Google only in the app; we never
store Google's text; the buyer may add their own label).

**Meeting-point recognition:** a destination pin within **1 km** of a station → the quotation offers
"🚌 Collect at <company>, <station>" (no last-mile leg) and "🚪 Deliver to this exact pin" (if covered).

### 4.3 Add-to-cart / buy-now sheet
Deliver to (header address, changeable) · quantity · **Pickup** or **Delivery** with the ⭐ quotation pre-selected
and "change" (edit legs / destination).

```json
POST /api/v1/e-commerce/cart/add
{
  "productId": "…", "quantity": 2,
  "fulfillment": { "type": "DELIVERY", "quotationId": "…" },   // the SHOP's choice
  "dropoff": { "addressId": "…" }                               // only if changed in the sheet: the CART's destination
}
```

### 4.4 Cart rules
- **The choice belongs to the shop**, not the item — items from one shop share it.
- **One destination per cart**; changing it re-quotes every shop.
- Cart endpoints: set the cart's destination · set / edit a shop's quotation · get options for a shop.
- **Checkout from the cart turns its quotations into agreements.** Buy-now does the same from the sheet.
- **Unsaved new pin**: held on the **cart** as its destination (pin + directions) for as long as the cart exists;
  becomes a **recent pin only after payment** (abandoned carts never add recents). "Save as" → saved address at once.
- **Default for a shop newly added to the cart:**

  | Buyer has… | Shop's parcel defaults to |
  |---|---|
  | a destination and a shipper covers it | **Delivery** with the ⭐ quotation |
  | a destination, no shipper covers it | **Pickup** + "Delivery not available to Tabata" |
  | no destination at all | **Pickup** + "Add a delivery address to see delivery options" |

### 4.5 Estimation
```json
POST /api/v1/shipping/estimations
{ "dropoff": { "addressId": "…" }, "productIds": ["…", "…"] }
→ [ { "productId": "…", "cost": { "from": 3500, "to": 7000 }, "eta": { "from": "30 min", "to": "2 h" },
      "freeDelivery": false, "pickupArea": "Ubungo, Ubungo, Dar es Salaam" } ]
```
`cost` range = cheapest → dearest of the *sensible* options (dominated / outliers removed). No shipper →
`cost: null` (card shows "Pickup only"). Cached shop-area → buyer-area (Redis ~1 h). The app asks with the
address in its header; list and feed responses are unchanged. Prices are always called **cost**
(`cost`, `originalCost` when a discount applies).

### 4.6 What the app keeps vs the server
**Rule:** anything that affects money or a promise stays on the server; anything that is only "where the user was"
can live in the app.

| The app may keep (no backend storage) | Why it's fine |
|---|---|
| Header "Deliver to" for card estimations | sent with every estimation request; estimations are only hints |
| Last destination used / last map position | convenience for the pin screen |
| A sheet in progress (before tapping Add) | nothing committed yet |
| Recently searched places | the search runs in the app (Google) |
| UI preferences (list / map, "See all") | personal display |
| An unsaved pin, to offer it again on the pin screen | never becomes a backend recent unless the order is paid |

| Must stay on the server | Why |
|---|---|
| The cart's destination + each shop's quotation | quotations **hold prices 5 days** — a promise; must work on any device |
| Agreements | bind shippers and money |
| Saved addresses, recent pins | shared across devices, used when ordering |

### 4.7 Multi-shipper per order
One parcel can travel through **up to 3 shippers** (legs), e.g.:
```
Leg 1 🚪 Kibuti Express  Mlimani City shop → Magufuli Terminal (Dar)   3,500   2–3 h
Leg 2 🚌 Shabiby         Magufuli Terminal → Mbeya Bus Stand          21,000   1 day
Leg 3 🚪 Mbeya Riders    Mbeya Bus Stand   → buyer's door              2,500   1–2 h
```
- **Meeting points**: legs connect only where both businesses hand over — a station business's stations, a door
  business's office, or a station inside a door business's coverage. Two points within **1 km** count as the same place.
- **Fewer legs are fine**; the chain ends at the door or at a station, as the buyer wants.
- The engine **always** builds chains next to single-shipper options; ranking decides.
- In the quotation the buyer can **stop early** (collect at a station), **swap one leg's shipper**, or **change a meeting point**.
- Pickup and money per leg: §10, §11, §12.

### 4.8 The shipping agreement — parties, signatures, changes

The agreement is **the deal every party signs**: buyer, seller and every shipper on the route. It is its own
entity and **controls every important action** on a parcel: one place decides whether a change is allowed, one
history records who proposed and who approved, and **money moves only on an agreement event** (no other code
path releases or refunds an escrow part).

**Signatures — each party already says yes somewhere in the flow:**

| Party | Signs when | Agrees to |
|---|---|---|
| **Buyer** | pays at checkout | items, destination, legs, cost |
| **Seller** | accepts the order (within 24 opening hours) | pack it and hand it over |
| **Each shipper** | accepts the offer at Ready | carry their leg (capacity — the price came from their own price table) |

The buyer can be charged a fixed price before the shippers sign because each shipper's price table is a
**standing offer**; a shipper's signature means "I'll carry it", not "I accept the price".

**States:**
```
DRAFT      created at checkout; the buyer can still edit
PENDING    the buyer paid → waiting for the seller, then the shippers
AGREED     everyone signed → binding on all; the parcel can move
DONE       buyer confirmed "✓ It's what I ordered" → all escrow parts released
CANCELLED  refunded as the cancel rules say (§3.4a)
```
- A shipper rejecting or timing out = **declining to sign** → that party is replaced (reassignment, §10a); the
  agreement stays PENDING.
- **"The parcel doesn't move until all legs accept"** = it doesn't move until AGREED.
- A shipper's **Upcoming** list (§6.6) = agreements waiting for that shipper's signature.
- A bulky mismatch (§8.4) = a shipper **withdrawing** their signature before pickup for a reason that is not their
  fault → back to PENDING, the leg is reassigned.

**Changes.** A change only re-opens the signatures it affects (swapping leg 2 never asks the seller or leg 1).
Three kinds:
1. **Affects only me** → applied at once; the others are told.
2. **Affects others** → **proposed**; the affected parties approve; **silence falls back to a written default** by
   the deadline (so one silent party never blocks the deal).
3. **Rule-based** (NexGate / the system) → applied under the rule, logged.

| Change | Kind | Who must approve | No answer by the deadline |
|---|---|---|---|
| Buyer edits before paying (DRAFT) | 1 | — | — |
| Buyer cancels the whole order before the seller signs | 1 | — | — |
| Seller cancels (pickup before collected / delivery before Ready; pop-up "I informed the buyer", §3.1) | 1 | — (buyer notified at once) | — |
| Buyer cancels the shipping / switches to pickup (before pickup) | 1 | — (shipper released and told; fee if heading to the shop) | — |
| Buyer changes the destination **before any shipper accepted** | 1 | — (re-quoted at today's prices) | — |
| **Buyer changes the destination after a shipper accepted** | 2 | the shipper(s) whose leg changes | **original destination stays** |
| Accepted leg's time moves > 4 h | 2 | that shipper (re-confirm) | treated as "no" → leg reassigned |
| Reassignment — same / cheaper and not later | 3 | — | — |
| Reassignment — dearer / slower / nobody | 2 | the buyer | 24 h, then automatic switch to pickup |
| Chain not fully accepted 24 h after Ready | 2 | the buyer | 24 h, then automatic switch to pickup |
| Bulky mismatch | 3 | — (seller pays the difference automatically) | — |
| Admin action (§6.7.2) | 3 | — (reason required, audit-logged) | — |

**Destination change (buyer) — when it is allowed** (like AliExpress: the app shows **"Change delivery location"**
only in these statuses, and says up front when a courier must approve):

| Order status | Change? | How |
|---|---|---|
| **placed / accepted** (before Ready) | ✅ freely | no approval — re-quoted at today's prices; same shipper covers it → only the cost changes (pay / refund the difference); else the buyer picks a new option |
| **ready, offers out, nobody accepted** | ✅ freely | same; pending offers withdrawn, new ones sent |
| **shipper accepted** (incl. heading to the shop) | ✅ with approval | below — decline = that leg reassigned |
| **picked up / on the way** | ✅ with approval | below — decline = the original location stays |
| **chain, some legs done** | ✅ with approval | only the legs still to come are asked |
| **delivered / collected / completed** | ❌ | — |
| **pickup order** | — | "Deliver it instead" (§3.4) until collected |

**Limit: 3 location changes per order**; after that only support (admin) can change it.

**With approval.** The buyer proposes a new pin; NexGate checks the affected shipper covers it and
prices it from that shipper's table. The shipper sees old and new side by side (response window 30 min):

| Shipper answers | Result |
|---|---|
| **Accept at the new cost** | the buyer pays the difference into that leg's escrow, or gets it back if cheaper |
| **Accept at the old price** (waives the increase) | nothing more to pay |
| **Decline — before pickup** | that shipper withdraws → the leg is reassigned (§10a: automatic if same / cheaper and not later, else the buyer decides) |
| **Decline — after pickup** | the shipper **cannot withdraw** (never abandon a carried parcel) → the **original destination stays** |

- Only the legs whose from / to changes are asked (a new final door asks the last shipper only).
- New pin outside the shipper's coverage: before pickup → handled like a decline (reassignment); after pickup →
  not possible now (later: paid redelivery, §15b).
- Not allowed once the parcel is **delivered**.

**Sketch of the entity:**
```
shipping_agreement     order, status, version
 ├ agreement_party     role (buyer / seller / shipper), who, leg, signed / declined / withdrawn + when
 ├ agreement_leg       from / to place, shipper, cost, ETA        ← each LEG escrow part points here
 └ agreement_change    type, proposed by, who must approve, deadline, default, status, before / after
```

## 5. Group purchase and installments

**Group purchase**
- Each member chooses **their own** pickup / delivery and pays the delivery fee **with their payment**.
- Group fails or member withdraws → delivery fee refunded with the items. Transferred payment → fulfillment moves with it.
- **Price frozen at payment**, even if the group fills days later; a shipper rejecting then → normal reassignment.

**Installments**
- **Immediate** (ships after the down payment): the full delivery fee is paid **with the down payment**.
- **Layaway** (ships after the last instalment): **no shipping at checkout**; pickup / delivery is chosen and the
  fee paid **after the last instalment** (same mechanism as "switch to delivery").
- Agreement cancelled before shipping → delivery fee refunded.

---

## 6. Shippers

### 6.1 Two kinds
| | **Native** (delivery business on NexGate) | **Integrated** (external provider) |
|---|---|---|
| Set up by | owner, in the app | NexGate: one adapter + an admin row |
| Coverage / prices | owner's tables | the provider's API |
| Jobs | offer in the **app** (required); SMS = notifications only | NexGate calls their API |
| Status | owner taps in the app | their webhooks / polling, mapped to our statuses |
| Money | owner's NexGate wallet | a **provider ledger account**, settled by NexGate per contract / invoice |
| Delivery proof | our codes | their proof of delivery, else the buyer's "received" button |
| Chains | can be any leg | **single leg only** (whole trip, in one city) |

Both answer the same contract: **covers? · quotation (cost + ETA) · book · cancel · status** — the engine never changes.

**Shipper registry:** native shippers **register themselves** (§6.2). Integrated providers are **defined by the system**
(an adapter in code + one row created by NexGate) — never registered through the app; NexGate controls them fully
(on / off, API keys, categories, limits, spend cap). Each integrated provider has its **own ledger account** and an
**admin status view** (live rides, today's spend, balance owed, receipt differences, failed calls, webhook health).
The engine and the admin shipper list treat both kinds the same way.

### 6.2 Native registration — two parts
**Part 1 — KYC** (`POST /api/v1/shipping/businesses`) — legal, checked once, **auto-approved**:
business name · contact phone · **office location** (exactly one; pin screen like shops) ·
**business licence** (file + number + expiry; number unique) · **director's NIDA copy** (file + number) ·
**LATRA licence** (file + number + expiry). Documents are private (owner + admins).
→ status `KYC_APPROVED` (not live).

**Part 2 — Service Setup** (own endpoints, any time after KYC: `.../{id}/setup/profile|hours|coverage|pricing|limits`,
`GET .../{id}/setup` = checklist):
profile (logo, description, WhatsApp, email, vehicle badge) · service type (door and / or station) ·
working hours · coverage · pricing (station businesses: optional **collection from shops** — areas + fee, 0 = free) · limits (max value, accepts bulky + extra, response window, heads-up on/off).

**Live:** automatically once it has service type + coverage + pricing (hours default Mon–Sat 08:00–18:00).
Statuses: `KYC_APPROVED → LIVE ⇄ PAUSED` (owner), `SUSPENDED` (admin / automatic). A user may own several.
Needs two new File Thunder upload types: private business document, business logo.

### 6.3 Working hours (shared piece: businesses, shops, stations)
Several ranges per day · special days (holidays) · temporarily closed · same-day cut-off · EAT · overnight ranges allowed.

### 6.4 Shops: hours and pause
- Shops get opening hours (same piece): "Open now / Opens Sat 09:00"; seller timers count only open hours.
- **Pause** (existing `TEMPORARILY_OFFLINE` + until + reason) gets a mode chosen by the seller:
  **Keep selling — ships when back** (timers wait) or **Stop orders** (Buy off, `SHOP_CLOSED`).
  Orders placed before the pause must still be handled. Reopens automatically at "until".

---

### 6.5 Integrated provider: Bolt (first and only one for now)

API reference in the repo: `docs/shipping/providers/bolt/Bolt-Ride-Booker-API-Docs.pdf` (Ride Booker API).
**Bolt confirmed the same API is used for parcels.** The **Bolt Business account is ready.**

**NexGate is a reseller of Bolt.** The API is literally `/reseller/v1/...`: NexGate books rides with its business
account, **owns the customer** (buyer and seller never deal with Bolt), Bolt **bills NexGate monthly**, and claims /
refunds go NexGate → Bolt support (email) → credited on the monthly statement. To the buyer, Bolt is just one
delivery option sold by NexGate.

**Where Bolt is used**
- **Single leg, in one city, door-to-door only.** Never inside a multi-shipper chain (no handover codes, its price
  `fare_id` lives 5 minutes, a ride can go back to "searching").
- Bolt offers **boda** in Tanzania → **small, non-bulky parcels only**.
- Usually ranks ⚡ Fastest; ranked like any other option.

**Mapping to the contract**
| Our question | Bolt |
|---|---|
| Covers? | `estimations` — boda category with an ETA; `eta: null` or `AREA_NOT_SERVICED` = no |
| Cost + ETA | `estimations` → `price {minimum_amount, maximum_amount}`, `eta` |
| Book | at **Ready**: estimate again → check the held price → `POST rides` (`fare_id`, valid 5 min, single use) |
| Cancel | allowed until the ride has started |
| Status | webhooks (live only, from Bolt's 3 fixed IPs, with our token) or polling ride details (≤ every 10 s) |

| Bolt state | Our meaning |
|---|---|
| SEARCHING | offer out |
| DRIVER_ON_ROUTE_TO_CLIENT | accepted — rider coming to the shop |
| ARRIVED_AT_CLIENT | rider at the shop |
| DRIVING_WITH_CLIENT | picked up → on the way |
| COMPLETED | delivered (Bolt's proof) → buyer confirms with the button |
| NO_DRIVER_FOUND / CANCELLED | rejected → reassignment (another Bolt try or a native shipper) |
| back to SEARCHING after accepting, > ~10 min | cancel the Bolt ride → reassignment |
| CLIENT_DID_NOT_SHOW (shop didn't hand over) | **seller pays** Bolt's charge (from the items part at release); re-book on the next Ready |

**Price**
- Quotation shows Bolt's **maximum amount + 2%**. NexGate absorbs any difference within that (Bolt's final price
  can move — the receipt may change up to 24 h later).
- At Ready: new estimate within the held price → book; above it → treated as a dearer reassignment (buyer decides).
- Real charges recorded on the **Bolt ledger account**, reconciled monthly with Bolt's invoice.

**On the ride**
- Bolt "user" = **the shop's contact** (driver calls them for pickup); the **receiver** goes in the note to the driver
  (template: "NexGate parcel. Pickup: <shop, landmark>. Deliver to: <receiver name, phone, directions>. Do not open.").
- Bolt returns the driver's **name, photo, phone, plate** and a **tracking link** → shown to seller (check the plate at
  pickup, instead of a code) and buyer ("with Juma, boda T 123 ABC — track").
- Codes: Bolt drivers can't enter ours → pickup = plate check; delivery = Bolt COMPLETED + buyer's "received" button.

**Control**
- Admin **kill-switch** (Bolt off instantly) and a **daily spend limit**.
- OAuth2 client credentials, tokens 10 min — backend only, cached and refreshed. Sandbox available for building.

### 6.6 The shipper app (native shippers)

**Same NexGate app**, in a "delivery business" mode (like managing a shop) — no separate rider app.
**For now only the owner** uses it; team members (dispatcher / rider roles, assigning jobs, the rider's name shown
to buyers) come later when businesses grow. Earnings always go to the owner's wallet.

| Screen | What it's for |
|---|---|
| **Dashboard** | today's jobs, open offers, **upcoming orders**, earnings held / released, reliability, "Paused" banner |
| **Upcoming** | orders in a **paid agreement** with this shipper, **from payment**, before any offer (below) |
| **Offers** | job offers with a **countdown**: from / to on a map, parcel value band, bulky, cost, when the parcel reaches them (chains) → **Accept** / **Reject (reason)** |
| **Heads-ups** | "order coming from Sinza in ~15 min" (non-binding) |
| **Active jobs** | exact from / to (office, map, phone, hours), receiver, note, navigation, **one button per next step** |
| **Codes and handovers** | show the pickup code to the seller; enter the buyer's delivery code; chain "handed over" / "received" + code; optional photo |
| **Re-confirms** | "parcel now reaches you at 23:00 instead of 15:00 — still OK?" |
| **History · Earnings · Reviews & reliability · Setup** | past timelines · held → released per job, wallet · ratings, replies, scores · KYC, Service Setup, pause / resume |

**Upcoming orders**
```
Upcoming (5)
🕐 Kariakoo → Mikocheni · small · 7,000        Waiting for the seller to accept
📦 Sinza → Mbezi · bulky · 22,000              Seller is packing — offer expected soon
🚌 Leg 2: Magufuli → Mbeya Stand · 21,000      Parcel expected at your office tomorrow ~10:00
```
- **Shippers see a parcel, never the order**: parcel number, size / bulky, value band, from / to, their cost —
  not the items, prices or order number.
- Shown **from payment**; chips: waiting for the seller → seller packing (= heads-up) → for chain legs, when the
  parcel is expected. On **Ready** the card moves to **Offers**.
- **Not a commitment** (accepting is at the offer). Cards can disappear (buyer cancels, switches to pickup, seller
  times out) with a short note.
- **Privacy:** until the shipper **accepts the offer** it sees **areas only** (ward / district), parcel size / bulky,
  value band and its cost — **not** the exact pin, directions or receiver phone. Full details after accepting.

**Endpoints (sketch)** — also pushed live to the app, like chat:
```
GET  /api/v1/shipping/businesses/{id}/upcoming
GET  /api/v1/shipping/businesses/{id}/offers
POST /api/v1/shipping/offers/{offerId}/accept | /reject      (reason)
GET  /api/v1/shipping/businesses/{id}/jobs?status=active
POST /api/v1/shipping/jobs/{jobId}/status                    (next step)
POST /api/v1/shipping/jobs/{jobId}/handover                  (code + optional photo)
POST /api/v1/shipping/jobs/{jobId}/reconfirm
GET  /api/v1/shipping/businesses/{id}/earnings
```

### 6.7 Admin side and settings

**Build order:** the admin **dashboard (screens) is the last thing built**, after everything works. But the admin
**endpoints** needed to fix stuck orders ship **with** the shipping service (no screens yet) — §6.7.2.

#### 6.7.1 Where each setting lives

**1 — Properties file: fixed platform rules** (change = config + redeploy)
| Setting | Value |
|---|---|
| Meeting-point range | 1 km |
| Loop guard (reassignments per order) | 3 |
| Re-confirm threshold for accepted legs | 4 h |
| Chain safety net / buyer decision timeout | 24 h / 24 h |
| Closed shipper: wait if it opens within | 4 h |
| Seller accept window | 24 opening hours |
| Pickup collection window (shop) / station + shipper-office hold | 14 days / 7 days |
| Destination changes per order | 3 |
| Quotation price hold | 5 days |
| Outlier rule / "expensive parcel" | 3× / 500,000 |
| Quotation options shown | top 5 |
| Codes: length / max wrong tries | 4 digits / 5 |
| Distance factor / rounding | ×1.3 / up to the nearest 100 |
| Estimation cache | 1 h |
| Auto-pause: missed offers warn / pause | 2 / 3 |
| Auto-pause: suspend after auto-pauses | 3 within 7 days |
| Acceptance rate warn / pause (last 20) | 50% / 30% |
| Broke binding: suspend after / found at fault: suspend after | 2 in 30 days / 2 in 30 days |
| False bulky claims → suspend | 3 |
| On-time warning (last 20 jobs) | 60% |
| Grace period (rate rules) | first 10 offers |
| Bulky mismatch: wasted-trip fee / auto-flag after | 50% of the leg cost / 2 mismatches (different shippers) |
| Defaults shippers can override | response window 30 min · station reach 30 km |
| Bolt | price buffer 2% · category boda |

**2 — Per shipper, set by NexGate** (the NexGate ↔ shipper agreement)
| Setting | Notes |
|---|---|
| **Delivery commission %** | default = a new fee type in the effective-dated fee table (0% now); a shipper with its own deal gets an **override with a start date** (past orders keep the old rate) |
| Settlement terms (integrated) | Bolt: monthly invoice |
| Daily spend limit (integrated) | e.g. Bolt 2,000,000 / day |
| On / off (integrated) | the kill-switch |
| Suspended / lifted (native) | with a reason the shipper sees |

**3 — Per shipper, set by the shipper** (Service Setup): hours, coverage, stations, prices, limits, heads-up on/off,
its own response window, its own station reach.

**4 — Admin-managed data**: free-shipping campaigns, integrated provider records, review moderation, manual money actions.

#### 6.7.2 Admin endpoints that ship WITH the shipping service (no screens)
`SUPER_ADMIN` only · every call needs a **reason** · every call is written to the **audit log** (who, what, when, why).

| Endpoint (sketch) | Why it's needed from day one |
|---|---|
| `POST /api/v1/admin/shipping/escrows/{escrowId}/release` · `/refund` | stand-in for disputes: fix a stuck or reported order by hand |
| `POST /api/v1/admin/shipping/orders/{orderId}/reassign` · `/cancel` | unstick a chain |
| `POST /api/v1/admin/shipping/businesses/{id}/suspend` · `/lift` | stop a bad shipper |
| `POST /api/v1/admin/shipping/providers/{code}/enable` · `/disable` | Bolt kill-switch |
| `PUT  /api/v1/admin/shipping/businesses/{id}/commission` | per-shipper commission override (with start date) |

#### 6.7.3 The dashboard (built last)
| Area | Contents |
|---|---|
| **Native shippers** | list / search / filter; one shipper's page: profile, **private KYC documents**, coverage map, stations, prices, reliability, reviews, jobs, earnings; suspend / lift; hide review; documents expiring soon |
| **Integrated providers** | kill-switch, spend limit, category, buffer; **status view**: live rides, today's spend vs limit, balance owed, receipt differences, failed calls, webhook health; **settlement**: record the monthly invoice, match the ledger, mark paid. API keys live in **Vault**, never in the database |
| **Operations board** | stuck things: chains not fully accepted, buyer decisions waiting, money held a long time, problem reports, Bolt rides stuck searching — with the §6.7.2 actions and internal notes |
| **Campaigns** | create / edit / pause / stop; budget used / reserved / left |
| **Reports** | by ward / district / region only (never per person): deliveries, on-time rate, average cost, pickup vs delivery, shipper ranking, Bolt spend |
| **Audit log** | every admin action |

**Who can do what (when the dashboard comes):** `STAFF_ADMIN` — view everything, suspend / lift, hide reviews, notes,
force reassignment. `SUPER_ADMIN` only — anything with money (release / refund, settlement), settings, Bolt
kill-switch and limits, campaigns, commission overrides.

## 7. Coverage

### 7.1 One model for door and station businesses
1. **Where do you work?** Tick areas from the region → district → ward list (with search). A read-only map
   shows the ticked areas to confirm. No radius, no drawing.
2. **Trips:** `WITHIN_EACH` (both ends inside the same ticked area) or `WITHIN_AND_ACROSS` (both ends inside any
   ticked areas — crossing borders between them). **Both ends must always be inside the ticked areas.**
3. **Lines** (optional, station businesses with separate lines): groups of areas; trips only between areas of the same line.

### 7.2 Stations (station businesses)
- **As many stations as needed**; at least **one per ticked area**, several per area allowed (e.g. Dar: Magufuli,
  Kariakoo, Ubungo). A station = a pin (Google map + our resolve, like a shop) + counter name + phone + own hours.
  Each business has its own stations.
- **Reach:** the buyer collects within **30 km** of a station (the shop side is reached by a door leg, §7.2a).

### 7.2a Handover points — where each leg picks up and drops off
1. **Leg 1 always starts with a collection at the shop** (**option A, decided 2026-10-13**) — the seller never
   leaves the shop. Who collects:
   - **A station business that collects from shops** — it ticks the areas where it collects (same area picker) and
     sets a **collection fee** (flat; **0 = free**). How it gets the parcel to its station is **its own business**;
     we don't model it. The collection is **part of its leg**: one leg, one business, one escrow part, the pickup
     code at the shop, "heading to the shop" applies.
     ```
     Leg 1 🚌 Shabiby (collects free)  shop (Ubungo) → Mbeya Bus Stand   21,000   1 day
     ```
   - **Otherwise a door shipper** — the station route becomes a **chain**: door leg shop → station, then the
     station leg(s):
     ```
     Leg 1 🚪 boda     shop (Ubungo) → Magufuli Terminal        3,500
     Leg 2 🚌 Shabiby  Magufuli Terminal → Mbeya Bus Stand     21,000   → buyer collects, or leg 3 door
     ```
   - Neither → no station route from that shop (door-only options, else pickup only).

   The engine builds both kinds side by side; **no special boost** — free collection wins on cost by itself, and
   **"fewer handovers"** breaks ties when cost and arrival are equal. After launch (§16): the seller may drop at stations.
2. **Station businesses hand over only at their own stations** (a bus company never drives to a door).
3. **Door businesses go wherever the leg needs**, inside their coverage: the shop, a station, the buyer's door.
   **Door shippers always come to the shop** for leg 1 (the seller does not drop at a door shipper's office — after launch).
4. The engine chooses **which** station: origin = a station a door shipper can reach from the shop (both inside that
   door shipper's coverage), nearest first; destination
   = its station nearest the buyer (within reach) **and** priced in its pair table; bus → bus offices within **1 km**.
   Several stations in reach → each is a candidate; ranking picks; the others are alternatives in the quotation.
5. **Every leg in the agreement stores its exact from / to place** (office name, pin, phone, hours), which is what
   that shipper's app shows ("Collect at: Shabiby office, Magufuli Terminal, gate 3 · [map] · open 06:00–20:00").

### 7.3 How the engine checks a trip
1. **Fast filter by area codes** (no maps): both ends inside, trips rule, line rule.
2. **Stations** (station businesses): origin station reached by a door leg from the shop (§7.2a), destination station
   nearest the buyer within reach.

### 7.4 Coverage request (sketch)
```json
PUT /api/v1/shipping/businesses/{id}/setup/coverage
{ "areas": [ { "level": "REGION", "regionCode": "07" },
             { "level": "DISTRICT", "regionCode": "05", "districtCode": "03" },
             { "level": "WARD", "wardId": 1146 } ],
  "trips": "WITHIN_AND_ACROSS",
  "lines": [ { "name": "Line A", "areas": [0, 1, 2] } ],
  "stationReachKm": { "seller": 30, "buyer": 30 } }
```
Location helpers: region → district → ward lists + search; coverage outline for the map.

---

## 8. Pricing and ETA

### 8.1 Cost of one parcel
```
base (shipper's table) + value add-on (insurance) + bulky extra = cost
```

**Base**
- **Door — distance bands** (price + time each). Distance = straight line × 1.3. Last band's end = max distance.
  ```
  0–3 km   2,000   30–60 min
  3–7 km   3,500   1–2 h
  7–15 km  5,000   2–3 h
  ```
- **Door — flat**: one price + one time.
- **Station — pair table**: from station → to station, price + time, "both ways" ✓. The app pre-fills the pairs;
  an empty pair = not carried.
- **Station — collection from shops** (optional): areas where it collects + one flat **collection fee** (0 = free) +
  the time it adds. Cost = collection fee + the pair price from its station nearest the shop.

**Value add-on** (optional ladder; fixed amounts per value range, % allowed for the top range) + **max value accepted**.
Parcel value = the shop's items in the cart.

**Bulky**: new product field `bulky` (category can pre-tick); a parcel is bulky if any item is.
Shipper: accepts bulky yes / no + extra. Non-accepting shippers are filtered out.

**Rounding**: whole TZS; add-ons rounded **up** to the nearest 100. New prices apply to new quotes only.

### 8.2 ETA
- Always **from when the shop is ready**, always a **range**.
- Door: the band's time. Station: the pair's time. Plus closed hours (shipper / station hours, cut-off).
- Record real delivery times from day one (reliability-based ETA after launch).

### 8.3 Fees
- **Delivery commission**: new fee type, **0%** for now, deducted from the shipper's part.
- **Seller's platform fee: items + tax only** (changes today's "fee on full total incl. shipping").

---

### 8.4 Bulky mismatch (product not ticked "bulky" but it is)
Rule: **the seller pays** (they set the flag), **the buyer's price never changes**, repeated mistakes **fix the flag**.

1. **Shipper reports at the shop, before pickup**: "Can't carry — too big / heavy" (+ optional photo). Not possible
   after the pickup code is used.
2. **That leg is reassigned for bulky only**: rejection reason `BULKY_MISMATCH` — **not counted against the shipper's
   reliability**; the parcel is now bulky → only bulky-accepting shippers, with their bulky extra.
3. **Money**: the replacement's extra cost is paid **by the seller automatically** (taken from the items escrow at
   release). The buyer is **not asked** — just told "too big for a boda; a car is coming, no extra cost to you".
4. **Wasted trip**: native first shipper gets **50% of its leg cost** (properties setting), paid by the seller;
   Bolt → Bolt's cancellation charge, paid by the seller.
5. **Nobody can carry it**: the buyer chooses **pickup** (delivery refunded) or **cancel the whole order** (full
   refund — seller's fault); the seller still pays the wasted trip.
6. **Fixing the flag**: 1st mismatch → seller told to tick "bulky" (with the photo); **2nd mismatch on the same
   product from a different shipper → bulky set automatically**; mismatches count in the seller's private reliability.
7. **Abuse**: a shipper claiming mismatches on products others carry fine → flagged for admins.
8. **Opposite case** (ticked bulky, actually small): no automatic change — higher prices are incentive enough.

### 8.5 Packing — the seller packs
- **The seller packs** (like AliExpress / Jumia): they know the item (fragile, leaking, box vs bag); packing happens
  before any shipper has the parcel; the box is part of the seller's item price, never a separate charge. The Ready
  pop-up ("I have packed it well", §10) records it.
- **Liability**: damaged because of poor packing → the seller; packed well and crushed on the way → the shipper
  (decided from the handover timeline and optional photos).
- **The shipper checks the outside at pickup** (QR scan, a look, optional photo).
- **"Badly packed" refusal** — same pattern as a bulky mismatch (§8.4): **at the shop, before pickup** only; reason
  `BADLY_PACKED` (torn, leaking, a fragile item with no protection) + photo; **not counted against the shipper**.
  The seller **repacks and taps Ready again** → the same shipper is offered it again (normal window), else the leg
  is reassigned. The seller pays the **wasted trip** (native 50% of the leg / Bolt's charge), from the items escrow
  at release. The buyer's price never changes; the buyer is told "the seller is repacking your parcel".
- Repeated `BADLY_PACKED` reports count in the seller's private reliability; a shipper reporting it on parcels
  others carry fine → flagged for admins (as §8.4 rule 7).

## 9. Engine and ranking

1. **Where**: both places' ward / district / region.
2. **Who**: native coverage + integrated providers (skip a provider slower than ~2 s).
3. **Filter**: coverage, max distance, max value, bulky, closed / cut-off (ETA shifts, not dropped), paused / suspended.
4. **Cost + ETA** for each.
5. **Clean-up**: hide **dominated** options (dearer *and* slower) and **outliers** (> 3× the cheapest of the same type) — "See all" shows them.
6. **Labels**
   - 💰 **Cheapest** — ties → earlier arrival → reliability.
   - ⚡ **Fastest** — by the **latest** arrival of the range — ties → cheaper.
   - ⭐ **Recommended** — balance score; parcel > 500,000 → reliability-heavy; cheap parcel → price-heavy; else
     price + speed. **At launch: price + time only** (reliability added after launch).
   - One option may carry two labels.
7. **Order**: labelled first (⭐ 💰 ⚡), then grouped "To your door" / "Collect at a station" by cost; top 5 + "See all".
8. **Fairness**: new shippers get a neutral reliability + "New" badge; exact ties rotate.
9. Quotations hold their prices **5 days** (§4.1); the sheet pre-selects ⭐.

---

## 10. Job flow

1. **Seller accepts** within **24 opening hours** — else auto-cancel + full refund. Shipper gets a non-binding
   **heads-up** (switchable per shipper).
2. **Seller taps Packed / Ready** → a **confirm pop-up** with two ticks, both required:
   ☐ *"I have packed it well"* · ☐ *"The parcel label (QR) / number is on the package"* (delivery only; pickup asks
   only the first). Recorded with the time — part of the evidence trail if a parcel arrives damaged or unlabelled.
   Then → pickup: buyer told; delivery: the offer goes to **every leg at once**, each
   showing when the parcel reaches them. **The parcel does not move until all legs have accepted.**
3. **Response window 30 min** (per shipper), counted only while the shipper is open. Shipper closed at Ready →
   wait if it opens within ~4 h, else reassign.
4. **Accept** = the shipper **signs the agreement** (§4.8) — capacity, not price (the price is the agreement). **After accepting it is binding: the shipper must
   find a way** — no buyer rescue mid-way; failing = heavy reliability hit, auto-pause, dispute / liability.
   **Reject (reason) or timeout before accepting** → reassignment (§10a).
5. **Who taps what**: seller — accept, ready, verifies the pickup code; shipper — accept / reject, every status,
   submits the delivery code; buyer — gives the code (or the button), confirms "it's what I ordered".

### 10a. Reassignment (a shipper rejects or doesn't answer — before accepting)

Only **before** a shipper accepts; after accepting it is binding.

1. **Record**: leg marked *rejected* (with reason) or *timed out* — a timeout counts exactly like a rejection.
   That shipper is excluded from this order and takes a reliability hit; **3 missed offers in a row → auto-pause**.
2. **Replace that leg only.** Other legs keep their acceptance; **nothing moves until every leg has accepted.**
   The replacement is the best-ranked option using **the label the buyer chose** (💰 → cheapest replacement …).
3. **Search in steps — stop at district:**

   | Step | Replacement | Neighbouring legs |
   |---|---|---|
   | **1. Nearby** | office within **1 km** of the original handover points | keep shipper + cost; get the updated exact office; **no re-confirm** |
   | **2. Same district** | office in the **same district** as the original point | door legs **re-route** inside their coverage and are **re-costed**; the **total of the affected legs** is compared; neighbours already accepted get a **re-confirm** ("drop at Ubungo Terminal instead, OK?") |
   | **3. Beyond the district** | — no automatic swap | **buyer decides** |

   Door legs follow the same steps (first the same points, then a meeting point elsewhere in the district).
4. **Compare with the agreement** (for the affected legs):
   - **same or cheaper AND arriving no later** (by latest arrival time) → **automatic**; the buyer is told; leg escrow **re-pointed**,
     difference **refunded**;
   - **dearer / slower / nobody** → the **buyer decides** while the parcel is still at the shop: pay the difference
     (top-up into the same leg escrow) · end the chain earlier (later legs refunded) · switch to pickup (all legs
     refunded) · cancel (everything refunded).
5. The new shipper gets the offer (normal response window) — and may reject too (back to step 1).
6. **Loop guard: 3 reassignments per order** (not per leg) → after that the buyer is always asked.
7. **Closed shipper at Ready**: its window starts when it opens if that is within **4 h**; otherwise reassign at once.
7a. **Accepted legs whose time moves**: moved by **≤ 4 h** → an update, still bound; moved by **> 4 h** → **re-confirm**
    ("now 23:00 instead of 15:00, still OK?"); "no" → that leg is reassigned (counts toward the 3 per order).
7b. **Chain safety net**: not fully accepted **24 h after Ready** → the buyer is asked: keep waiting · end the chain
    earlier · pickup · new delivery proposal · cancel the whole order.
7c. **Buyer doesn't answer a decision screen**: reminders, then after **24 h** → **automatic switch to pickup**
    (leg escrows refunded; the buyer can still ask for a new delivery proposal).
8. **Free shipping**: seller / campaign caps are recalculated for the new cost; the buyer pays only what's above them.
9. **The agreement keeps its history** ("leg 3: Mbeya Riders rejected 10:42, busy → Mbeya Express 2,500").
10. **Who is told**: buyer (notice on auto swaps / decision screen) · seller ("waiting for a courier", nothing to do) ·
    legs already accepted ("still waiting for the full route", or a re-confirm when their point moved).

---

## 11. Codes and handovers

**Parcel number** — identifies the parcel (the codes below prove the handover):
- One per parcel (one shop order), created when the **seller accepts** the order — so the label can be printed while
  packing, before the Ready pop-up asks for it. Every order gets one, **pickup too** (the counter finds the parcel on
  the shelf by it; a later switch to delivery keeps the same number); short and readable aloud, no 0/O or 1/I — e.g. **`NX-4K7P-2Q`**.
- **The same on every leg**: boda, bus company and station staff all see it; station staff **search by it** on
  arrival and when the buyer collects; the buyer sees it too.
- **QR label at launch, made by the app (frontend)** — the backend only gives the parcel number. From **accept** the
  seller's app shows a label: **QR (the parcel number only — no personal data)** + the number in large
  text + receiver name + from / to areas → print or share it to a printer. **No printer → the seller writes the
  number on the box** (the fallback always works).
- **Checked at every pickup / handover**: the receiving shipper (or station staff) **scans the QR** or types the
  number → the app confirms
  **"✓ this parcel is yours"** or **"✗ wrong parcel — not on your job"** before the code is used. Stops the wrong box
  leaving the shop or a busy station.
- Not secret (it's on the box) and separate from the order number, which never reaches shippers.

| | Parcel number `NX-4K7P-2Q` | 4-digit codes |
|---|---|---|
| Purpose | **identifies** the parcel | **proves** a handover |
| Secret? | no — written on the box | **yes** — hashed, never logged |
| How many | one per parcel, for life | one per handover |

**Codes**
- **4 random digits**, hashed, never logged, valid for one order. **5 wrong tries** → locked; the owner gets a new one.
- **Pickup code** — shipper receives it after accepting; at the shop the **seller verifies** it, then hands over
  (proves the right shipper collected).
- **Delivery code** — buyer receives it once the parcel is on the way; the **shipper submits** it at the door.
- **Shipper → shipper** (multi-shipper): the giver taps "I've handed over", the receiver taps "I've received" and
  enters that handover's code; optional photo from either side. One side missing → flagged for disputes.
- **Pickup at the shop / collection at a station** — the same delivery code, entered by the seller / station staff.
- **Buyer option (account setting):** use a **"received" button** instead of the code. Default = code.
- **Handover photos**: optional for now (stored if taken) — the evidence trail for disputes.
- Integrated providers: their proof of delivery, else the buyer's button.

---

## 12. Money

### 12.1 Escrow parts per order
```
Buyer pays once → ORDER ESCROW
   ├ items part  → seller (fee: items + tax)
   └ leg part    → shipper owner (native) / provider ledger account (integrated)   ← one per leg
   (pickup = items part only)
```
"Held" = in escrow, nobody's yet. **Release** = to the payees. **Refund** = back to the buyer.
Each part can be released or refunded on its own.

**One escrow record per part, all children of the order:**
```
Order ORD-…  (one shop's parcel)                                     ← parent
 ├ ESC-…101  part ITEMS  payee seller                    60,000  HELD
 ├ ESC-…102  part LEG    payee Kibuti Express   legId L1  3,500  HELD
 ├ ESC-…103  part LEG    payee Shabiby          legId L2 21,000  HELD
 └ ESC-…104  part LEG    payee Mbeya Riders     legId L3  2,500  HELD
```
- Each record: `orderId` (the escrow table's existing, unused field — now filled) · `part` (ITEMS / LEG) ·
  `legId` · its own payee (user or provider account) · amount · fee · status · ledger account.
- Why separate records: each part moves on its own (refund only leg 3, re-point only leg 2, pay an innocent
  rider in a dispute); everyone's history shows only their own money; the ledger already works per escrow;
  it is the cart-fix mechanism (one payment → several escrows), whose `session_part` key folds into this.
- **Release** ("it's what I ordered") = every escrow of the order, found by `orderId`, in **one transaction**.
- The buyer still sees **one payment** line listing its escrows.
- Table changes: `part`, `legId`, `orderId` filled, and a **provider payee**.

### 12.2 When money moves
- **Everything stays held until the buyer taps "✓ It's what I ordered"** (after receiving) — then **all parts are
  released together** (seller and shipper).
- **"⚠ Report a problem"** → **all parts frozen**; the dispute involves buyer, seller **and the shipper**
  (the rider could have swapped or damaged the parcel); the admin decides from the handover timeline.
- **No automatic release for now.**

### 12.3 Adjustments and refunds
| Event | Money |
|---|---|
| Reassign — same / cheaper | leg part re-pointed to the new shipper; difference refunded |
| Reassign — dearer | buyer tops up the difference into the same leg part, or switches / cancels |
| Pickup → delivery | new payment for the leg part(s) |
| Delivery → pickup / cancel the shipping, shipper not heading to the shop yet | leg part(s) refunded |
| Cancel the shipping, shipper heading to the shop | leg part refunded minus the wasted-trip fee (native 50% of the leg / Bolt's charge), which goes to the shipper |
| Destination change | difference paid into / refunded from that leg part (nothing if the shipper keeps the old price) |
| Cancel before the seller accepts / pickup not collected in 14 days / seller cancels (§3.1) / group fails | all parts refunded |
| Installment immediate / layaway | legs with the down payment / a new payment at the end |

The escrow table must allow a **provider payee** (today every escrow needs a user).

---

## 13. Free shipping

**Seller-funded** (shop setting): areas (same picker) · optional min order (this shop's items) · "I pay up to X per
delivery" · product override (use shop / always free / never free). Mixed parcel: free only if every item qualifies.

**NexGate campaigns** (admin): areas · dates · min order · cap per delivery · audience (everyone / first order) ·
shops (all / selected) · total budget → stops automatically; budget **reserved at payment**.

**Rules**
- The **cheapest qualifying option** becomes free (up to the cap); faster options cost the difference.
- **Stacking**: delivery cost − seller (cap) − NexGate (cap) = buyer pays.
- **Shipper always paid in full**: leg part holds the full cost = buyer's share + NexGate's share (from the
  campaign ledger account at payment) + seller's share (taken from the seller's items part at release).
- Refund → NexGate's share returns to the campaign budget.
- Display: ~~3,500~~ **Free**; card badge "Free delivery"; search filter "Free delivery to my area".

---

## 14. Reviews, reliability, auto-pause

- **Reviews** like shops (rating 1–5 + text, owner reply, moderation statuses, summary) — **no subscribe** — and
  **only from people the shipper served** (buyers it delivered to, sellers it collected from), tagged
  "Verified delivery". Shown on the shipper profile and in quotes ("⭐ 4.6 (120)").
- **Reliability** (internal, automatic): acceptance rate, on time vs quoted ETA, failed / returned, disputes lost.
- **Auto-pause** — three levels, warnings first:

  | Level | Undone by | Effect |
  |---|---|---|
  | ⚠ Warning | — | notice ("one more missed offer and you'll be paused") |
  | ⏸ Paused | **owner** taps Resume | no new quotations / offers |
  | ⛔ Suspended | **admin only** (reason) | same + hidden from buyers |

  Accepted jobs are **always finished** (binding); agreements not yet offered are reassigned at Ready.

  | Signal | ⚠ Warning | ⏸ Paused | ⛔ Suspended |
  |---|---|---|---|
  | Missed offers in a row (timed out) | 2 | **3** | — |
  | Auto-pauses | — | — | **3rd within 7 days** |
  | Acceptance rate (last 20 offers) | < 50% | < 30% | — |
  | Broke a binding job (accepted, then failed) | — | 1st time | **2nd within 30 days** |
  | Found at fault in a problem report | 1st time | — | **2 within 30 days** |
  | False bulky-mismatch claims (flagged) | — | — | **3** (admin review) |
  | On time vs quoted ETA (last 20 jobs) | < 60% | — | — |

  - Rejecting **with a reason** is allowed — it only counts through the acceptance rate, never "in a row".
  - **Grace period**: rate rules (acceptance, on-time) apply only after the **first 10 offers**.
  - "In a row" resets on the next accepted offer; 7 / 30 days are rolling windows.
  - Every action shows the shipper **why** ("Paused: 3 offers missed — 10:02, 10:41, 11:15") and is recorded for admins.
  - Numbers live in the properties file. Integrated providers are not auto-paused (kill-switch instead).
- **Two-way ratings (private)**: shipper rates the buyer (address, no-show) and the seller (late handover).

---

## 15. Open — to talk about next

| # | Topic | Where we are |
|---|---|---|
| 1 | ~~Buyer cancellation rule~~ | **decided** — see §3.4a |
| 2 | **Buyer never confirms** (all parts held) | proposed: a check window after the delivery code; no decision |
| 3 | **Disputes** | **skipped for now** (decided). Draft discussed: buyer / shipper / seller can open; reasons; evidence + automatic handover timeline; 48 h to respond; outcomes no fault / full / partial / return & refund / replacement; shipper liability capped at its leg part; one module for digital + physical |
| 4 | **Failed delivery** (buyer unreachable, refuses the parcel, return trip) | with disputes |
| 5 | ~~Auto-pause numbers~~ | **decided** — §14 |
| 8–12 | ~~Reassignment proposals~~ | **decided** — §10a items 4, 7a–7c; door shippers always come to the shop (§7.2a) |
| 6 | ~~Cart: unsaved new pin~~ | **decided** — §4.4 |
| 7 | ~~Cart: default for a shop newly added~~ | **decided** — §4.4 |
| 13 | **Seller cancels a delivery order AFTER Ready** | open — before Ready is decided (§3.1); after Ready shippers have offers or signed (heading to the shop → who pays the wasted trip?) |

## 15a. Future — decide after implementation

Parked on purpose (2026-10-12): build the main flows first, then decide these with real cases.

| # | Scenario | What we know so far |
|---|---|---|
| F1 | **Buyer never confirms the delivery** (never there to receive / never gives the code) | idea: the shipper **holds the parcel** and it is **returned to the shipper's office**; how long, who pays storage / the trip back, what happens to the money — to decide |
| F1b | **Buyer received (code entered) but never taps "✓ It's what I ordered"** | all escrows stay held (no auto-release decided); a check window was proposed — to decide |
| F2 | **Failed delivery** — buyer unreachable, refuses the parcel, wrong address | "we will find a way later": re-attempt? return to the shop or the shipper's office? who pays? |
| F3 | **Parcel never collected at a station** | no rule yet (shop pickup has the 7-day rule); days to collect, storage, return — to decide |
| F4 | Disputes, returns, shipper liability | skipped for now — draft in §15 row 3 |

## 15b. Plan for the unhappy paths (recommended — NOT implemented now)

Based on common practice (Jumia, DHL-style couriers, Glovo, bus parcel services). **Principle: whoever caused
the failure pays for it.** These are recommendations to confirm after the main flows are built.

### Recommended rules

**F1 — Buyer not there to receive**
1. Rider **calls** the buyer and **waits ~10 min**, then marks **"attempt failed"** (time, location, optional photo).
   Buyer is notified: "We missed you — reschedule?"
2. **Up to 2 attempts**; the buyer picks a new time for attempt 2 in the app.
3. After the last failed attempt the parcel goes to the **shipper's office** and is **held 7 days** — the buyer can
   collect it there or ask for **redelivery** (pays a new delivery cost).
4. Not collected in 7 days → **returned to the seller**. Buyer refunded **items only**; the delivery cost is kept by
   the shipper (work done) and the return trip is charged to the buyer.

**F1b — Delivered (code entered) but the buyer never taps "✓ It's what I ordered"**
- **Auto-confirm after 3 days** (like digital products today); **7 days for parcels above 1,000,000**.
- Reminders at 24 h and 48 h. **"⚠ Report a problem" stops the clock.**
- Safe because the delivery code proves the buyer has the parcel.

**F2 — Failed delivery**
| Cause | Rule |
|---|---|
| Unreachable | F1 |
| Refused at the door, no reason | back to the seller; buyer refunded items **minus delivery + return** |
| Refused because wrong / damaged (seen at the door) | rider records reason + photo; back to the seller; buyer **full refund**; cost on the at-fault party (dispute) |
| Wrong / unclear address | rider calls; corrected spot **inside the shipper's coverage** → deliver (buyer pays any difference); else F1 |

**F3 — Parcel never collected at a station**
- Arrival notice; reminders on days 1, 3, 6.
- **7 days free** (shop pickup is 14 days — a shipper's shelf space costs them; a shop already holds the item).
- Not collected → **returned to the seller** via the reverse route; buyer refunded items **minus delivery + return**.
- Daily storage fee: possible later, not at first.

**Who pays**
| Failure caused by | Pays |
|---|---|
| Buyer (absent, refused without reason, never collected) | loses the delivery cost + pays the return; items refunded |
| Seller (wrong / damaged item seen at the door) | both ways; buyer fully refunded |
| Shipper (lost, broken, gave up after accepting) | its leg + liability (with disputes, later) |

### Plan — prepare now, switch on later

| Phase | What | When |
|---|---|---|
| **0 — data hooks (build WITH the shipping service)** | so the rules above slot in without rework: **delivery attempt records** (time, location, photo, outcome); **failure reason codes** (UNREACHABLE, REFUSED, REFUSED_DAMAGED, WRONG_ADDRESS, NOT_COLLECTED); statuses **ATTEMPT_FAILED, HELD_AT_OFFICE, RETURNING, RETURNED**; the **held-at place** on the fulfillment; timers stored as data (not code constants); the **reverse direction** allowed on a leg (A → B and B → A) | now |
| **1 — F1b auto-confirm** | the 3 / 7-day window + reminders (reuses the digital auto-confirm job) | first, after launch — unblocks seller and shipper money |
| **2 — attempts + office hold (F1, F2 unreachable)** | attempt button for riders, reschedule for buyers, 7-day hold, collect / redeliver | next |
| **3 — returns (F1 step 4, F2 refused, F3)** | reverse legs back to the seller, refunds minus costs, who-pays rules | with or after disputes |
| **4 — disputes (F4)** | the full draft in §15 | later |

## 16. To do after launch

- ⭐ Recommended uses reliability (delivery history).
- Real ETAs from recorded delivery times.
- Licence expiry / document renewal (KYC re-check).
- Coverage exclusions ("all Dar except Kigamboni").
- Shop front photo.
- **Paid packing by shippers** ("we pack for you") for sellers without boxes.
- Seller may drop a parcel at a door shipper's office (instead of being collected at the shop).
- **Seller drops at stations**: shop setting "I can drop parcels at stations for free" + the districts they will go to
  (area picker; the shop's own district pre-ticked) → a station route without the door leg.
- Shipper team members (dispatcher / rider roles, job assignment, rider shown to the buyer).
- Account deletion removes addresses.
- Location step 4 records recent pins at checkout-session creation — change to **after payment** when building (§4.4).
- New dedicated shipping notifications (after the shipping service).
- Staging / production: PostGIS, ward file (at deployment).

---

## 17. Worked scenarios

Illustrative numbers. Each scenario uses only rules decided above.

### A — Pickup, collected
Buyer in Sinza buys shoes from a shop in Ubungo, chooses **Pickup**.

| Step | Who | What happens | Money |
|---|---|---|---|
| 1 | Buyer | pays 60,000 | items escrow 60,000 HELD |
| 2 | Seller | accepts, then taps **Ready** | — |
| 3 | Buyer | told "ready at Ubungo, Gate B" (directions, phone); picks **"I'll come Thu 15:00"** (optional) | — |
| 3a | Seller | sees "Buyer coming Thu 15:00"; buyer reminded Thursday morning | — |
| 4 | Buyer + seller | buyer shows code **4821**, seller enters it → *collected* | — |
| 5 | Buyer | taps **"✓ It's what I ordered"** | items released to seller (minus fee) |

If the buyer never comes: reminders, then after **14 days** auto-cancel → 60,000 refunded, stock back.

| Instead | Who | What happens | Money |
|---|---|---|---|
| Day 2, buyer phones: "I can't come, cancel" | Seller | **Cancel** → pop-up "I have already informed the buyer" → confirm | 60,000 refunded, stock back |
| Before Ready, seller finds the shoes damaged, calls the buyer | Seller | same pop-up → confirm; fixes stock by hand | 60,000 refunded |

### B — Door-to-door, one shipper
Phone 400,000, shop in Kariakoo → buyer's Home in Mikocheni (~9 km).

| Step | Who | What happens | Money |
|---|---|---|---|
| 1 | Buyer | sheet shows quotation: 💰 Dar Cargo 7,000 · 1–2 h | — |
| 2 | Buyer | checkout → **agreement**; pays 407,000 | items 400,000 + leg 7,000 HELD |
| 3 | Seller | accepts (Dar Cargo gets a heads-up), packs, taps **Ready** | — |
| 4 | Dar Cargo | accepts the offer → receives pickup code | — |
| 5 | Seller | verifies the rider's pickup code, hands over → *picked up* | — |
| 6 | Buyer | told "on the way", receives delivery code **0937** | — |
| 7 | Rider | buyer tells the code, rider submits it → *delivered* | — |
| 8 | Buyer | opens, taps **"✓ It's what I ordered"** | items → seller, 7,000 → Dar Cargo (one transaction) |

### C — Multi-shipper, door in another region
Laptop 1,500,000, shop at Mlimani City (Dar) → buyer's door in Mbeya.

| Leg | Shipper | From → to | Cost | ETA |
|---|---|---|---|---|
| 1 | 🚪 Kibuti Express | shop → Shabiby office, Magufuli Terminal | 3,500 | 2–3 h |
| 2 | 🚌 Shabiby | Magufuli → Shabiby office, Mbeya Stand | 21,000 | 1 day |
| 3 | 🚪 Mbeya Riders | Mbeya Stand → buyer's door | 2,500 | 1–2 h |

| Step | What happens |
|---|---|
| Quotation | buyer edits: none — or "collect at Mbeya Stand" removes leg 3 (−2,500) |
| Ready | **all three legs get the offer at once**; parcel stays at the shop until **all** accept |
| Handovers | shop → Kibuti (pickup code) · Kibuti → Shabiby ("handed over" / "received" + code) · Shabiby → Mbeya Riders (same) · Mbeya Riders → buyer (delivery code) |
| Release | buyer taps "✓ It's what I ordered" → items + all 3 legs released together |

### D — Reassignment, nearby swap (automatic)
In C, Shabiby **rejects** ("full today").

| Step | Result |
|---|---|
| Search step 1 (1 km) | Abood: offices 300 m (Magufuli) and 500 m (Mbeya Stand) from Shabiby's · 20,000 · 1 day |
| Compare | cheaper, not slower → **automatic** |
| Money | leg-2 escrow re-pointed to Abood; **1,000 refunded** to the buyer |
| Others | Kibuti and Mbeya Riders keep their leg and price; get the new exact office ("Abood office, gate 5"), no re-confirm |
| Buyer | told "New courier for Dar → Mbeya: Abood, 1,000 refunded" |

### E — Reassignment, same district (re-confirm)
In C, no other bus company within 1 km at Magufuli; one leaves from **Ubungo Terminal** (same district).

| Step | Result |
|---|---|
| Search step 2 (district) | Kilimanjaro Express from Ubungo · 21,500 |
| Neighbours | Kibuti re-routed shop → Ubungo Terminal, re-costed 3,000 (shorter) |
| Compare | affected total 24,500 vs agreed 24,500 → same, not slower → **automatic** |
| Re-confirm | Kibuti had already accepted and its drop point moved > 1 km → **re-confirm** "drop at Ubungo Terminal instead, OK?" |
| If Kibuti says no | its leg is reassigned in turn (counts toward the **3 per order** guard) |

### F — Chain fails → buyer chooses
In C, nobody in the district can do leg 2 at the agreed price; best is 30,000 (+9,000).

| Buyer chooses | Result |
|---|---|
| Pay the difference | +9,000 from wallet into the leg-2 escrow; new shipper gets the offer |
| End the chain earlier | e.g. collect in Dar — later legs refunded |
| Pickup | all leg escrows refunded (27,000) |
| New delivery proposal | new quotation → new agreement |
| **Cancel the whole order** | full refund; stock back (allowed because the chain failed) |

### G — Switching
| Case | Allowed? | Money |
|---|---|---|
| Ordered **Pickup**, seller already Ready, buyer taps "Deliver it instead" | ✅ before collecting | fresh quotation; pays delivery cost; offer goes to the shipper **at once** |
| Ordered **Delivery**, no shipper accepted yet, buyer switches to pickup | ✅ | legs refunded |
| Ordered **Delivery**, shipper accepted, not heading to the shop yet | ✅ free | legs refunded |
| Ordered **Delivery**, shipper heading to the shop | ✅ with a fee | leg refunded minus the wasted-trip fee |
| Ordered **Delivery**, parcel picked up | ❌ | only a destination change (scenario O) |

### H — Cancelling
| When | Allowed? | Money |
|---|---|---|
| Before the seller accepts | ✅ whole order | full refund |
| Seller accepted, no shipper accepted | ✅ shipping only (pickup / new proposal) | legs refunded or adjusted |
| Shipper accepted, not heading to the shop | ✅ shipping only, free | legs refunded |
| Shipper heading to the shop | ✅ shipping only | Mbezi Boda leg 3,500 → buyer gets 1,750 back, Mbezi Boda gets 1,750 |
| Parcel picked up | ❌ shipping | only a destination change |
| Chain failed | ✅ shipping or the whole order | as chosen |

### I — Free shipping, stacked
Shoes 60,000, shop in Kinondoni → buyer in Kinondoni (~4 km). Shop: free delivery in Kinondoni, pays up to 4,000.
NexGate weekend campaign in Dar: pays up to 3,000.

| Option | Cost | Seller pays | NexGate pays | Buyer pays |
|---|---|---|---|---|
| 💰 Mbezi Boda (cheapest qualifying) | 3,500 | 3,500 | 0 | **0 (Free)** |
| ⚡ Express Riders (faster) | 5,000 | 3,500 | 0 | **1,500** (the difference — the discount is what the cheapest qualifying option costs) |
| a 9 km trip (other buyer) | 7,500 | 4,000 | 3,000 | **500** |

Shipper always paid the full cost: leg escrow = buyer share + NexGate share (campaign account, at payment) +
seller share (taken from the items escrow at release).

### J — Group purchase
| Case | Result |
|---|---|
| Member pays (delivery 3,500) | items + leg escrows HELD; price frozen even if the group fills days later |
| Group fails / member withdraws | items + 3,500 refunded |
| Payment moved to another group | fulfillment moves with it |
| Group fills, shipper rejects at Ready | normal reassignment (D–F) |

### K — Installments
| Mode | Delivery |
|---|---|
| Immediate (ships after down payment) | full delivery cost paid **with the down payment** |
| Layaway (ships after the last instalment) | pickup / delivery chosen and paid **after the last instalment** |
| Agreement cancelled before shipping | delivery cost refunded |

### L — Estimation on a card
Buyer's header address: Home, Kijitonyama. Product from a shop in Ubungo.

| Shippers covering | Card shows |
|---|---|
| Mbezi Boda 3,500 · 40–60 min, Dar Cargo 7,000 · 1–2 h | 🚚 3,500 – 7,000 · Kijitonyama |
| one shipper, 5,000 | 🚚 5,000 |
| free option + faster ones up to 2,000 | 🚚 Free – 2,000 |
| none | Pickup only at Ubungo |

### N — Bulky mismatch
Seller lists a 65" TV (value 1,800,000) **without** "bulky". Buyer chose 💰 Mbezi Boda 3,500.

| Step | What happens | Money |
|---|---|---|
| Rider arrives at the shop | taps "Can't carry — too big" + photo (before pickup) | — |
| Reassignment (bulky only) | Dar Cargo (car) 7,000 + bulky extra 15,000 = 22,000 | buyer pays nothing more |
| Seller pays | difference 22,000 − 3,500 = **18,500** + Mbezi Boda's wasted trip **1,750** (50%) | taken from the items escrow at release |
| Buyer told | "Too big for a boda — a car is coming, no extra cost to you" | — |
| Product flag | 1st mismatch → seller asked to tick bulky; if a 2nd shipper reports it on a later order → bulky set automatically | — |
| Mbezi Boda | reliability **not** affected | gets 1,750 |

### M — A shipper's day in the app (Mbezi Boda, owner only)

| Time | Screen | What the owner sees / does | Data visible |
|---|---|---|---|
| 08:05 | Upcoming | new card "Sinza → Mbezi · small · 3,500 — Waiting for the seller to accept" (buyer just paid) | areas only, size, value band, cost |
| 08:40 | Upcoming | chip changes to "Seller is packing" + heads-up push "order coming from Sinza in ~15 min" | areas only |
| 09:00 | Offers | seller tapped Ready → offer with a 30-min countdown | areas only, map of the two areas |
| 09:04 | Offers | taps **Accept** → job moves to Active; pickup code **4821** shown | **full details now**: shop Gate B + phone, buyer pin, directions "blue gate", receiver Mama Json +255712… |
| 09:20 | Active job | at the shop: tells code 4821, seller verifies → taps **Picked up** | — |
| 09:45 | Active job | at the door: buyer says **0937** → enters it → **Delivered** | — |
| 11:30 | Earnings | job shows 3,500 **held** (waiting for the buyer's "✓ It's what I ordered") | — |
| 12:10 | Earnings | buyer confirmed → 3,500 **released** to the wallet (commission 0%) | — |
| 14:00 | Offers | another offer, but busy → **Reject** "too busy" → reliability notes it; order is reassigned | — |

### O — Destination change (agreement change)
Buyer ordered shoes to home in Sinza with **Mbezi Boda 3,500**; at work in Mlimani City they change the destination.

| Case | Mbezi Boda answers | Result |
|---|---|---|
| Before pickup, new cost 4,500 | **Accept at the new cost** | buyer pays +1,000 into the leg escrow |
| Before pickup, new cost 4,500 | **Accept at the old price** | nothing to pay |
| Before pickup | **Decline** | leg reassigned: Kibuti Express 4,000 is dearer → buyer decides (pay +500 / keep Sinza / pickup) |
| Before pickup | no answer in 30 min | Sinza stays; the buyer is told |
| After pickup, new cost 2,500 | **Accept** | buyer gets 1,000 back |
| After pickup | **Decline** | Sinza stays — the rider keeps the parcel and delivers as agreed |
| Delivered | — | not allowed |

### P — Cancelling the shipping (signed shipper)
Same order, Mbezi Boda signed (accepted) at 09:04.

| When the buyer cancels the shipping | Fee | Money |
|---|---|---|
| 09:10 — accepted, not set out | none (like Bolt) | 3,500 refunded; Mbezi Boda released, reliability unaffected |
| 09:15 — Mbezi Boda tapped **Heading to the shop** | wasted trip 50% | 1,750 refunded to the buyer, 1,750 to Mbezi Boda |
| 09:20 — picked up | — | not allowed; destination change only |

# # NexGate Shipping Service — Build Plan Development

How we build `docs/shipping/SHIPPING_SERVICE_DESIGN.md` (the "design", § numbers below point to it).
Status: **plan agreed to start, nothing built yet.** Built on the Location Service (done: wards, shop locations,
user addresses, frozen places).

## Ground rules for every step

- **Talk first, then build** — each step starts with a short talk on its details, then code.
- **Code standard**: new top-level package `shipping_service/` (same level as `location_service/`), the project's
  controller / service / service/impl / payload / entity / repo shape, no boilerplate, comments only where needed.
- **Existing responses**: add fields; reshape only when agreed (dev phase) and always recorded.
- **Every change recorded** in `commerce_logistics_changes.md` — before / after, examples, app to-do.
- **Design doc kept true** — any decision that changes during a step is updated in the design.
- **Settings**: fixed rules in properties (`shipping.*`), per-shipper agreement settings in the database (§6.7.1).
- **Money**: every money move goes through the ledger; every step that moves money ends with the ledger balance check.
- **Tested live** locally after each step (like the location steps), using the worked scenarios (§17) as test cases.
- **Phase-0 hooks** (§15b) are built in from the start: attempt records, failure reason codes, the extra statuses,
  timers as data, reverse legs allowed — even though their rules come later.

## The order at a glance

| Step | Delivers | Real-world result after the step |
|---|---|---|
| **0** | Foundations | nothing visible; ground ready |
| **1** | Pickup, end to end (with codes and "✓ It's what I ordered") | **buyers can buy and collect at the shop** |
| **2** | Native shipper registration (KYC + Service Setup basics) | delivery businesses can sign up |
| **3** | Door coverage, pricing, ETA | businesses describe where / how much |
| **4** | Engine: estimation + quotation (single door leg) | buyers see real delivery costs |
| **5** | Cart / checkout / agreement, escrow per part | **buyers pay real delivery** |
| **6** | Job flow: offers, codes, statuses, release | **first real door-to-door deliveries** |
| **7** | Reassignment, switching, cancelling, bulky mismatch | unhappy-but-common cases handled |
| **8** | Reliability, reviews, auto-pause, upcoming orders | trust and planning |
| **9** | Stations (single leg) | intercity: collect at a station |
| **10** | Multi-shipper chains | shop → bus → door |
| **11** | Group purchase and installments | shipping inside group / installment buys |
| **12** | Free shipping (seller rules + campaigns) | "Free delivery" badges and filter |
| **13** | Bolt integration | boda on demand in town |
| **14** | Admin dashboard (screens) | ops tooling — **last** |
| later | Notifications set · unhappy paths (§15a/b) · staging deploy | after the build |

---

## Step 0 — Foundations
**Goal:** everything later steps stand on, with no behaviour change.

- Package `shipping_service/` with sub-packages from §2 (empty shells added as each step needs them).
- `shipping.*` properties with every value from §6.7.1 (read through one settings class).
- **Shared opening hours** (§6.3): weekly ranges, special days, temporarily closed, cut-off, EAT, overnight;
  "is open at", "next opening", "add opening hours" helpers. Attached to **shops** now (§6.4): shop hours endpoints,
  "Open now / Opens Sat 09:00" on shop responses; shop **pause modes** (keep selling / stop orders, `SHOP_CLOSED`).
- **Escrow table**: `part` (ITEMS / LEG), `legId`, `orderId` filled, **provider payee** (§12.1) — new columns only,
  current payments keep working (they are "ITEMS" parts).
- **Product `bulky`** field (§8.1) — default false; category pre-tick later.
- **File Thunder**: new upload types *business document* (private) and *business logo* (separate repo, small).
- **Codes service**: 4 random digits, hashed, never logged, 5 tries → locked, regenerate (§11). Replaces the old
  `DeliveryConfirmation` code generator (and its plain-code log line).

**Check:** existing checkout / orders / cart-escrow tests still pass; shop hours + pause visible; a code can be
generated, verified, locked after 5 wrong tries, and never appears in logs.

## Step 1 — Pickup, end to end
**Goal:** a buyer can buy, the seller prepares, the buyer collects with a code, money is released on confirmation.

- Move Step-4 `e_commerce/fulfillment` (JSON) into `shipping_service/fulfillment` as a **table**; orders link to it
  (§2, §3.5). Frozen places stay inside the record.
- **Shipping agreement entity** (§4.8): `shipping_agreement` + parties + changes; states DRAFT → PENDING → AGREED →
  DONE / CANCELLED. For pickup the only parties are the buyer and the seller. **Escrow parts move only on agreement
  events** from here on.
- Order flow: seller **accepts** (24 opening hours, else auto-cancel + refund) → **Ready** → buyer told → **pickup at
  the counter**: buyer's code, seller enters it → *collected* (§3.1, §10).
- **"✓ It's what I ordered"** releases **all** escrow parts in one transaction; **"⚠ Report a problem"** freezes them (§12.2).
- Account setting: **code or "received" button** (§11).
- Pickup statuses `placed → accepted → ready → collected → completed` (+ cancelled / expired); optional **pickup
  time** (shop opening hours, inside the window; reminder that morning).
- **14-day collection** expiry with reminders (§3.1). **Cancel before the seller accepts** (§3.4a). **Seller cancel** at once
  (pop-up "I have already informed the buyer"; pickup before collected, delivery before Ready).
- Recent pins recorded **after payment**, not at checkout (§4.4).
- Admin endpoints needed from now: manual **release / refund** of an escrow part (§6.7.2) — `SUPER_ADMIN`, reason, audit log.

**Check:** scenario **A** (§17) live: pay → accept → ready → code → collected → confirm → seller paid; 14-day expiry; seller cancel
refunds; cancel before accept refunds; problem report freezes; admin release works and is logged.

## Step 2 — Native shipper registration
**Goal:** a delivery business can sign up and get approved automatically.

- **KYC** (§6.2 part 1): name, contact phone, **office location** (pin), business licence (file + number + expiry,
  unique number), director's NIDA (file + number), LATRA (file + number + expiry) → auto-approved `KYC_APPROVED`.
- **Service Setup basics** (§6.2 part 2): profile (logo, description, WhatsApp, email, badge), service type
  (door / station), **hours** (shared piece, default Mon–Sat 08:00–18:00), limits (max value, bulky + extra,
  response window, heads-up). Setup checklist endpoint.
- Statuses `KYC_APPROVED → LIVE ⇄ PAUSED`, `SUSPENDED`; documents private (owner + admin).
- "Delivery business" mode in the app (owner only, §6.6) — endpoints for the owner's own business.
- Admin endpoints: **suspend / lift** (§6.7.2).

**Check:** register with all documents → auto-approved; duplicate licence number refused; documents not visible to
others; checklist shows what's missing; suspend / lift logged.

## Step 3 — Door coverage, pricing, ETA
**Goal:** a business says where it works, how much, how long — and goes LIVE.

- **Location helpers** (in `location_service`): regions → districts → wards lists + search; coverage outline for the map.
- **Coverage** (§7.1): ticked areas (region / district / ward), trips `WITHIN_EACH` / `WITHIN_AND_ACROSS`,
  "both ends inside", fast **area-code matching** (the spec's second core function, `areaMatch`).
- **Pricing** (§8.1): distance bands (price + time each, ×1.3, last band = max distance), flat, value add-on ladder
  + max value, bulky extra, rounding up to 100.
- Goes **LIVE automatically** when service type + coverage + pricing exist.
- Delivery commission fee type (0%) in the fee table + per-shipper override with start date (§6.7.1).

**Check:** the §7.1 crossing table (Sinza → Mikocheni with WITHIN_EACH vs ACROSS…) as tests; band and add-on maths
incl. rounding; business flips to LIVE when complete.

## Step 4 — Engine: estimation + quotation (single door leg)
**Goal:** buyers see real delivery options and costs.

- Engine (§9): where → who (coverage) → filter (distance, value, bulky, hours / cut-off, paused) → cost + ETA →
  clean-up (dominated, outliers 3×) → labels 💰 ⚡ ⭐ (⭐ = price + time at launch) → order, top 5, fairness.
- **ETA** (§8.2): from "shop ready", ranges, closed hours.
- **Estimation** `POST /api/v1/shipping/estimations` (§4.5): `cost {from,to}`, `eta {from,to}`, pickup area;
  Redis cache shop-area → buyer-area (1 h).
- **Quotation** (§4.1): live options for a shop's parcel and a destination (§4.2: saved / recent / pin; station
  recognition comes with step 9).
- Product detail: live quotation for the viewer's address.

**Check:** scenario **L** (cards) and the engine walk-throughs from the master guide (A, B, E) reproduce; cache hit
on the second call; closed shipper shifts ETA instead of disappearing.

## Step 5 — Cart, checkout, agreement, escrow per part
**Goal:** buyers pay the real delivery cost; money split into items + leg.

- Cart (§4.3, §4.4): one destination per cart, per-shop quotation **held 5 days**, add-to-cart `fulfillment` +
  `dropoff`, defaults for a new shop, unsaved pin on the cart, re-quote on changes.
- Checkout → **agreement** (§4.1, §4.8) with its **legs** (each leg escrow part points to one): editable on the checkout screen until paid (re-quote, wallet re-check), **locked
  once paid**. Buy-now uses the sheet's quotation.
- **Escrow per part** (§12.1): items part → seller, leg part → shipper owner; release all on confirm.
- **Seller fee on items + tax only**; delivery commission from the leg (§8.3).
- `shippingByShop` now real costs (replaces the 0 placeholder).
- What the app keeps vs the server (§4.6) honoured.

**Check:** scenario **B** up to payment: escrows created per part with the right payees and fees; quotation older
than 5 days refreshed; edit at checkout re-quotes; ledger balance check passes.

## Step 6 — Job flow, codes, delivery
**Goal:** the first real door-to-door delivery from offer to release.

- Seller accepts → **heads-up**; **Ready** → **offer** with response window (counted while open), **closed-shipper
  4 h rule** (§10).
- **Ready pop-up**: "I have packed it well" + "label / number is on the package" (recorded).
- **Parcel number** created when the seller accepts (QR label generated by the app, or written on the box); scanned / typed at pickup → "✓ yours / ✗ wrong parcel";
  shippers see the parcel, never the order (§11, §6.6).
- Shipper: accept / reject (reason), timeout; active job steps; **pickup code** (seller verifies) and **delivery
  code** (shipper submits) or the buyer's button (§11); optional handover photos.
- Shipper accept = **signs the agreement**; all signed → AGREED, parcel moves (§4.8).
- Statuses door ladder (§3.2) incl. **heading to the shop** + phase-0 statuses.
- Release on "✓ It's what I ordered": items → seller, leg → shipper (one transaction).
- Shipper app endpoints for offers / jobs / earnings (§6.6), live push.

**Check:** scenario **B** end to end; scenario **M** (a shipper's day) step by step; timeout counted; codes locked
after 5 tries.

## Step 7 — Reassignment, switching, cancelling, bulky mismatch
**Goal:** the common unhappy-but-normal cases.

- **Reassignment** (§10a): rejection / timeout → that leg only; tiers **1 km → same district → buyer**; same-or-cheaper
  and not slower = automatic (escrow re-pointed, difference refunded); dearer / none → buyer decides; **loop guard
  3 per order**; **buyer silent 24 h → pickup**; **chain safety net 24 h**; free-shipping caps recalculated; history kept.
- **Switching** (§3.4): pickup → delivery (fresh quotation, pay, offer at once if Ready); delivery → pickup (before any
  shipper accepted, refund).
- **Cancelling** (§3.4a): shipping-only until pickup — free before **heading to the shop**, wasted-trip fee (50% / Bolt's
  charge) after; whole order when the chain failed.
- **Agreement changes** (§4.8): propose → affected parties approve → default on silence; **destination change**
  (accept new cost / keep old price / decline; no withdraw after pickup).
- **Bulky mismatch** (§8.4): report before pickup, bulky-only reassignment, seller pays difference + 50% wasted trip,
  auto-flag after 2.
- **Badly packed** refusal (§8.5): before pickup, photo, seller repacks + Ready again, seller pays 50% wasted trip.
- Admin endpoints: force **reassign / cancel** (§6.7.2).

**Check:** scenarios **D, F, G, H, N, O, P**; loop guard; silent buyer → pickup after 24 h; ledger balanced after every
adjustment.

## Step 8 — Reliability, reviews, auto-pause, upcoming orders
- **Reliability counters** (acceptance, on time, failed, broke binding) and **auto-pause** levels with the §14 table,
  grace period 10 offers, reasons shown.
- **Reviews** like shops, verified only, owner replies, moderation (§14); shown in quotations.
- **Two-way private ratings** (shipper rates buyer / seller).
- **Upcoming orders** on the shipper dashboard, area-only until accepted (§6.6).
- Real delivery times recorded (for after-launch ETA).

**Check:** the §14 trigger table as tests (2 / 3 missed, 3rd pause in 7 days → suspended…); new shipper not paused
inside the grace period; upcoming card hides the exact pin until accepted.

## Step 9 — Stations (reached by a door leg)
- Stations (§7.2): pins with counter name, phone, hours; ≥ 1 per ticked area; **lines**; **reach 30 km**
  (per business override).
- **Station-pair table** (price + time, both ways, pre-filled pairs) (§8.1).
- Handover points (§7.2a): leg 1 always starts with a collection at the shop (option A) — either the station
  business **collects from shops** (areas + flat fee, 0 = free; one leg) or a door shipper brings it to the station
  (the **two-leg chain** door → station, built here); buyer collects at the destination station (station staff enter the
  buyer's code). Step 10 extends it to 3 legs, editing and re-confirms.
- Station ladder (§3.3); quotation **meeting-point recognition** ("collect at Mbeya Bus Stand", §4.2).

**Check:** a Mbeya → Morogoro trip as boda → bus (two legs) and as a bus company collecting free (one leg, ranked
cheapest); no door shipper at the shop → no station route; pin within 1 km of a station
offers "collect there"; empty pair = not offered.

## Step 10 — Multi-shipper chains
- Chain building (§4.7): up to 3 legs, meeting points within 1 km, always next to single-leg options.
- Quotation editing per leg: stop early, swap a leg's shipper, change a meeting point.
- **All legs offered at Ready, nothing moves until all accept**; **binding after accept**; **re-confirm** when an
  accepted leg's time moves > 4 h (§10a 7a).
- Shipper → shipper handover: "handed over" / "received" + that handover's code, optional photo (§11).
- One escrow part **per leg**; release all together (§12).

**Check:** scenarios **C, D, E** with three legs; one leg rejecting while others accepted; re-confirm triggered by a
> 4 h move.

## Step 11 — Group purchase and installments
- Group (§5): each member's own fulfillment and fee with their payment; refunds on fail / withdraw; moves with a
  transferred payment; price frozen at payment.
- Installments (§5): immediate = fee with the down payment; layaway = choose and pay after the last instalment
  (reuses switch-to-delivery).

**Check:** scenarios **J** and **K**.

## Step 12 — Free shipping
- Seller rules (areas, minimum, cap, product override) and NexGate campaigns (areas, dates, cap, audience, shops,
  budget reserved at payment, auto-stop) (§13).
- Stacking, the cheapest qualifying option free, faster pays the difference; campaign ledger account; seller share
  from the items part at release.
- Estimation `freeDelivery` + card badge + "Free delivery to my area" search filter.

**Check:** scenario **I**; campaign budget never overspent under parallel checkouts; refund returns budget.

## Step 13 — Bolt integration
- Adapter (§6.5): OAuth2 token cache, estimations (boda, non-bulky, in-city), book at Ready (re-estimate, held price
  = max + 2%), cancel, webhooks (3 IPs + token) and polling fallback, state mapping, tracking link + driver details.
- **Bolt ledger account**, monthly settlement record, receipt differences; **kill-switch** and **daily spend limit**
  (§6.7); seller pays a shop no-show.
- Built and tested in Bolt's **sandbox** first.

**Check:** sandbox flow (estimate → create → states → completed → receipt); NO_DRIVER_FOUND → reassignment; spend
limit blocks new Bolt quotations; kill-switch hides Bolt immediately.

## Step 14 — Admin dashboard (last)
Screens on top of the existing admin endpoints (§6.7.3): shippers + KYC documents, Bolt status and settlement,
operations board, campaigns, reports (by area), audit log, `STAFF_ADMIN` / `SUPER_ADMIN` split.

## After the build
- **New dedicated shipping notifications** (one set, after the shipping service).
- **Unhappy paths** (§15a / §15b): auto-confirm window, delivery attempts + office hold, returns, disputes.
- **Staging / production**: PostGIS image + `CREATE EXTENSION`, ward file, settings — at deployment.
- After-launch items (§16).

## Dependencies

```
0 ─► 1 ─► 2 ─► 3 ─► 4 ─► 5 ─► 6 ─► 7 ─► 8
                         │         ├─► 9 ─► 10
                         │         ├─► 11
                         │         ├─► 12
                         │         └─► 13
                         └─────────────────────► 14 (last)
```
Steps 9, 11, 12, 13 can be reordered after step 6 (each only needs the single-leg flow). 10 needs 9.

# Location Service API

**Author**: Josh S. Sakweli, Backend Lead Team **Last Updated**: 2026-10-24 **Version**: v1.0

**Base URL**: `https://api.nexgate.co/api/v1`

**Short Description**: The location service turns map pins into Tanzanian places (ward, district, region), keeps every shop's location and every user's saved addresses, and hands checkout and shipping a frozen copy of a place. Everything in shipping — who can deliver, at what price, which campaign applies — starts from what this service knows about a place.

**Hints**:

- **Pins only.** Nobody types a street, city or region. The app sends `lat` / `lng`; the backend works out the ward. Show our `areaLabel` once a pin is confirmed (Google's text is only for the live map).
- **Places are frozen on orders.** Editing or deleting a saved address or moving a shop never changes an order already placed — the order keeps its own copy (a *place snapshot*, §1.5).
- All endpoints need a logged-in user, except reading a shop's location.
- Coded refusals come back as HTTP **409** with `data.code` (and sometimes `data.details`) — switch on the code, not the message.

---

## Standard Response Format

### Success

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Location resolved",
  "action_time": "2026-10-24T10:30:45",
  "data": { }
}

```

### Error (coded refusal)

```json
{
  "success": false,
  "httpStatus": "CONFLICT",
  "message": "You can save up to 10 addresses",
  "action_time": "2026-10-24T10:30:45",
  "data": { "code": "ADDRESS_LIMIT_REACHED", "reason": "You can save up to 10 addresses" }
}

```

Some refusals add `data.details` (e.g. `NEAR_DUPLICATE` returns the address it collides with).

<table id="bkmrk-field-type-descripti"><thead><tr><th>Field</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>`success`</td><td>boolean</td><td>`true` for success, `false` for errors</td></tr><tr><td>`httpStatus`</td><td>string</td><td>HTTP status name</td></tr><tr><td>`message`</td><td>string</td><td>Human-readable result, safe to show</td></tr><tr><td>`action_time`</td><td>string</td><td>When the response was made</td></tr><tr><td>`data`</td><td>object/string</td><td>Payload, or error details</td></tr></tbody></table>

---

## HTTP Method Badge Standards

- **GET** - <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> - read only
- **POST** - <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> - create / act
- **PUT** - <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> - replace
- **DELETE** - <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> - remove

---

# Part 1 — How the location service works

## 1.1 The map of Tanzania inside the backend

The backend holds the official **NBS 2022 ward boundaries**: about 4,300 wards, each inside a **district**, each district inside a **region**.

```
Region (e.g. 07 Dar es Salaam)
 └─ District (07-01 Kinondoni)      ← a district is regionCode + districtCode: district codes repeat across regions
     └─ Ward (1131 Kijitonyama)     ← the smallest area; every pin lands in exactly one

```

The ward data is a file loaded by the backend at start-up (only when the file changes). If it is not loaded yet, calls that need it answer `WARD_DATA_UNAVAILABLE`.

## 1.2 A pin becomes a place — "resolve"

```
 App map stops moving ──► GET /locations/resolve?lat&lng ──► covered?
                                                            ├─ yes: ward + district + region + areaLabel
                                                            └─ no:  covered:false (sea, lake, outside Tanzania)

```

- **CONTAINED** — the pin is inside a ward.
- **NEAREST** — the pin is just outside every ward (a beach, a river bank, a border line) but within **500 m** of one: that ward is used and `distanceM` says how far.
- Further than that → `covered: false`. The app disables *Confirm* and says "We don't deliver here yet".

Resolve stores nothing; it is safe to call on every map stop (debounce ~400 ms).

## 1.3 Areas — the picker for coverage and campaigns

Shippers tick **where they work** and campaigns choose **where they apply** with an *area*: a whole region, a district, or a single ward. The area endpoints give the lists (regions → districts → wards) and a search box (`/areas/search?q=sin` → "Sinza, Ubungo, Dar es Salaam"). An area is always one of:

<table id="bkmrk-level-identified-by-"><thead><tr><th>level</th><th>identified by</th></tr></thead><tbody><tr><td>`REGION`</td><td>`regionCode`</td></tr><tr><td>`DISTRICT`</td><td>`regionCode` + `districtCode`</td></tr><tr><td>`WARD`</td><td>`wardId`</td></tr></tbody></table>

## 1.4 Two kinds of places people own

<table id="bkmrk-shop-location-saved-"><thead><tr><th></th><th>Shop location</th><th>Saved address</th></tr></thead><tbody><tr><td>Who</td><td>the shop (owner sets it)</td><td>any user (buyer, seller, anyone)</td></tr><tr><td>How many</td><td>exactly one per shop</td><td>up to 10 per user, plus up to 5 recent pins</td></tr><tr><td>Who can see it</td><td>**public** — buyers need to find the shop</td><td>**private** — only the owner</td></tr><tr><td>Used for</td><td>pickup point, where riders collect, product page "Directions"</td><td>where to deliver</td></tr><tr><td>Extra</td><td>landmark, building, official address, the shop's phone</td><td>label (Home / Work / named), directions</td></tr></tbody></table>

**Recent pins:** when an order is delivered to a new pin that the buyer did not save, the pin becomes a *recent*(up to 5, kept 60 days; a pin within 50 m of an existing recent just refreshes it). A recent can later be saved as an address.

## 1.5 Place snapshots — frozen copies on orders

Every order, quotation and shipping leg keeps its own copy of the places it uses:

```json
{
  "source": "SAVED_ADDRESS",              // SHOP_LOCATION | SAVED_ADDRESS | RECENT | NEW_PIN | STATION
  "sourceId": "9b1d…",                    // the address / recent / shop / station it came from
  "label": "Home",
  "lat": -6.7735, "lng": 39.2187,
  "ward": { "wardId": 1131, "wardName": "Kijitonyama", "districtCode": "01", "districtName": "Kinondoni",
            "regionCode": "07", "regionName": "Dar es Salaam", "nbsCode": "070113062", "councilName": "…" },
  "areaLabel": "Kijitonyama, Kinondoni, Dar es Salaam",
  "directions": "Black gate, blue house",
  "building": null,                       // shops only
  "phone": "+255744742944",               // shops and stations only
  "capturedAt": "2026-10-24T10:30:45"
}

```

Because of this, editing or deleting an address, or moving a shop, **never changes an order already placed**.

## 1.6 Choosing where to deliver — the drop-off request

Checkout, the cart and shipping all accept the same small object to say *where*:

```json
{ "addressId": "…" }                          // a saved address
{ "recentId": "…" }                           // a recent pin
{ "lat": -6.7735, "lng": 39.2187,             // a new pin
  "directions": "Opposite the petrol station",
  "saveAs": "OTHER", "customLabel": "Office" } // optional: also save it to the address book

```

Give **exactly one** of `addressId`, `recentId` or `lat`+`lng` → otherwise `DROPOFF_INVALID`; none at all where one is needed → `DROPOFF_REQUIRED`. Who receives the parcel and the note for the rider belong to the **order**, not to the place.

## 1.7 Event venues

An in-person or hybrid event has one venue: name, optional typed address, and a **pin**. The pin is resolved like a shop's (`OUTSIDE_COVERAGE` when not covered) and the event's `venue` shows `ward`, `areaLabel` and `matchType`. A pin is required to publish (or reveal the location of) an in-person / hybrid event. The venue is part of the event (no separate endpoint): set it with `PATCH /e-events/drafts/{draftId}/location` or `PATCH /e-events/{eventId}/published/reveal-location`.

## 1.8 How shipping uses all this

- **Who can deliver:** a shipper covers a trip only when both the shop's ward and the buyer's ward are inside its ticked areas.
- **Price:** road distance = straight line between the two pins × 1.3.
- **Campaigns:** "free delivery in Dar" means the buyer's ward is in region 07.
- **Reports** are by region / district / ward, never per person.

---

# Part 2 — Endpoints

## Pins and areas

## 1. Resolve a pin

**Purpose**: Turn a map pin into ward / district / region, or say it is not covered.

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/locations/resolve`

**Access Level**: 🔒 Protected (any logged-in user)

**Authentication**: Bearer token

**Query Parameters**:

<table id="bkmrk-parameter-type-requi"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th><th>Default</th></tr></thead><tbody><tr><td>lat</td><td>number</td><td>Yes</td><td>Latitude of the pin</td><td>-90 … 90, not 0,0</td><td>—</td></tr><tr><td>lng</td><td>number</td><td>Yes</td><td>Longitude of the pin</td><td>-180 … 180</td><td>—</td></tr></tbody></table>

**Success Response JSON Sample** (covered):

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Location resolved",
  "action_time": "2026-10-24T10:30:45",
  "data": {
    "covered": true,
    "latitude": -6.819, "longitude": 39.2768,
    "matchType": "CONTAINED",
    "distanceM": 0,
    "ward": {
      "wardId": 1146, "nbsCode": "070214112", "wardName": "Kariakoo",
      "districtCode": "02", "districtName": "Ilala",
      "councilName": "Halmashauri ya Jiji la Dar es Salaam",
      "regionCode": "07", "regionName": "Dar es Salaam"
    },
    "areaLabel": "Kariakoo, Ilala, Dar es Salaam"
  }
}

```

Not covered (sea, lake, outside Tanzania): `data` = `{ "covered": false, "latitude": -6.8, "longitude": 39.4, "reason": "OUTSIDE_COVERAGE" }`.

**Success Response Fields**:

<table id="bkmrk-field-description-co"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`covered`</td><td>`false` = no ward within 500 m: disable *Confirm*</td></tr><tr><td>`matchType`</td><td>`CONTAINED` inside a ward, `NEAREST` just outside one (≤ 500 m)</td></tr><tr><td>`distanceM`</td><td>metres to the ward when `NEAREST`</td></tr><tr><td>`ward`</td><td>the ward with its district and region</td></tr><tr><td>`areaLabel`</td><td>the name to show: "Ward, District, Region"</td></tr><tr><td>`reason`</td><td>only when not covered</td></tr></tbody></table>

**Errors**: `INVALID_COORDINATES`, `WARD_DATA_UNAVAILABLE`.

---

## 2. List regions

**Purpose**: First level of the area picker.

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/locations/regions`

**Access Level**: 🔒 Protected

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Regions", "action_time": "2026-10-24T10:30:45",
  "data": [
    { "regionCode": "07", "regionName": "Dar es Salaam", "districtCount": 5, "wardCount": 102 },
    { "regionCode": "12", "regionName": "Mbeya", "districtCount": 7, "wardCount": 199 }
  ]
}

```

---

## 3. List a region's districts

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/locations/regions/{regionCode}/districts`

**Access Level**: 🔒 Protected

**Path Parameters**:

<table id="bkmrk-parameter-type-requi-1"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>regionCode</td><td>string</td><td>Yes</td><td>e.g. `07`</td></tr></tbody></table>

**Success Response** `data`: `[{ "regionCode": "07", "regionName": "Dar es Salaam", "districtCode": "01", "districtName": "Kinondoni", "wardCount": 20 }]`

---

## 4. List a district's wards

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/locations/regions/{regionCode}/districts/{districtCode}/wards`

**Access Level**: 🔒 Protected

**Success Response** `data`: a list of ward objects, the same shape as `ward` in [Resolve](#1-resolve-a-pin).

---

## 5. Search areas

**Purpose**: Type-ahead for the area picker ("sin" → Sinza).

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/locations/areas/search?q=sin`

**Access Level**: 🔒 Protected

**Query Parameters**:

<table id="bkmrk-parameter-type-requi-2"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>q</td><td>string</td><td>Yes</td><td>Part of a region, district or ward name</td><td>at least 2 letters</td></tr></tbody></table>

**Success Response** `data` (up to 20, regions first, prefix matches first):

```json
[
  { "level": "WARD", "regionCode": "07", "districtCode": "04", "wardId": 1212, "name": "Sinza", "label": "Sinza, Ubungo, Dar es Salaam" }
]

```

The returned item is exactly what coverage and campaigns accept as an area (`level` + codes).

**Errors**: `SEARCH_TOO_SHORT`.

---

## Shop location

## 6. Set or replace the shop location

**Purpose**: The shop owner pins the shop. Used for pickups, riders and the product page.

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

**Access Level**: 🔒 Protected (shop owner, or platform admin)

**Request JSON Sample**:

```json
{
  "lat": -6.8190, "lng": 39.2768,
  "landmark": "Kariakoo market, opposite the clock tower",
  "building": "Shop 12",
  "officialAddress": null,
  "deviceLat": -6.7700, "deviceLng": 39.2400
}

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi-3"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>lat / lng</td><td>number</td><td>Yes</td><td>The pin</td><td>must be inside a ward (or ≤ 500 m)</td></tr><tr><td>landmark</td><td>string</td><td>Yes</td><td>How to find the shop</td><td>max 300</td></tr><tr><td>building</td><td>string</td><td>No</td><td>Building / shop number</td><td>max 100</td></tr><tr><td>officialAddress</td><td>string</td><td>No</td><td>Anwani za Makazi</td><td>max 100</td></tr><tr><td>deviceLat / deviceLng</td><td>number</td><td>No</td><td>The phone's own position, only to warn when the pin is far</td><td>—</td></tr></tbody></table>

**Success Response** (message "Shop location saved"): the shop location (as in [Get](#7-get-a-shop-location)), plus `warnings` when the pin is more than 1 km from the phone: `"warnings": [{ "code": "FAR_FROM_DEVICE", "distanceM": 6797 }]` → ask "Your pin is 6.8 km from where you are. Is this your shop?" It is saved either way.

**Rules**: one location per shop; editing = the same `PUT` with the whole location; the ward is always worked out from the pin. Orders already placed keep their pickup place. Buyers are not notified when a shop moves.

**Errors**: `OUTSIDE_COVERAGE`, `INVALID_COORDINATES`, 403 "Only the shop owner can set the shop location".

---

## 7. Get a shop location

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/e-commerce/shops/{shopId}/location`

**Access Level**: 🌐 Public (no login)

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Shop location retrieved", "action_time": "2026-10-24T10:30:45",
  "data": {
    "shopId": "aaaa0000-0000-4000-8000-000000000001",
    "lat": -6.819, "lng": 39.2768,
    "ward": { "wardId": 1146, "wardName": "Kariakoo", "districtName": "Ilala", "regionName": "Dar es Salaam" },
    "matchType": "CONTAINED",
    "areaLabel": "Kariakoo, Ilala, Dar es Salaam",
    "landmark": "Kariakoo market, opposite the clock tower",
    "building": "Shop 12",
    "phone": "+255744742944",
    "officialAddress": null,
    "updatedAt": "2026-10-12T11:49:59"
  }
}

```

`phone` is the shop's own phone (one phone per shop). **App:** "Directions" opens maps with `lat,lng`; "Call" uses `phone`. 404 when the shop has no location yet. A shop without a location cannot sell physical products: checkout answers `SHOP_LOCATION_REQUIRED`.

---

## Saved addresses and recent pins

## 8. My addresses

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/locations/addresses`

**Access Level**: 🔒 Protected (own addresses only)

**Success Response** `data`: default first, then most recently used:

```json
[
  {
    "id": "9b1d…", "labelType": "HOME", "customLabel": null,
    "lat": -6.7745, "lng": 39.2419,
    "ward": { "wardName": "Kijitonyama", "districtName": "Kinondoni", "regionName": "Dar es Salaam" },
    "matchType": "CONTAINED", "areaLabel": "Kijitonyama, Kinondoni, Dar es Salaam",
    "directions": "Black gate, blue house",
    "isDefault": true, "lastUsedAt": "2026-10-20T09:00:00", "createdAt": "…", "updatedAt": "…"
  }
]

```

---

## 9. Save an address

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/locations/addresses`

**Access Level**: 🔒 Protected

**Request JSON Sample**:

```json
{
  "lat": -6.7745, "lng": 39.2419,
  "labelType": "OTHER",
  "customLabel": "Mama's place",
  "directions": "Black gate, blue house",
  "makeDefault": false,
  "allowNearDuplicate": false
}

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi-4"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>lat / lng</td><td>number</td><td>Yes</td><td>The pin</td><td>inside a ward</td></tr><tr><td>labelType</td><td>enum</td><td>Yes</td><td>`HOME`, `WORK`, `OTHER`</td><td>HOME / WORK once each</td></tr><tr><td>customLabel</td><td>string</td><td>for OTHER</td><td>The name for an OTHER address</td><td>max 40</td></tr><tr><td>directions</td><td>string</td><td>No</td><td>How to find the place</td><td>max 300</td></tr><tr><td>makeDefault</td><td>boolean</td><td>No</td><td>Make it the default</td><td>—</td></tr><tr><td>allowNearDuplicate</td><td>boolean</td><td>No</td><td>Save even if within 50 m of another address</td><td>—</td></tr></tbody></table>

**Success Response**: the saved address (shape as in [My addresses](#8-my-addresses)).

**Rules**:

- Up to **10** addresses. The **first** one saved becomes the default; deleting the default leaves none (the app pre-selects the most recently used).
- Within **50 m** of another saved address → `NEAR_DUPLICATE` with that address in `data.details`. Ask "This looks like 🏠 Home. Use it?"; to save anyway send again with `allowNearDuplicate: true`.

**Errors**: `ADDRESS_LIMIT_REACHED`, `LABEL_ALREADY_USED`, `CUSTOM_LABEL_REQUIRED`, `NEAR_DUPLICATE`, `OUTSIDE_COVERAGE`.

---

## 10. Edit an address

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

**Access Level**: 🔒 Protected (own address)

Same body and rules as [Save](#9-save-an-address) — send the whole address. Orders already placed are not affected.

---

## 11. Delete an address

**Endpoint**: <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `{base_url}/locations/addresses/{addressId}`

**Access Level**: 🔒 Protected (own address)

---

## 12. Make an address the default

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/locations/addresses/{addressId}/default`

**Access Level**: 🔒 Protected (own address)

**Success Response**: the address, now `isDefault: true` (the old default is cleared).

---

## 13. My recent pins

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/locations/recent`

**Access Level**: 🔒 Protected

**Success Response** `data`: `[{ "id": "…", "lat": -6.7735, "lng": 39.2187, "ward": {…}, "matchType": "CONTAINED", "areaLabel": "…", "lastUsedAt": "…" }]`— up to 5, newest first. Added by checkout when an order is delivered to a new, unsaved pin.

---

## 14. Remove a recent pin / clear all

**Endpoints**:

- <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `{base_url}/locations/recent/{recentId}`
- <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `{base_url}/locations/recent`

**Access Level**: 🔒 Protected

---

# Part 3 — Codes and values

## Error codes (HTTP 409, `data.code`)

<table id="bkmrk-code-when-invalid_co"><thead><tr><th>Code</th><th>When</th></tr></thead><tbody><tr><td>`INVALID_COORDINATES`</td><td>lat/lng out of range, or 0,0</td></tr><tr><td>`OUTSIDE_COVERAGE`</td><td>saving a shop location or address whose pin is not in Tanzania's wards (resolve answers `covered:false` instead)</td></tr><tr><td>`WARD_DATA_UNAVAILABLE`</td><td>the ward data is not loaded on this server yet</td></tr><tr><td>`SEARCH_TOO_SHORT`</td><td>area search with fewer than 2 letters</td></tr><tr><td>`ADDRESS_LIMIT_REACHED`</td><td>an 11th saved address</td></tr><tr><td>`LABEL_ALREADY_USED`</td><td>a second HOME or WORK</td></tr><tr><td>`CUSTOM_LABEL_REQUIRED`</td><td>OTHER without a name</td></tr><tr><td>`NEAR_DUPLICATE`</td><td>within 50 m of a saved address (`data.details` = that address)</td></tr><tr><td>`DROPOFF_REQUIRED`</td><td>a drop-off is needed and none was given</td></tr><tr><td>`DROPOFF_INVALID`</td><td>not exactly one of address / recent / pin, or the address / recent is not yours</td></tr><tr><td>`SHOP_LOCATION_REQUIRED`</td><td>checkout of a physical product from a shop without a location</td></tr></tbody></table>

## Values

<table id="bkmrk-value-meaning-matcht"><thead><tr><th>Value</th><th>Meaning</th></tr></thead><tbody><tr><td>`MatchType` `CONTAINED` / `NEAREST`</td><td>pin inside a ward / within 500 m of one</td></tr><tr><td>`AddressLabel` `HOME` / `WORK` / `OTHER`</td><td>HOME and WORK once each; OTHER needs `customLabel`</td></tr><tr><td>`PlaceSource`</td><td>where a snapshot came from: `SHOP_LOCATION`, `SAVED_ADDRESS`, `RECENT`, `NEW_PIN`, `STATION`</td></tr><tr><td>`AreaLevel` `REGION` / `DISTRICT` / `WARD`</td><td>the three kinds of area</td></tr></tbody></table>

## Limits

<table id="bkmrk-limit-value-nearest-"><thead><tr><th>Limit</th><th>Value</th></tr></thead><tbody><tr><td>Nearest-ward distance</td><td>500 m</td></tr><tr><td>Saved addresses per user</td><td>10</td></tr><tr><td>Recent pins per user / kept</td><td>5 / 60 days</td></tr><tr><td>Same place (duplicate / recent refresh)</td><td>50 m</td></tr><tr><td>Shop pin far from the phone (warning)</td><td>1 km</td></tr><tr><td>Area search results</td><td>20</td></tr></tbody></table>

# Shipping Service API

**Author**: Josh S. Sakweli, Backend Lead Team **Last Updated**: 2026-10-28 **Version**: v1.1

**Base URL**: `https://api.nexgate.co/api/v1`

**Short Description**: The shipping service decides how a shop's order reaches the buyer — **pickup** at the shop or **delivery** by a shipper — and runs it from the price on a product card to the money being paid out. It holds the shippers (delivery businesses that register themselves, and providers like Bolt that NexGate plugs in), their coverage, prices, hours and stations; the engine that picks and ranks delivery options; the orders' pickup and delivery steps with their codes; the money per leg; reliability, reviews and the admin tools.

**Related docs**:

- `docs/location/location_api_doc.md` — pins, wards, areas, shop locations, saved addresses, the *drop-off* object and *place snapshots* used everywhere below.
- `docs/shipping/campaigns/campaigns_api_doc.md` — shipping campaigns (free / discounted delivery paid by a shipper, the seller or NexGate).
- `commerce_logistics_changes.md` — what changed in **existing** endpoints (cart, checkout, orders, payments) — the numbered §-sections referenced below.

**Hints**:

- **Shipper logos** are objects, like shop logos — never a bare URL. Lists (delivery options, cart, leg alternatives): `logo` = `{ fileId, status, thumbUrl, mimeType }`. Shipper screens (profile, favourites, my businesses, admin): `logo` = `{ fileId, status, variants, mimeType }`. While `status` is not `READY` the URLs are null — show a placeholder. `logo` is null when the shipper has none.
- Every endpoint needs a logged-in user (Bearer token) except the Bolt webhook.
- **The buyer, the seller and every shipper only talk to NexGate.** Nobody books a shipper directly.
- **Money never moves on trust.** It sits in escrow and moves on proof: a 4-digit code at each handover and the buyer's "✓ It's what I ordered".
- **Shippers see a parcel, never the order** — no items, prices or order number; exact places and phones only after they accept.
- Coded refusals are HTTP **409** with `data.code` (some with `data.details`) — switch on the code. Full list in Part 4.
- Money is whole TZS; times are East Africa Time.

---

## Standard Response Format

### Success

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Delivery options",
  "action_time": "2026-10-24T10:30:45",
  "data": { }
}

```

### Error (coded refusal)

```json
{
  "success": false,
  "httpStatus": "CONFLICT",
  "message": "A shipper has taken this order; it can no longer switch to pickup",
  "action_time": "2026-10-24T10:30:45",
  "data": { "code": "SWITCH_NOT_ALLOWED", "reason": "A shipper has taken this order; it can no longer switch to pickup" }
}

```

<table id="bkmrk-field-type-descripti"><thead><tr><th>Field</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>`success`</td><td>boolean</td><td>`true` for success, `false` for errors</td></tr><tr><td>`httpStatus`</td><td>string</td><td>HTTP status name</td></tr><tr><td>`message`</td><td>string</td><td>Human-readable result, safe to show</td></tr><tr><td>`action_time`</td><td>string</td><td>When the response was made</td></tr><tr><td>`data`</td><td>object/string</td><td>Payload, or `{ code, reason, details? }` for a coded refusal</td></tr></tbody></table>

Other errors: 400 validation (field messages), 401 not logged in, 403 not allowed (e.g. not the owner, not an admin), 404 not found.

---

## HTTP Method Badge Standards

- **GET** - <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> - read only
- **POST** - <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> - create / act
- **PUT** - <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> - replace
- **DELETE** - <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> - remove

---

## Contents

- **Part 1 — How shipping works** (read this first) 1.1 The people · 1.2 Pickup or delivery · 1.3 From a product card to a paid order · 1.4 The engine · 1.5 The money · 1.6 Pickup order, step by step · 1.7 Door delivery, step by step · 1.8 Station routes · 1.9 Bolt · 1.10 Codes and the parcel number · 1.11 When a shipper says no · 1.12 What the buyer can change · 1.13 Refusing a parcel at the shop · 1.14 Finishing: confirm or report · 1.15 Shippers: register, set up, go live · 1.16 Reliability, reviews, ratings · 1.17 Group purchase and installments · 1.18 Timers · 1.19 Notifications · 1.20 Admin
- **Part 2 — Endpoints for buyers and sellers** (estimation, quotations, cart, order actions, favourites, reviews)
- **Part 3 — Endpoints for shippers** (registration, setup, stations, offers, jobs) and **admins**
- **Part 4 — Statuses, values, error codes, settings**

---

# Part 1 — How shipping works

## 1.1 The people

<table id="bkmrk-who-does-uses-buyer-"><thead><tr><th>Who</th><th>Does</th><th>Uses</th></tr></thead><tbody><tr><td>**Buyer**</td><td>chooses pickup or delivery, pays, gives the code, confirms "✓ It's what I ordered"</td><td>the normal app</td></tr><tr><td>**Seller** (shop owner)</td><td>accepts the order, packs, taps Ready, hands over by typing the code</td><td>shop orders screen</td></tr><tr><td>**Native shipper** ("delivery business")</td><td>registers itself, sets coverage / prices / hours, accepts job offers, carries the parcel</td><td>the same app, in "delivery business" mode (owner only for now)</td></tr><tr><td>**Integrated provider** (Bolt)</td><td>NexGate books it by API; never registers through the app</td><td>nothing — the backend talks to Bolt</td></tr><tr><td>**Station business** (e.g. a bus company)</td><td>a shipper with **stations**: carries between its own stations</td><td>same app</td></tr><tr><td>**Admin**</td><td>unsticks orders, settles money, suspends shippers, reports</td><td>admin endpoints</td></tr></tbody></table>

**Talking to a shipper is by call only** — no chat. Once a shipper accepts, the order shows its name and phone (`fulfillment.shippers`), and since 2026-11-17 `assignedTo` (`accountId`, `name`, `userProfileMedia`, never a phone) when the business gave the leg to one of its riders. The buyer and the shop can also make a NexGate call about the parcel while the order is open (`docs/team/api/nexgate_app_team_api.md` Part 8). Bolt shows its driver's phone (`fulfillment.rider`).

## 1.2 Pickup or delivery

- Every **shop's order is one parcel**. A cart with three shops = three parcels, each with its own choice.
- **PICKUP** — the buyer collects at the shop with a code. Free.
- **DELIVERY** — a shipper brings it: to the **door**, or to a **station** where the buyer collects (e.g. Mbeya bus stand). One parcel may travel through **up to 3 shippers** (legs).
- The choice belongs to the **shop**, not the item. The cart has **one destination** for all shops.
- Digital products need neither.

Every order's fulfillment keeps a frozen copy of the shop (`pickup`) and the destination (`dropoff`) — see location doc §1.5 — plus the receiver (name + phone; default = the buyer) and a note for this order only.

## 1.3 From a product card to a paid order — estimation → quotation → agreement

```
Product card      "🚚 3,500 – 7,000 · 30 min – 2 h"      ESTIMATION  — a hint; nothing saved
     │
Add-to-cart sheet  options: ⭐ Mbezi Boda 3,500 · ⚡ …     QUOTATION   — real prices, held 5 days
Cart               one choice per shop, editable           (the buyer may change shipper, address, pickup/delivery)
     │
Checkout           the quotation becomes the deal           AGREEMENT   — editable until paid
     │
Paid               price locked for the order's life; seller and shippers still have to sign (accept)

```

<table id="bkmrk-stage-endpoint-rules"><thead><tr><th>Stage</th><th>Endpoint</th><th>Rules</th></tr></thead><tbody><tr><td>Estimation</td><td>`POST /shipping/estimations`</td><td>one call per list screen with the header "Deliver to"; cached ~1 h per pair of wards; `cost` = range of the sensible options</td></tr><tr><td>Quotation</td><td>`POST /shipping/quotations`</td><td>per shop; covers the shop's **whole parcel** (cart items + the new one with `includeCart: true`); **prices held 5 days** while the parcel (items, quantities, destination) is unchanged — any change = a new quotation at today's prices</td></tr><tr><td>Cart</td><td>`PUT /e-commerce/cart/destination`, `PUT /e-commerce/cart/shops/{shopId}/fulfillment`</td><td>defaults below</td></tr><tr><td>Agreement</td><td>checkout session (`commerce_logistics_changes.md` §11c, §33)</td><td>made when the session is created; expired held price → re-quoted; same shipper same price → silent, else refused `DELIVERY_PRICE_CHANGED` / `DELIVERY_OPTION_GONE` — **never a silent new price**</td></tr></tbody></table>

**Cart defaults for a shop** (until the buyer picks):

<table id="bkmrk-the-buyer-has%E2%80%A6-the-s"><thead><tr><th>The buyer has…</th><th>The shop's parcel is</th></tr></thead><tbody><tr><td>a destination and a shipper covers it</td><td>**Delivery** with the pre-selected option</td></tr><tr><td>a destination, nobody covers it</td><td>**Pickup** + notice "Delivery is not available to X yet"</td></tr><tr><td>no destination</td><td>**Pickup** + notice "Add a delivery address to see delivery options"</td></tr></tbody></table>

A pickup the **buyer** chose never changes by itself; a default pickup turns into delivery once a shipper covers. On an address change the buyer's shipper is kept while it can carry, else a favourite, else ⭐. Every cart change answers with a **delivery change** (`deliveryBefore → deliveryAfter`, "1 shop switched to pickup", `canChangeBack`).

**Pre-selected option** = the shipper the buyer chose for this shop in the cart (if it still can carry) → else the cheapest favourite that can → else ⭐ Recommended. An earlier pick outside the cart only gets the `USED_BEFORE` label.

**What the app may keep locally:** the header "Deliver to" for cards, last map position, recently searched places, a sheet in progress. **What must stay on the server:** the cart's destination and each shop's quotation (a 5-day price promise), agreements, saved addresses and recents.

## 1.4 The engine — who can deliver, at what price, in what order

1. **Where:** both places' ward / district / region.
2. **Who:** native shippers whose coverage holds **both ends** (trip rule `WITHIN_EACH` = both in the same ticked area, `WITHIN_AND_ACROSS` = both in any ticked areas), plus integrated providers (Bolt), plus station routes.
3. **Filter (with a reason):** too far (`TOO_FAR`), parcel value above its maximum (`VALUE_TOO_HIGH`), bulky and not accepted (`BULKY_NOT_ACCEPTED`), no prices (`NO_PRICING`), never open soon (`NOT_OPEN_SOON`); paused / suspended shippers are left out.
4. **Cost** = base (distance band or flat) + value add-on (insurance ladder) + bulky extra; add-ons rounded **up** to 100. Distance = straight line × **1.3** (cards: ward centre to ward centre, so every card for the same two wards agrees).
5. **Time** = always a range, **from when the shop is ready**: the first moment both the shop and the shipper are open (and before the shipper's same-day cut-off), plus the band's minutes. Closed hours **move** the time (`shiftReason`: `SHOP_PAUSED`, `SHOP_CLOSED`, `SHIPPER_CLOSED`, `CUT_OFF`), they never drop the option.
6. **Clean-up** (moved under "See all", never deleted): **dominated** (another option is cheaper-or-equal *and*earlier-or-equal), **outlier** (&gt; 3× the cheapest), **beyond the top 5**. Favourites are never hidden.
7. **Labels:** 💰 `CHEAPEST`, ⚡ `FASTEST` (by latest arrival), ⭐ `RECOMMENDED` (price + speed; cheap parcels lean on price; a well-rated shipper with ≥ 5 reviews gets a small nudge), `USED_BEFORE`. One option can carry two. With campaigns, "price" means **what the buyer pays**.
8. **Order:** ⭐, 💰, ⚡, then favourites, then the rest by cost; 5 shown, the others in `more`.
9. Ties rotate daily so equal shippers share the top. New shippers show a "New" badge for 30 days.

## 1.5 The money

The buyer pays once. Each shop's order holds its money in **escrow parts**:

```
Order ORD-…  (one shop's parcel)
 ├ ITEMS part  → the seller          platform fee on items + tax only
 ├ LEG part 1  → shipper 1's owner   fee = that shipper's delivery commission (0% today)
 ├ LEG part 2  → shipper 2's owner   (station routes: one part per leg)
 └ (pickup or a free delivery: ITEMS only)

```

- Bolt's leg is paid into the ledger account **`PROVIDER-BOLT`** (money NexGate owes Bolt, settled monthly), with no commission — NexGate's margin is a 2% price buffer.
- **Everything stays held until the buyer's code is typed** at the shop or the door → **all parts released together** in one transaction. Bolt has no code, so there the buyer taps "✓ It's what I ordered", and "⚠ Report a problem" freezes every part until support settles it.
- Campaign shares (shipper discount, seller share, NexGate share) are worked out at the quotation, taken at payment and frozen on the order → `docs/shipping/campaigns/campaigns_api_doc.md`.

<table id="bkmrk-event-money-buyer-ca"><thead><tr><th>Event</th><th>Money</th></tr></thead><tbody><tr><td>Buyer cancels before the seller accepts · seller cancels · not collected in time · shop never accepted</td><td>everything refunded, stock back</td></tr><tr><td>Switch to pickup (only until a shipper accepts)</td><td>the delivery parts refunded in full</td></tr><tr><td>Pickup → delivery after payment</td><td>the buyer pays the delivery from the wallet into new leg part(s)</td></tr><tr><td>New shipper, same or cheaper</td><td>the leg part moves to the new shipper, the difference is refunded</td></tr><tr><td>New shipper, dearer</td><td>the buyer decides; "use it" tops up the leg part from the wallet</td></tr><tr><td>Address change before a shipper accepts</td><td>the difference is paid from / refunded to the wallet</td></tr><tr><td>Admin cancel while the shipper is heading to the shop</td><td>the shipper keeps 50% (wasted trip), the rest is refunded</td></tr></tbody></table>

The order's `shippingFee` / `totalAmount` follow these changes (they can change after payment).

## 1.6 Pickup order, step by step

```
PLACED ──seller accepts──► ACCEPTED ──"Packed & ready"──► READY ──seller types buyer's code──► COLLECTED ──buyer confirms──► COMPLETED
   │ buyer may cancel          │ seller may cancel           │ seller may cancel
   └── not accepted in 3 opening hours → CANCELLED          └── not collected in 14 days → EXPIRED (refund)

```

1. **Accept** (`POST /shipping/orders/{id}/accept`, seller) — within **3 opening hours** of the shop (a shop with no hours counts 8:00-20:00), else the order is cancelled and refunded. The order gets its **parcel number** (`NX-4K7P-2Q`).
2. **Ready** (`/ready`) — one tap "Packed &amp; ready" (`packedWell` tick recorded). The buyer gets the place (shop, landmark, phone), a **collect-by** date (14 days) and the **4-digit code by SMS**.
3. **Pickup time** (optional, `/pickup-time`) — "When will you come?" inside the shop's opening hours. Not binding, does not move the 14 days; the seller sees it. Reminders on day 7, day 12 and the last day (SMS).
4. **Collect** (`/collect`) — at the counter the **seller types the buyer's code** → `COMPLETED`, money released. The buyer checks the parcel before giving the code. No confirm step and no Report a problem on pickup orders.

The buyer can turn a pickup into a delivery any time before collecting (§1.12).

## 1.7 Door delivery, step by step

```
PLACED → ACCEPTED → READY → SHIPPER_ACCEPTED → HEADING_TO_SHOP → ON_THE_WAY → COMPLETED
         seller     seller   shipper accepts    shipper taps      seller types   shipper types
         accepts    Ready    (offer)            "heading"         rider's code   buyer's code

```

1. **Paid** — the shipper already sees the parcel under **Upcoming** (areas only, value band, size, its cost): "Waiting for the seller" → "Seller is packing". Not a commitment; cards can disappear.
2. **Seller accepts** — parcel number given; the seller's app can print a **QR label** (parcel number only) or the seller writes the number on the box. A non-binding heads-up goes to the shipper.
3. **Seller taps Ready** — the pop-up needs **both ticks**: "I have packed it well" and "the parcel number / label is on the package" (`READY_CONFIRM_REQUIRED`). The **job offer** goes to the shipper with a countdown (its response window, **15 min** for every shipper, counted only while it is open; closed → the offer waits and rings at opening; closed for more than 24 h → the next shipper at once).
4. **Shipper accepts** = signs the deal. **From here the buyer's delivery is locked** (no address change, no switch to pickup). The shipper gets the **pickup code** (shown once + SMS) and the exact places and phones.
5. **Heading to the shop** — the shipper taps it when it sets out; the seller is told (SMS too).
6. **At the shop** — both sides can see the parcel number; the **seller types the rider's pickup code** (`/hand-over`) → `ON_THE_WAY`; the order becomes `SHIPPED`and the buyer's **confirmation code** goes by SMS to the receiver.
7. **At the door** — the **rider types the receiver's code** (`/jobs/{id}/deliver`) → `COMPLETED`, seller and shipper paid. Wallet history: "Sale Earnings" / "Delivery Earnings". The buyer's code is their confirmation.

After accepting, a job is **binding**: the shipper must finish it. Failing it is a heavy reliability hit.

## 1.8 Station routes — collect at a station, or several shippers

A station business carries between its own stations (pair price table, e.g. Dar Magufuli Terminal → Mbeya Bus Stand). The parcel always starts with a collection **at the shop**:

<table id="bkmrk-route-kind-how-leg-1"><thead><tr><th>Route kind</th><th>How leg 1 starts</th></tr></thead><tbody><tr><td>`STATION_COLLECTS`</td><td>the station business fetches it from the shop itself (it ticks where it collects + a flat fee, 0 = free)</td></tr><tr><td>`DOOR_TO_STATION`</td><td>a door shipper takes it shop → origin station, then the station business carries it on</td></tr></tbody></table>

The route can end **at a station** (`route.collectAt` set — the buyer collects there, within the station's reach, default 30 km) or **at the door** (`collectAt` null — a last door leg from the destination station). Up to 3 legs. A station within **1 km** of the buyer's pin (`atPin`) is never hidden.

```
Leg 1 🚪 Kibuti Express   shop (Ubungo) → Magufuli Terminal      3,500
Leg 2 🚌 Shabiby          Magufuli Terminal → Mbeya Bus Stand   21,000   → buyer collects (AT_STATION), or
Leg 3 🚪 Mbeya Riders     Mbeya Bus Stand → buyer's door          2,500

```

- Offers go to **every leg at once**; the parcel moves only when **all** legs have accepted (`SHIPPER_ACCEPTED`), then only the leg collecting at the shop gets the pickup code.
- **Handovers between legs** follow one rule: *whoever receives holds the code, whoever hands over types it*. A station counter gets its code on the station's phone, a rider on its owner's phone.
- The bus company taps **Arrived** at its destination station → `AT_STATION`; that sends the next code (the buyer's collection code, or the last rider's handover code). `collectBy` = +7 days.
- Station staff type the buyer's code with the last leg's `deliver`.
- In the quotation the buyer can **swap a door leg's shipper** (`alternatives` → `swap`); another bus company or another meeting point is a separate option.
- Not yet: switching to a station route or changing a station route's destination after payment (`STATION_ROUTE_NOT_HERE`).

## 1.9 Bolt

NexGate resells Bolt rides (boda): **single leg, one city, door to door, non-bulky parcels only**, and only in the areas NexGate turned on for Bolt. To the buyer it is just another option card named "Bolt".

- **Price:** Bolt's highest estimate + **2%**, rounded up. NexGate absorbs differences within that.
- **Ready books the ride.** No rider / price went up / daily spend limit reached → handled like a shipper saying no.
- Rider assigned → `HEADING_TO_SHOP`; the order gets a **`rider`** card (name, photo, phone, **plate**, model, tracking link, minutes to the shop).
- **No codes with Bolt:** the seller checks the **plate** and taps `/hand-over-rider` (`USE_PLATE_CHECK` if the code hand-over is used; `PLATE_MISMATCH` if wrong). Bolt starting the ride also counts as the hand-over. Bolt "completed" → `DELIVERED`; the buyer confirms with the button.
- **The shop did not hand over** (Bolt "client did not show") → back to `ACCEPTED` (Ready again = a new ride); Bolt's call-out charge is taken from the **seller's** items money at completion.
- Followed by a webhook **and** a poller every 15 s. Admins have a kill-switch, a daily spend limit, a status view and the monthly invoice settlement (Part 3).

## 1.10 Codes and the parcel number

<table id="bkmrk-parcel-number-nx-4k7"><thead><tr><th></th><th>Parcel number `NX-4K7P-2Q`</th><th>4-digit codes</th></tr></thead><tbody><tr><td>Purpose</td><td>**identifies** the parcel (on the box, QR)</td><td>**proves** a handover</td></tr><tr><td>Secret</td><td>no</td><td>yes — hashed, never logged</td></tr><tr><td>How many</td><td>one per parcel, for life (kept when switching pickup ↔ delivery)</td><td>one per handover</td></tr><tr><td>Who sees it</td><td>buyer, seller, every shipper on the route, station staff</td><td>only the holder</td></tr></tbody></table>

**Rule: whoever RECEIVES the parcel holds the code; whoever HANDS IT OVER types it in.**

<table id="bkmrk-handover-holder-%28get"><thead><tr><th>Handover</th><th>Holder (gets the SMS)</th><th>Types it</th><th>Endpoint</th></tr></thead><tbody><tr><td>Pickup at the shop</td><td>buyer (receiver)</td><td>seller</td><td>`POST /shipping/orders/{id}/collect`</td></tr><tr><td>Shop → shipper</td><td>shipper (owner's phone)</td><td>seller</td><td>`POST /shipping/orders/{id}/hand-over`</td></tr><tr><td>Shipper → shipper / station</td><td>the receiving rider / station counter</td><td>the giver</td><td>`POST /shipping/jobs/{id}/hand-over-next`</td></tr><tr><td>Door delivery</td><td>receiver</td><td>rider</td><td>`POST /shipping/jobs/{id}/deliver`</td></tr><tr><td>Collect at a station</td><td>buyer</td><td>station staff (last leg)</td><td>`POST /shipping/jobs/{id}/deliver`</td></tr></tbody></table>

- Codes live **24 h** (`CODE_EXPIRED`); **5 wrong tries** lock it (`CODE_LOCKED`; each wrong try says `triesLeft`).
- Holders see their code in the app, hidden until they tap View, for its 24 hours (`code.value` for the buyer, `myCode` for the shipper).
- Lost or leaked? **Only the holder** can ask for a new code: a fresh code in the app + SMS; the old one dies at once. Max **5** per handover per 24 h (`CODE_LIMIT`). Holder endpoints: buyer `POST /shipping/orders/{id}/code`, shipper at the shop `POST /shipping/jobs/{id}/code`, receiving rider / station `POST /shipping/jobs/{id}/handover-code`.
- The bell list only says "code sent" — the code itself is only in the SMS (and the one-time screen).
- The parcel number is public to both sides, so checking it is **not required**: the pickup code alone proves the handover. `POST /jobs/{id}/check-parcel` still answers for apps that use it.

## 1.11 When a shipper says no — reassignment and the buyer's decision

Before accepting, a shipper may **reject** (with a reason) or let the offer **run out**. Either way that shipper is left out of this order and the system looks for the next one, the way the buyer chose (⭐ / 💰 / ⚡):

<table id="bkmrk-found-what-happens-s"><thead><tr><th>Found</th><th>What happens</th></tr></thead><tbody><tr><td>**same price or cheaper, and not later**</td><td>takes over by itself; the difference is refunded; buyer notified (`SHIPPER_CHANGED`)</td></tr><tr><td>**dearer, slower, nobody, or already 3 changes on this order**</td><td>the **buyer decides** (`fulfillment.decision`)</td></tr></tbody></table>

`fulfillment.decision` = `{ reason, legId, askedAt, answerBy, proposal, difference, choices, ifNoAnswer, routeProposal }`:

<table id="bkmrk-reason-means-no_ship"><thead><tr><th>`reason`</th><th>Means</th></tr></thead><tbody><tr><td>`NO_SHIPPER`</td><td>nobody can take it</td></tr><tr><td>`COSTS_MORE` / `SLOWER`</td><td>the replacement is dearer / later</td></tr><tr><td>`TOO_MANY_CHANGES`</td><td>3 replacements already on this order</td></tr><tr><td>`WAITING_TOO_LONG`</td><td>still no shipper 24 h after Ready</td></tr><tr><td>`PARCEL_TOO_BIG`</td><td>a shipper found it bulky at the shop (§1.13)</td></tr></tbody></table>

<table id="bkmrk-choices-does-use_new"><thead><tr><th>`choices`</th><th>Does</th></tr></thead><tbody><tr><td>`USE_NEW_SHIPPER`</td><td>pay the `difference` from the wallet (`WALLET_INSUFFICIENT` if short; negative = money back)</td></tr><tr><td>`KEEP_WAITING`</td><td>only for `WAITING_TOO_LONG`; not asked again for 24 h</td></tr><tr><td>`PICKUP`</td><td>delivery refunded, the order becomes a pickup order (`READY`, code by SMS)</td></tr><tr><td>`END_AT_STATION`</td><td>station route whose last door leg failed: collect at that station, the leg refunded</td></tr><tr><td>`CANCEL`</td><td>everything refunded</td></tr></tbody></table>

**No answer in 24 h → `ifNoAnswer` (pickup).** Station routes: a failing bus leg is first replaced by another station business within 1 km at both ends (neighbours unchanged), else in the same district (neighbours re-routed and re-costed; an already-accepted neighbour whose point or time moved gets a **re-confirm** offer with `reconfirmNote`). `routeProposal` lists every leg that would change. Any accepted leg whose arrival moves more than **4 h** later must re-confirm.

## 1.12 What the buyer can change after paying

<table id="bkmrk-action-allowed-while"><thead><tr><th>Action</th><th>Allowed while</th><th>Money</th></tr></thead><tbody><tr><td>**Cancel the whole order**</td><td>`PLACED` (before the seller accepts), or the delivery is stuck (no shipper / a decision waiting)</td><td>everything refunded</td></tr><tr><td>**Switch to pickup**</td><td>delivery, **until a shipper accepts** (`PLACED` / `ACCEPTED` / `READY`)</td><td>delivery refunded in full</td></tr><tr><td>**Switch to delivery**</td><td>pickup, until collected (`PLACED` / `ACCEPTED` / `READY`)</td><td>delivery paid from the wallet</td></tr><tr><td>**Change the delivery address**</td><td>**until a shipper accepts**; max **3** changes per order</td><td>difference paid / refunded</td></tr></tbody></table>

Both switches and the address change are two calls: **options** (`POST /shipping/orders/{id}/delivery-options` with a drop-off → a normal quotation) then **apply** (`switch-to-delivery` / `change-destination` with the `quotationId` + `optionId`). Once a shipper accepts → `CHANGE_NOT_ALLOWED` / `SWITCH_NOT_ALLOWED` — like AliExpress once an order ships. Switching to delivery on a parcel already Ready with both ticks sends the offer at once; otherwise the seller taps Ready again.

**The seller** can cancel (pop-up "I have already informed the buyer", `informedBuyer: true`): a pickup order until collected; a delivery order only before Ready. After Ready → support (admin cancel).

**Installment orders** are cancelled only through their installment agreement (`INSTALLMENT_ORDER`).

## 1.13 Refusing a parcel at the shop

After accepting and **before taking the parcel**, a shipper may refuse it (`POST /shipping/jobs/{id}/refuse-parcel`):

<table id="bkmrk-reason-then-too_big-"><thead><tr><th>Reason</th><th>Then</th></tr></thead><tbody><tr><td>`TOO_BIG`</td><td>the parcel is treated as bulky; a shipper that carries bulky is found. Same or cheaper → automatic; dearer → buyer decides (`PARCEL_TOO_BIG`); nobody → pickup or cancel. Two different shippers reporting the same single-product parcel → the product is marked `bulky`</td></tr><tr><td>`BADLY_PACKED`</td><td>back to `ACCEPTED`; the seller repacks and taps Ready again → the same shipper gets a fresh offer</td></tr></tbody></table>

**Nobody pays for the trip** (like a driver turning down a ride) and it never counts against the shipper. The order shows `fulfillment.refusal`. Admins can mark a "too big" claim false (a strike on the shipper).

## 1.14 Finishing — confirm or report a problem

**The buyer's code finishes the order.** Pickup and delivery both go straight to `COMPLETED`; every escrow part (seller, every shipper, instalments held) is released together, with no more buttons to confirm.

**"⚠ Report a problem"** (`/report-problem` with a note) is for **delivery orders only**, until `problemReportUntil` (7 days after completion). It is only recorded: no money moves. Admins see it under `problemReports` on the operations board, NexGate settles it by hand, then marks it with `POST /admin/shipping/orders/{id}/problem-resolved` (`{ "reason": "…" }`).

**Bolt has no code**, so it still ends at `DELIVERED` with two buttons: **"✓ It's what I ordered"** (`/confirm`) releases the money, and **"⚠ Report a problem"** freezes every part; confirm is refused (`AGREEMENT_FROZEN`) until an admin releases or refunds. Parcels already at `COLLECTED` or `DELIVERED` before this change finish the same way.

## 1.15 Shippers — register, set up, go live

```
Register (KYC, auto-approved) ──► KYC_APPROVED ──service type + coverage + prices (+ stations)──► LIVE ⇄ PAUSED (owner)
                                                                                                  └─► SUSPENDED (admin / automatic)

```

1. **KYC** — `POST /shipping/businesses`: name, contact phone, **office pin**, and three private documents (file + number, + expiry where it has one): **business licence** (number unique), **director's NIDA** (20 digits), **LATRA licence**. Upload files first to File Thunder as business documents. No manual approval.
2. **Service setup** (any order, any time; `GET …/setup` = checklist with `canGoLive` and what is missing): 
    - `PROFILE` logo, description, WhatsApp, email (optional)
    - `SERVICE_TYPE` door and / or station (required)
    - `HOURS` working hours (default Mon–Sat 08:00–18:00; several ranges a day, special days, same-day cut-off)
    - `COVERAGE` ticked areas + trip rule (required)
    - `PRICING` door prices: distance **bands** or **flat**, optional value add-on ladder (required for door)
    - `LIMITS` max parcel value, bulky yes / no + extra, response window (5–120 min), heads-up on/off, station reach
    - `STATIONS` + `STATION_PRICES` (station businesses: a station in every ticked area, at least one priced pair) and optional **collection from shops** (areas + fee + extra minutes)
3. **Live** automatically once the required items are done. The owner can **pause** (with a reason) and **resume**. Documents close to expiry send `SHIPPER_DOCUMENT_EXPIRING` (14 and 3 days before).

A user may own several businesses. Only the owner manages one; admins can read everything.

## 1.16 Reliability, reviews, private ratings, favourites

**Reliability** (automatic, internal):

<table id="bkmrk-signal-%E2%9A%A0-warning-%E2%8F%B8-p"><thead><tr><th>Signal</th><th>⚠ Warning</th><th>⏸ Paused (owner resumes)</th><th>⛔ Suspended (admin lifts)</th></tr></thead><tbody><tr><td>Offers missed in a row</td><td>2</td><td>3</td><td>—</td></tr><tr><td>Automatic pauses</td><td>—</td><td>—</td><td>3rd within 7 days</td></tr><tr><td>Acceptance rate (last 20 offers)</td><td>&lt; 50%</td><td>&lt; 30%</td><td>—</td></tr><tr><td>Broke an accepted job (admin finding)</td><td>—</td><td>1st</td><td>2nd within 30 days</td></tr><tr><td>Found at fault in a problem (admin finding)</td><td>1st</td><td>—</td><td>2 within 30 days</td></tr><tr><td>False "too big" claims</td><td>—</td><td>—</td><td>3</td></tr><tr><td>On time (last 20 jobs)</td><td>&lt; 60%</td><td>—</td><td>—</td></tr></tbody></table>

Rates count only after the first 10 offers; misses while closed or paused, and withdrawn offers, don't count; rejecting with a reason only counts through the rate. Counting restarts after an automatic pause is resumed or a suspension lifted. Every step sends `SHIPPER_STANDING` with the reason ("Paused: 3 offers missed in a row — 10:02, 10:41, 11:15"). Accepted jobs must still be finished.

**Reviews** — like shop reviews: rating 1–5 and / or text (10–1000), one per person per shipper, **anyone except the owner**, owner reply, admin moderation. `verifiedDelivery` when the reviewer got a delivery from that shipper.

**Private ratings** — the shipper rates the seller (after hand-over) and the buyer (after delivery): 1–5 + an optional issue. Only admins read them.

**Favourites** — a buyer keeps up to 10 favourite shippers: ❤ badge, pre-selected when they can carry, never hidden.

## 1.17 Group purchase and installments

- **Group purchase:** each member chooses their own pickup / delivery and pays their delivery with their payment; the choice is frozen while the group fills; leaving or a failed group refunds items **and** delivery.
- **Installment, ships now:** the whole delivery is paid with the down payment.
- **Layaway (ships after the last instalment):** delivery refused at checkout (`LAYAWAY_DELIVERY_LATER`); the order is created as pickup when paid off and the buyer may choose delivery then (switch to delivery).

## 1.18 Timers (run by the backend)

<table id="bkmrk-timer-rule-seller-ac"><thead><tr><th>Timer</th><th>Rule</th></tr></thead><tbody><tr><td>Seller accept</td><td>3 opening hours, reminder 1 h before; then cancelled + refunded</td></tr><tr><td>Offer</td><td>15 min while the shipper is open</td></tr><tr><td>Chain safety net</td><td>no shipper 24 h after Ready → buyer asked (`WAITING_TOO_LONG`)</td></tr><tr><td>Buyer decision</td><td>24 h, then pickup</td></tr><tr><td>Pickup collection</td><td>14 days from Ready; reminders day 7, 12, last day (SMS); then `EXPIRED` + refund</td></tr><tr><td>Station collection</td><td>7 days (`collectBy`)</td></tr><tr><td>Codes</td><td>24 h</td></tr><tr><td>Quotation prices</td><td>held 5 days</td></tr><tr><td>Bolt</td><td>poller every 15 s; a ride searching over 10 min is cancelled and reassigned</td></tr><tr><td>Admin digest</td><td>07:30 every morning when something is stuck</td></tr></tbody></table>

## 1.19 Notifications

Each one opens the screen named by its `targetType` / `targetId`.

<table id="bkmrk-type-to-when-order_a"><thead><tr><th>Type</th><th>To</th><th>When</th></tr></thead><tbody><tr><td>`ORDER_ACCEPTED`</td><td>buyer</td><td>seller accepted (parcel number)</td></tr><tr><td>`ORDER_ACCEPT_REMINDER`</td><td>seller</td><td>1 h before the accept deadline</td></tr><tr><td>`PICKUP_READY` · `PICKUP_REMINDER` · `PICKUP_LAST_DAY` (+SMS)</td><td>buyer</td><td>pickup ready / not collected yet / last day</td></tr><tr><td>`SHIPPER_FOUND` · `SHIPPER_CHANGED`</td><td>buyer</td><td>every leg accepted (or Bolt rider) / automatic swap</td></tr><tr><td>`DELIVERY_DECISION_NEEDED`</td><td>buyer</td><td>`fulfillment.decision` set</td></tr><tr><td>`PARCEL_AT_STATION`</td><td>buyer</td><td>the parcel reached the buyer's station</td></tr><tr><td>`HANDOVER_CODE` (SMS)</td><td>the holder</td><td>a code for a handover</td></tr><tr><td>`ORDER_AWAITING_CONFIRM`</td><td>buyer</td><td>delivered / collected: tap "Received"</td></tr><tr><td>`RIDER_COMING` (+SMS)</td><td>seller</td><td>shipper heading to the shop / Bolt rider (plate)</td></tr><tr><td>`PARCEL_REFUSED`</td><td>seller</td><td>badly packed / Bolt left without the parcel</td></tr><tr><td>`ORDER_DELIVERED`</td><td>seller</td><td>Bolt only: delivered; paid when the buyer confirms</td></tr><tr><td>`JOB_CANCELLED`</td><td>shipper</td><td>an offer or job taken away</td></tr><tr><td>`DELIVERY_EARNINGS`</td><td>shipper</td><td>its money released</td></tr><tr><td>`SHIPPER_STANDING` · `SHIPPER_DOCUMENT_EXPIRING`</td><td>shipper</td><td>warning / pause / suspension · document expiring</td></tr><tr><td>`SHIPPER_NEW_REVIEW` · `SHIPPER_REVIEW_REPLY`</td><td>shipper · reviewer</td><td>review / reply</td></tr><tr><td>`SHIPPING_ADMIN_DIGEST`</td><td>staff + super admins</td><td>something stuck, 07:30</td></tr></tbody></table>

Campaign notifications: `docs/shipping/campaigns/campaigns_api_doc.md`.

## 1.20 Admin

<table id="bkmrk-role-can-staff_admin"><thead><tr><th>Role</th><th>Can</th></tr></thead><tbody><tr><td>`STAFF_ADMIN`</td><td>view everything (shippers, overview, operations board, reports, campaigns, Bolt status, audit log), suspend / lift, force a reassignment, mark a false bulky claim, moderate reviews, notes</td></tr><tr><td>`SUPER_ADMIN`</td><td>all of that + anything with money or settings: escrow release / refund, order cancel, commission changes, Bolt on/off, coverage, invoices, ride state (test modes)</td></tr></tbody></table>

Every admin action needs a **reason** and is written to the **audit log** (`GET /admin/audit`) with the state before and after. `shipperAtFault: true` on release / refund / cancel / reassign records a strike against the shipper.

---

# Part 2 — Endpoints for buyers and sellers

## A. Estimation and quotations

## A1. Card estimates

**Purpose**: The delivery hint on product cards and lists: cost range, time range, or "Pickup only". One call per screen.

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/estimations`

**Access Level**: 🔒 Protected (any logged-in user) · Bearer token

**Request JSON Sample**:

```json
{
  "dropoff": { "addressId": "9b1d0c2e-…" },
  "productIds": ["5f0e…", "77a1…"]
}

```

<table id="bkmrk-parameter-type-requi"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>dropoff</td><td>object</td><td>Yes</td><td>the header "Deliver to" — a drop-off (location doc §1.6)</td></tr><tr><td>productIds</td><td>array</td><td>Yes</td><td>products on screen (`TOO_MANY_PRODUCTS` above the limit)</td></tr></tbody></table>

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Delivery estimates", "action_time": "2026-10-24T10:30:45",
  "data": {
    "destinationArea": "Sinza, Ubungo, Dar es Salaam",
    "items": [
      { "productId": "5f0e…", "shopId": "aaaa…", "status": "DELIVERY",
        "cost": { "from": 3500, "to": 7000 }, "eta": { "fromMinutes": 30, "toMinutes": 120 },
        "freeDelivery": false, "pickupArea": null,
        "campaign": { "listFrom": 7000, "paidBy": ["SELLER", "NEXGATE"] } },
      { "productId": "77a1…", "shopId": "bbbb…", "status": "PICKUP_ONLY", "cost": null, "eta": null,
        "freeDelivery": false, "pickupArea": "Kariakoo, Ilala, Dar es Salaam" }
    ]
  }
}

```

<table id="bkmrk-field-description-st"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`status`</td><td>`DELIVERY` (cost + eta) · `PICKUP_ONLY` (no shipper; show `pickupArea`) · `DIGITAL` · `UNAVAILABLE`</td></tr><tr><td>`cost`</td><td>what the buyer pays (after campaigns), cheapest → dearest of the sensible options</td></tr><tr><td>`freeDelivery`</td><td>the cheapest shown option is free</td></tr><tr><td>`campaign`</td><td>badge "Delivery from <s>7,000</s> 3,500 · Shop + NexGate pay part" (absent without a campaign)</td></tr></tbody></table>

Nothing is saved; estimates ignore opening hours (durations only).

---

## A2. Get delivery options (quotation)

**Purpose**: The real options for one shop's parcel: the add-to-cart / buy-now sheet, the cart's "change shipper", the product page preview.

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/quotations`

**Access Level**: 🔒 Protected (buyer) · Bearer token

**Request JSON Sample** (sheet):

```json
{
  "items": [ { "productId": "5f0e…", "quantity": 2 } ],
  "includeCart": true,
  "dropoff": { "lat": -6.7735, "lng": 39.2187 },
  "preview": false
}

```

<table id="bkmrk-parameter-type-requi-1"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>items</td><td>array</td><td>one of items / shopId</td><td>products of **one** shop (`PRODUCTS_FROM_DIFFERENT_SHOPS`), quantity 1–1000, max 50 lines</td></tr><tr><td>shopId</td><td>UUID</td><td>without items</td><td>the cart page: quote what is in the cart from this shop</td></tr><tr><td>includeCart</td><td>boolean</td><td>No</td><td>add what the buyer already has in the cart from this shop (needed so the quotation fits the cart)</td></tr><tr><td>dropoff</td><td>object</td><td>Yes</td><td>where to (location doc §1.6)</td></tr><tr><td>preview</td><td>boolean</td><td>No</td><td>product page: compute only, nothing saved, no `quotationId`</td></tr></tbody></table>

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Delivery options", "action_time": "2026-10-24T10:30:45",
  "data": {
    "quotationId": "3c1f…", "shopId": "aaaa…", "shopName": "Shoe Shop",
    "pickup":  { "areaLabel": "Kariakoo, Ilala, Dar es Salaam", "wardId": 1146, "lat": -6.819, "lng": 39.2768, "source": "SHOP_LOCATION" },
    "dropoff": { "areaLabel": "Sinza, Ubungo, Dar es Salaam", "wardId": 1212, "lat": -6.7735, "lng": 39.2187, "source": "NEW_PIN" },
    "parcel": { "value": 120000, "bulky": false, "itemCount": 2,
                "items": [ { "productId": "5f0e…", "productName": "Sneakers", "quantity": 2, "unitPrice": 60000, "bulky": false } ] },
    "roadKm": 6.2,
    "deliveryAvailable": true, "unavailableReason": null, "unavailableMessage": null,
    "options": [
      { "optionId": "o-1", "businessId": "c4bc…", "name": "Mbezi Boda", "logo": { "fileId": "a1b4…", "status": "READY", "thumbUrl": "https://…/thumb.webp", "mimeType": "image/png" }, "isNew": false, "favourite": false,
        "labels": ["RECOMMENDED", "CHEAPEST", "FASTEST"],
        "cost": { "base": 3500, "valueAddon": 0, "bulkyExtra": 0, "total": 3500 },
        "eta": { "minMinutes": 30, "maxMinutes": 60, "startsAt": "2026-10-24T10:31:00",
                 "arrivalFrom": "2026-10-24T11:01:00", "arrivalTo": "2026-10-24T11:31:00", "shiftReason": null },
        "hiddenReason": null, "selected": true, "rating": { "average": 4.6, "count": 120 },
        "route": null, "offer": null }
    ],
    "more": [ { "optionId": "o-2", "name": "Dar Cargo", "hiddenReason": "DOMINATED", "…": "…" } ],
    "selectedOptionId": "o-1", "selectedBusinessId": "c4bc…", "selectionReason": "RECOMMENDED",
    "pricesHeldUntil": "2026-10-29T10:30:45", "expired": false,
    "cartBefore": { "businessId": "c4bc…", "businessName": "Mbezi Boda", "total": 3000 }, "difference": 500,
    "createdAt": "2026-10-24T10:30:45"
  }
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-qu"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`quotationId`</td><td>null for a preview or when no delivery is possible</td></tr><tr><td>`deliveryAvailable` / `unavailableMessage`</td><td>false → show the message and offer pickup</td></tr><tr><td>`options`</td><td>up to 5 shown; `more` = under "See all" with `hiddenReason` (`DOMINATED`, `OUTLIER`, `BEYOND_TOP`)</td></tr><tr><td>`labels`</td><td>`RECOMMENDED` ⭐ · `CHEAPEST` 💰 · `FASTEST` ⚡ · `USED_BEFORE`</td></tr><tr><td>`cost.total`</td><td>the shipper's table price; with a campaign show `offer.buyerPays` (campaigns doc)</td></tr><tr><td>`eta`</td><td>`startsAt` = first moment both shop and shipper are open; `shiftReason` says why it is later</td></tr><tr><td>`rating`</td><td>null = no ratings yet</td></tr><tr><td>`route`</td><td>station route (legs, `collectAt`, `atPin`) — §1.8; null = door delivery by one shipper</td></tr><tr><td>`selected` / `selectionReason`</td><td>the pre-selected option: `BUYER_CHOICE`, `FAVOURITE`, `RECOMMENDED`</td></tr><tr><td>`pricesHeldUntil`</td><td>prices held 5 days for this exact parcel and destination</td></tr><tr><td>`cartBefore` / `difference`</td><td>this shop's delivery in the cart now → after, for "3,000 → 3,500 (+500)"</td></tr></tbody></table>

**Errors**: `SHOP_REQUIRED`, `PRODUCTS_FROM_DIFFERENT_SHOPS`, `PRODUCT_NOT_IN_SHOP`, `PRODUCT_NOT_AVAILABLE`, `DIGITAL_NO_DELIVERY`, `ITEMS_REQUIRED`, `SHOP_LOCATION_REQUIRED`, `DROPOFF_INVALID`.

---

## A3. Read a quotation

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/quotations/{quotationId}`

**Access Level**: 🔒 Protected (the buyer it belongs to)

Same response as A2. `expired: true` once the 5 days are over — ask again for today's prices.

---

## A4. Pick an option

**Purpose**: The buyer taps another option in the sheet / cart list.

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

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

**Request**: `{ "optionId": "o-2" }` → the quotation with that option `selected`.

**Errors**: `OPTION_NOT_FOUND`, `QUOTATION_EXPIRED`, `QUOTATION_REPLACED`.

---

## A5. Other shippers for one leg of a route

**Purpose**: On a station route, list who else can do a **door** leg (e.g. leg 1 shop → terminal).

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/quotations/{quotationId}/options/{optionId}/legs/{position}/alternatives`

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

**Path Parameters**: `position` = leg number, starting at 1.

**Success Response** `data` (message "Other shippers for this leg"):

```json
[ { "businessId": "d1…", "name": "Kibuti Express", "logo": { "fileId": "a1b4…", "status": "READY", "thumbUrl": "https://…/thumb.webp", "mimeType": "image/png" }, "total": 3500, "minMinutes": 60, "maxMinutes": 120,
    "current": true, "rating": { "average": 4.2, "count": 15 } } ]

```

**Errors**: `LEG_NOT_FOUND`, `NOT_A_DOOR_LEG` (the bus leg: pick another option instead).

---

## A6. Swap one leg's shipper

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/quotations/{quotationId}/options/{optionId}/swap`

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

**Request**: `{ "position": 1, "businessId": "d2…" }` → the quotation with the edited route added as a **new option**and selected (the original start is kept; the arrival is the sum of the legs).

**Errors**: `LEG_NOT_FOUND`, `NOT_A_DOOR_LEG`, `SHIPPER_CANNOT_DO_LEG`.

---

## B. Cart

The cart's delivery side also shows in `GET /e-commerce/cart` (`destination`, `shops[]`, `deliveryTotal`, nudges) and in the answers of add / update / remove item — see `commerce_logistics_changes.md` §32, §48, §49, §68.

## B1. Set the cart's delivery address

**Purpose**: One destination for the whole cart; every shop is re-quoted.

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

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

**Request JSON Sample**:

```json
{ "dropoff": { "recentId": "a71e…" } }

```

**Success Response JSON Sample** (the delivery change):

```json
{
  "success": true, "httpStatus": "OK", "message": "Delivery address set", "action_time": "2026-10-24T10:30:45",
  "data": {
    "deliveryBefore": 10500, "deliveryAfter": 13000, "switchedToPickup": 1, "canChangeBack": true,
    "message": "Delivery 10,500 → 13,000, 1 shop switched to pickup",
    "changes": [
      { "shopId": "bbbb…", "shopName": "Phone Shop",
        "before": { "type": "DELIVERY", "businessName": "Dar Cargo", "total": 7000 },
        "after":  { "type": "PICKUP", "businessName": null, "total": 0 },
        "message": "Delivery is not available to Tabata yet" }
    ]
  }
}

```

**App:** show `message`; offer "Change back" when `canChangeBack`. An unsaved new pin is held on the cart and becomes a recent pin only after payment.

---

## B2. Change back to the previous address

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/e-commerce/cart/destination/change-back`

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

Same response as B1. **Errors**: `NOTHING_TO_CHANGE_BACK`.

---

## B3. Pickup or delivery for one shop

**Endpoint**: <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/e-commerce/cart/shops/{shopId}/fulfillment`

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

**Request JSON Sample**:

```json
{ "type": "DELIVERY", "quotationId": "3c1f…", "optionId": "o-2" }

```

<table id="bkmrk-parameter-type-requi-2"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>type</td><td>enum</td><td>Yes</td><td>`PICKUP` or `DELIVERY`</td></tr><tr><td>quotationId / optionId</td><td>UUID</td><td>No</td><td>the option picked in the list; `DELIVERY` alone = the default shipper</td></tr></tbody></table>

**Success Response**: the delivery change (as B1), message "Delivery choice saved".

**Errors**: `SHOP_NOT_IN_CART`, `DESTINATION_REQUIRED`, `DELIVERY_NOT_AVAILABLE`, `OPTION_REQUIRED`, `QUOTATION_OUTDATED`, `QUOTATION_EXPIRED`.

---

## C. Order actions — `{base_url}/shipping/orders/{orderId}/…`

One set of endpoints for pickup **and** delivery orders. Each answers with the order's **fulfillment**(`FulfillmentResponse`, also inside `GET /orders/{id}` as `fulfillment`):

```json
{
  "type": "DELIVERY",
  "status": "SHIPPER_ACCEPTED",
  "parcelNumber": "NX-4K7P-2Q",
  "pickup":  { "source": "SHOP_LOCATION", "label": "Shoe Shop", "areaLabel": "Kariakoo, Ilala, Dar es Salaam", "phone": "+2557…", "…": "…" },
  "dropoff": { "source": "SAVED_ADDRESS", "label": "Home", "areaLabel": "Sinza, Ubungo, Dar es Salaam", "directions": "Blue gate", "…": "…" },
  "receiver": { "name": "Mama Json", "phone": "+255712345678" },
  "note": "Call when you arrive",
  "delivery": { "quotationId": "…", "optionId": "…", "businessId": "c4bc…", "businessName": "Mbezi Boda", "roadKm": 6.2,
                "base": 3500, "valueAddon": 0, "bulkyExtra": 0, "total": 3500, "minMinutes": 30, "maxMinutes": 60,
                "arrivalFrom": "…", "arrivalTo": "…", "pricesHeldUntil": "…", "route": null, "offer": null },
  "placedAt": "…", "acceptedAt": "…", "readyAt": "…", "packedConfirmedAt": "…", "labelConfirmedAt": "…",
  "acceptBy": "…", "collectBy": null,
  "code": { "status": "ACTIVE", "expiresAt": "…" },
  "shippers": [ { "leg": 1, "businessId": "c4bc…", "name": "Mbezi Boda", "phone": "+255745051250",
                  "assignedTo": { "accountId": "3213…", "name": "Mama Yoyo", "userProfileMedia": { "fileId": "8c2e…", "status": "COMPLETED", "thumbUrl": "https://…/thumb.jpg", "mimeType": "image/jpeg" } } } ]
}

```

<table id="bkmrk-field-shown-when-sta"><thead><tr><th>Field</th><th>Shown when</th></tr></thead><tbody><tr><td>`status`</td><td>always — Part 4</td></tr><tr><td>`parcelNumber`</td><td>from the seller's accept</td></tr><tr><td>`delivery`</td><td>delivery orders: the shipper, price breakdown, window, `route`, campaign `offer`</td></tr><tr><td>`pickupTime`</td><td>pickup: the buyer's planned time</td></tr><tr><td>`collectBy` / `acceptBy`</td><td>collection deadline / seller's accept deadline</td></tr><tr><td>`needsShipperSince`</td><td>a shipper said no; "We're finding a new shipper"</td></tr><tr><td>`decision`</td><td>the buyer must choose (§1.11)</td></tr><tr><td>`refusal`</td><td>a shipper refused the parcel at the shop (§1.13)</td></tr><tr><td>`code`</td><td>the code the **viewer** holds: `ACTIVE` / `USED` / `LOCKED` / `REPLACED` / `EXPIRED`. `code.value` holds the digits **only** for the buyer on `GET /orders/{id}`, only while `ACTIVE`; everyone else sees the status alone. Hide it until the buyer taps View</td></tr><tr><td>`rider`</td><td>Bolt: driver card (§1.9)</td></tr><tr><td>`shippers`</td><td>name + phone per leg once its shipper accepted (not for Bolt)</td></tr><tr><td>`headingAt`, `pickedUpAt`, `deliveredAt`, `collectedAt`, `completedAt`, `closedAt` + `closeReason`, `problemReportedAt`</td><td>each step's time</td></tr></tbody></table>

## C1. Accept the order (seller)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/accept`

**Access Level**: 🔒 Protected (the shop's seller)

No body. → fulfillment `ACCEPTED` with `parcelNumber` (message "Order accepted"). Idempotent. **Errors**: `NOT_YOUR_ORDER`, `FULFILLMENT_STATE`.

---

## C2. Packed &amp; ready (seller)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/ready`

**Access Level**: 🔒 Protected (the shop's seller)

**Request JSON Sample**:

```json
{ "packedWell": true, "labelOnPackage": true }

```

<table id="bkmrk-parameter-type-requi-3"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>packedWell</td><td>boolean</td><td>delivery: Yes</td><td>"I have packed it well"</td></tr><tr><td>labelOnPackage</td><td>boolean</td><td>delivery: Yes</td><td>"the parcel number / label is on the package"</td></tr></tbody></table>

Pickup: the body may be left out. Delivery: sends the job offer(s) (or books Bolt). → fulfillment `READY`.

**Errors**: `READY_CONFIRM_REQUIRED`, `NOT_YOUR_ORDER`, `FULFILLMENT_STATE`.

---

## C3. Planned pickup time (buyer, pickup)

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

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

**Request**: `{ "pickupTime": "2026-10-25T15:00:00+03:00" }` (null clears it) → fulfillment with `pickupTime`.

**Errors**: `PICKUP_TIME_INVALID` (shop closed then, or outside the collection window), `NOT_PICKUP`.

---

## C4. "I lost my code" (buyer / receiver)

**Purpose**: A fresh code for the code the buyer holds: the pickup code (pickup order) or the delivery / station collection code (delivery order).

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/code`

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

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Show this code at the counter. It was also sent by SMS",
  "action_time": "2026-10-24T10:30:45",
  "data": { "code": "4821", "expiresAt": "2026-10-25T10:30:45", "sentTo": "+255712****78", "maxWrongTries": 5 }
}

```

Delivery orders answer "Give this code to the rider at the door. It was also sent by SMS". **Show the code once; it is never returned again.**

**Errors**: `CODE_LIMIT`, `CODE_NOT_YET` (station route: the code comes when the parcel arrives), `FULFILLMENT_STATE`.

---

## C5. Hand over to the shipper (seller)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/hand-over`

**Access Level**: 🔒 Protected (the shop's seller)

**Request**: `{ "code": "1234" }` — the 4-digit code the rider shows.

→ fulfillment `ON_THE_WAY` (message "Handed to the rider"); the order is `SHIPPED`; the receiver gets the delivery code.

**Errors**: `CODE_WRONG` (`details.triesLeft`), `CODE_LOCKED`, `CODE_EXPIRED`, `CODE_NOT_ACTIVE`, `USE_PLATE_CHECK` (Bolt), `USE_PICKUP_FLOW`.

---

## C6. Hand over to the Bolt rider (seller)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/hand-over-rider`

**Access Level**: 🔒 Protected (the shop's seller)

**Request**: `{ "plate": "MC 123 ABC" }` (spaces and case ignored) → fulfillment `ON_THE_WAY`.

**Errors**: `PLATE_MISMATCH` (the message names the expected plate), `BOLT_NOT_ASSIGNED`, `NO_BOLT_RIDE`.

---

## C7. Buyer collects at the counter (seller, pickup)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/collect`

**Access Level**: 🔒 Protected (the shop's seller)

**Request**: `{ "code": "4821" }` — the buyer's code. → fulfillment `COLLECTED`; the buyer is asked to confirm.

**Errors**: `CODE_WRONG`, `CODE_LOCKED`, `CODE_EXPIRED`, `CODE_NOT_ACTIVE`, `NOT_PICKUP`.

---

## C8. "✓ It's what I ordered" (buyer)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/confirm`

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

No body; only where the order is at `COLLECTED` / `DELIVERED`, which now means Bolt. → `COMPLETED`; every escrow part released (message "Order completed"). Idempotent.

**Errors**: `AGREEMENT_FROZEN` (a problem is open), `FULFILLMENT_STATE`.

---

## C9. Report a problem (buyer)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/report-problem`

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

**Request**: `{ "note": "The box was crushed and one shoe is missing" }` (required, max 500).

Delivery orders only. → fulfillment with `problemReportedAt`.

<table id="bkmrk-order-is-result-mess"><thead><tr><th>Order is</th><th>Result</th><th>Message</th></tr></thead><tbody><tr><td>`COMPLETED`, within `problemReportUntil`</td><td>Recorded for admins, no money moves</td><td>"Problem reported; our team will review it"</td></tr><tr><td>`DELIVERED` (Bolt)</td><td>Every part frozen; an admin settles it with escrow release / refund</td><td>"Problem reported; payment is on hold"</td></tr></tbody></table>

**Errors**: `DELIVERY_ONLY` (pickup order), `PROBLEM_WINDOW_CLOSED` (over 7 days), `FULFILLMENT_STATE`.

---

## C10. Delivery options for this order (buyer)

**Purpose**: Step 1 of switching a pickup order to delivery, or changing a delivery order's address.

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/delivery-options`

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

**Request**: a drop-off — `{ "addressId": "…" }` / `{ "recentId": "…" }` / `{ "lat": …, "lng": …, "directions": "…" }`.

**Success Response**: a quotation (as A2) for this order's items. Campaigns are priced against the items money held.

**Errors**: `CHANGE_NOT_ALLOWED` (a shipper accepted), `DROPOFF_INVALID`.

---

## C11. Switch to delivery (buyer, pickup order)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/switch-to-delivery`

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

**Request JSON Sample**:

```json
{
  "quotationId": "3c1f…", "optionId": "o-1",
  "dropoff": { "addressId": "9b1d…" },
  "receiver": { "name": "Mama Json", "phone": "0712345678" },
  "note": "Call when you arrive"
}

```

<table id="bkmrk-parameter-type-requi-4"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>quotationId / optionId</td><td>UUID</td><td>Yes</td><td>from C10</td></tr><tr><td>dropoff</td><td>object</td><td>Yes</td><td>the same drop-off as in C10</td></tr><tr><td>receiver</td><td>object</td><td>No</td><td>omit = the buyer</td></tr><tr><td>note</td><td>string</td><td>No</td><td>max 300</td></tr></tbody></table>

The delivery is paid from the wallet; the pickup code stops working. Ready with both ticks → offer sent now; else back to `ACCEPTED`. → fulfillment `type: DELIVERY`.

**Errors**: `ALREADY_DELIVERY`, `SWITCH_NOT_ALLOWED`, `WALLET_INSUFFICIENT`, `DELIVERY_PRICE_CHANGED`, `DELIVERY_OPTION_GONE`, `CAMPAIGN_ENDED`, `QUOTATION_OUTDATED`, `STATION_ROUTE_NOT_HERE`.

---

## C12. Change the delivery address (buyer, delivery order)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/change-destination`

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

Same body as C11. Only **before a shipper accepts**; max 3 changes. The difference is paid from / refunded to the wallet; an open offer is withdrawn and sent again for the new address (another shipper may be picked). Campaign shares never grow after payment. → fulfillment (message "Delivery address changed").

**Errors**: `CHANGE_NOT_ALLOWED`, `DESTINATION_CHANGE_LIMIT`, `NOT_DELIVERY`, `BOLT_RIDE_BOOKED`, `DELIVERY_NOT_PAID`, `WALLET_INSUFFICIENT`, `STATION_ROUTE_NOT_HERE`, plus the C11 price codes.

---

## C13. Switch to pickup (buyer, delivery order)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/switch-to-pickup`

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

No body. Only until a shipper accepts; the delivery is refunded in full (every campaign share goes back). If packed, the order is `READY` with a `collectBy` and the buyer gets the pickup code.

**Errors**: `ALREADY_PICKUP`, `SWITCH_NOT_ALLOWED`.

---

## C14. Answer a delivery decision (buyer)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/delivery-decision`

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

**Request**: `{ "choice": "USE_NEW_SHIPPER" }` — one of `fulfillment.decision.choices` (§1.11).

→ fulfillment (message "Decision saved").

**Errors**: `NO_DECISION_NEEDED`, `DECISION_CHOICE_INVALID`, `WALLET_INSUFFICIENT`, `CANNOT_END_HERE`.

---

## C15. Cancel (buyer or seller)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/orders/{orderId}/cancel`

**Access Level**: 🔒 Protected (the buyer or the shop's seller)

**Request JSON Sample** (seller):

```json
{ "informedBuyer": true, "reason": "Out of stock in this size" }

```

<table id="bkmrk-parameter-type-requi-5"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>informedBuyer</td><td>boolean</td><td>seller: Yes</td><td>the pop-up "I have already informed the buyer"</td></tr><tr><td>reason</td><td>string</td><td>No</td><td>max 500</td></tr></tbody></table>

The buyer may leave the body out. Rules in §1.12; everything is refunded and stock comes back.

**Errors**: `CANCEL_NOT_ALLOWED` (message says what to do instead), `INFORM_BUYER_FIRST`, `INSTALLMENT_ORDER`.

---

## D. Favourite shippers (buyer)

## D1. My favourites

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/favourites`

**Access Level**: 🔒 Protected

**Success Response** `data`: `[{ "businessId": "c4bc…", "name": "Mbezi Boda", "logo": { "fileId": "a1b4…", "status": "READY", "variants": { "lqip": "data:…", "thumb": "https://…", "medium": "https://…", "blurhash": "L53o…" }, "mimeType": "image/png" }, "status": "LIVE", "areaLabel": "Mbezi, Ubungo, Dar es Salaam", "addedAt": "…" }]`

## D2. Add / remove a favourite

**Endpoints**:

- <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/shipping/favourites/{businessId}` — add (idempotent)
- <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `{base_url}/shipping/favourites/{businessId}` — remove

Both answer with the updated list. **Errors**: `FAVOURITES_LIMIT` (10).

---

## E. Shipper profile and reviews (anyone logged in)

## E1. Public shipper profile

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/public`

**Access Level**: 🔒 Protected (any logged-in user)

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Shipper profile", "action_time": "2026-10-24T10:30:45",
  "data": {
    "businessId": "c4bc…", "name": "Mbezi Boda", "logo": { "fileId": "a1b4…", "status": "READY", "variants": { "lqip": "data:…", "thumb": "https://…", "medium": "https://…", "blurhash": "L53o…" }, "mimeType": "image/png" }, "description": "Fast boda in Ubungo",
    "verified": true, "isNew": false, "onNexGateSince": "2026-10-12T09:00:00",
    "availability": "OPEN",
    "openNow": { "hasHours": true, "openNow": true, "closesAt": "2026-10-24T18:00:00+03:00", "nextOpensAt": null },
    "office": { "areaLabel": "Mbezi, Ubungo, Dar es Salaam", "landmark": "Near Mbezi Mwisho stand" },
    "services": { "door": true, "station": false, "acceptsBulky": false, "bulkyExtra": null, "maxParcelValue": 2000000, "valueProtection": true },
    "coverage": { "businessId": "c4bc…", "trips": "WITHIN_AND_ACROSS", "areas": [ { "level": "REGION", "regionCode": "07", "name": "Dar es Salaam", "label": "Dar es Salaam" } ], "wardCount": 102 },
    "hours": { "weekly": [ { "day": "MONDAY", "open": "08:00", "close": "18:00" } ], "specialDays": [], "sameDayCutoff": "16:00", "timeZone": "Africa/Dar_es_Salaam" },
    "prices": { "mode": "BANDS", "bands": [ { "fromKm": 0, "toKm": 3, "price": 2000, "minMinutes": 30, "maxMinutes": 60 } ], "maxDistanceKm": 15, "distanceFactor": 1.3 },
    "rating": { "average": 4.6, "totalRatings": 120, "distribution": { "1": 2, "2": 3, "3": 8, "4": 30, "5": 77 }, "activeReviews": 64 },
    "stats": { "parcelsDelivered": 340, "parcelsLast30Days": 41, "onTimeRate": 92.0, "savedByBuyers": 18, "areasServed": 1, "enoughHistory": true },
    "viewer": { "isFavourite": false, "isOwner": false }
  }
}

```

Never shows documents, owner, commission or reliability details. `contact` carries the public phone, WhatsApp and email from the profile, never the owner's account number. `availability`: `OPEN`, `CLOSED`, `TAKING_A_BREAK` (paused). Until `enoughHistory` show "New shipper".

---

## E2. Reviews

<table id="bkmrk-endpoint-does-post-%7B"><thead><tr><th>Endpoint</th><th>Does</th></tr></thead><tbody><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/businesses/{businessId}/reviews`</td><td>write a review</td></tr><tr><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/shipping/businesses/{businessId}/reviews`</td><td>edit my review</td></tr><tr><td><span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `{base_url}/shipping/businesses/{businessId}/reviews`</td><td>delete my review</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/reviews`</td><td>reviews with text</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/reviews/paged?page=1&size=10`</td><td>paged</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/reviews/my-review`</td><td>mine</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/reviews/summary`</td><td>average + 1..5 distribution</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/businesses/{businessId}/reviews/{reviewId}/reply`</td><td>owner reply `{ "replyText": "…" }` (max 1000)</td></tr></tbody></table>

**Request** (write / edit): `{ "ratingValue": 5, "reviewText": "Fast and careful, thank you!" }` — at least one of the two; text 10–1000.

**Review JSON Sample**:

```json
{ "reviewId": "…", "businessId": "c4bc…", "userId": "…", "userName": "Joshua", "userProfileMedia": null,
  "ratingValue": 5, "reviewText": "Fast and careful, thank you!", "status": "ACTIVE",
  "replyText": "Asante!", "repliedAt": "…", "createdAt": "…", "updatedAt": "…",
  "isMyReview": true, "verifiedDelivery": true }

```

**Errors**: `OWN_BUSINESS`, `REVIEW_EXISTS`, `REVIEW_EMPTY`, `NOT_REVIEWABLE` (not live yet).

---

# Part 3 — Endpoints for shippers and admins

All `…/businesses/{businessId}/…` endpoints below are for **the business owner** (403 / `NOT_YOUR_BUSINESS` for anyone else) unless marked otherwise. A suspended business can read but not change (`BUSINESS_SUSPENDED`).

## F. Register and manage the business

## F1. Register (KYC)

**Purpose**: Part 1 of becoming a shipper. Auto-approved → `KYC_APPROVED` (not live yet).

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/businesses`

**Access Level**: 🔒 Protected (any user)

**Request JSON Sample**:

```json
{
  "name": "Mbezi Boda",
  "contactPhone": "0745051250",
  "office": { "lat": -6.7350, "lng": 39.1180, "landmark": "Near Mbezi Mwisho stand", "building": "Room 4" },
  "businessLicence": { "fileId": "f1…", "number": "BL-2026-00123", "expiresOn": "2027-06-30" },
  "directorNida":    { "fileId": "f2…", "number": "19900101123450000123" },
  "latraLicence":    { "fileId": "f3…", "number": "LATRA-55821", "expiresOn": "2027-01-31" }
}

```

<table id="bkmrk-parameter-type-requi-6"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>name</td><td>string</td><td>Yes</td><td>business name</td><td>max 100</td></tr><tr><td>contactPhone</td><td>string</td><td>Yes</td><td>the phone buyers and sellers call</td><td>valid TZ phone</td></tr><tr><td>office</td><td>object</td><td>Yes</td><td>the office pin (`lat`, `lng`, `landmark` ≤300, `building` ≤100)</td><td>inside a ward</td></tr><tr><td>businessLicence</td><td>object</td><td>Yes</td><td>`fileId` (File Thunder, business document), `number` (unique), `expiresOn`</td><td>number ≤60</td></tr><tr><td>directorNida</td><td>object</td><td>Yes</td><td>`fileId`, `number`</td><td>20 digits</td></tr><tr><td>latraLicence</td><td>object</td><td>Yes</td><td>`fileId`, `number`, `expiresOn`</td><td></td></tr></tbody></table>

**Success Response**: the business (F4), message "Delivery business registered".

**Errors**: `LICENCE_TAKEN`, `NIDA_INVALID`, `PHONE_INVALID`, `DOCUMENT_INVALID`, `DOCUMENT_EXPIRED`, `OUTSIDE_COVERAGE`.

---

## F2. My businesses

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/mine`

**Success Response** `data`: `[{ "id": "c4bc…", "name": "Mbezi Boda", "status": "KYC_APPROVED", "logo": null, "canGoLive": false, "missingToGoLive": ["COVERAGE", "PRICING"] }]`

---

## F3. Replace / open a KYC document

- <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/shipping/businesses/{businessId}/documents/{type}` — body `{ "fileId", "number", "expiresOn" }` → the business.
- <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/documents/{type}` — owner or admin: a short-lived link `{ "type": "LATRA_LICENCE", "mimeType": "application/pdf", "url": "https://…", "expiresInSeconds": 300 }`.

`type`: `BUSINESS_LICENCE`, `DIRECTOR_NIDA`, `LATRA_LICENCE`. **Errors**: `DOCUMENT_NOT_READY`, `DOCUMENT_INVALID`, `DOCUMENT_EXPIRED`, `LICENCE_TAKEN`.

---

## F4. Get the business (owner / admin)

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}`

**Success Response JSON Sample**:

```json
{
  "id": "c4bc…", "ownerId": "3213…", "name": "Mbezi Boda", "contactPhone": "+255745051250",
  "office": { "lat": -6.735, "lng": 39.118, "ward": { "wardName": "Mbezi", "…": "…" }, "areaLabel": "Mbezi, Ubungo, Dar es Salaam",
              "landmark": "Near Mbezi Mwisho stand", "building": "Room 4" },
  "status": "LIVE", "provider": null, "logo": { "fileId": "a1b4…", "status": "READY", "variants": { "lqip": "data:…", "thumb": "https://…", "medium": "https://…", "blurhash": "L53o…" }, "mimeType": "image/png" },
  "description": "Fast boda in Ubungo", "whatsapp": "+255745051250", "email": "hello@mbeziboda.co.tz",
  "servesDoor": true, "servesStation": false,
  "limits": { "maxParcelValue": 2000000, "acceptsBulky": false, "bulkyExtra": null,
              "responseWindowMinutes": 30, "headsUp": true, "stationReachKm": 30 },
  "documents": [ { "type": "LATRA_LICENCE", "number": "LATRA-55821", "expiresOn": "2027-01-31", "fileStatus": "READY" } ],
  "kycApprovedAt": "…", "wentLiveAt": "…", "pausedAt": null, "pauseReason": null,
  "suspendedAt": null, "suspensionReason": null, "createdAt": "…"
}

```

`provider` = `BOLT` for an integrated provider (no owner). **App:** show a banner from `status` + `pauseReason` / `suspensionReason`.

---

## F5. Pause / resume

- <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/businesses/{businessId}/pause` — body optional `{ "reason": "Ramadan break" }` (≤255)
- <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/businesses/{businessId}/resume` — also restarts reliability counting after an automatic pause

Both → the business. Paused = no new quotations or offers; accepted jobs must still be finished. Suspended → only an admin lifts it (`BUSINESS_SUSPENDED`).

---

## F6. My reliability

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/reliability`

**Success Response JSON Sample**:

```json
{
  "businessId": "c4bc…", "status": "LIVE", "statusReason": null, "pausedBySystem": false,
  "countingSince": "2026-10-12T09:00:00", "offersCounted": 24, "graceOffers": 10,
  "acceptanceRate": 88, "missedInARow": 0, "jobsCounted": 21, "onTimeRate": 95,
  "strikes": { "brokeBinding": 0, "atFault": 0, "falseBulkyClaims": 0 },
  "events": [ { "type": "WARNED", "signal": "MISSED_OFFERS", "orderId": "…", "reason": "2 offers missed in a row", "at": "…" } ]
}

```

Rates are null until the grace number is reached.

---

## G. Service setup — `{base_url}/shipping/businesses/{businessId}/setup/…`

## G1. Checklist

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/setup`

```json
{ "businessId": "c4bc…", "status": "KYC_APPROVED", "canGoLive": false,
  "items": [ { "key": "KYC", "done": true, "requiredToGoLive": true, "note": null },
             { "key": "SERVICE_TYPE", "done": true, "requiredToGoLive": true, "note": null },
             { "key": "HOURS", "done": true, "requiredToGoLive": true, "note": null },
             { "key": "COVERAGE", "done": false, "requiredToGoLive": true, "note": "Tick the areas you serve" },
             { "key": "PRICING", "done": false, "requiredToGoLive": true, "note": "Set your door prices and times" },
             { "key": "LIMITS", "done": true, "requiredToGoLive": false, "note": null },
             { "key": "PROFILE", "done": false, "requiredToGoLive": false, "note": "…" } ] }

```

Station businesses also get `STATIONS` and `STATION_PRICES`. The business goes **live by itself** when every required item is done.

## G2. Profile

<span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/setup/profile` — `{ "logoFileId": "…", "description": "…" (≤500), "whatsapp": "…", "email": "…" }` → the business. **Errors**: `LOGO_INVALID`, `PHONE_INVALID`.

## G3. Service type

<span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/setup/service-type` — `{ "door": true, "station": false }` → the business. **Errors**: `SERVICE_TYPE_REQUIRED`.

## G4. Limits

<span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/setup/limits`

```json
{ "maxParcelValue": 2000000, "acceptsBulky": true, "bulkyExtra": 3000,
  "responseWindowMinutes": 30, "headsUp": true, "stationReachKm": 30 }

```

<table id="bkmrk-parameter-descriptio"><thead><tr><th>Parameter</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>maxParcelValue</td><td>most valuable parcel it carries (null = no limit)</td><td>≥ 0</td></tr><tr><td>acceptsBulky / bulkyExtra</td><td>carries bulky parcels, and the extra charged (0 = none)</td><td>extra required when bulky (`BULKY_EXTRA_REQUIRED`)</td></tr><tr><td>responseWindowMinutes</td><td>time to answer an offer</td><td>5–120, default 30</td></tr><tr><td>headsUp</td><td>non-binding "order coming" notices</td><td>default on</td></tr><tr><td>stationReachKm</td><td>station businesses: how far buyers may be to collect</td><td>1–200, default 30</td></tr></tbody></table>

## G5. Working hours

- <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/setup/hours` · <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/setup/hours`

```json
{
  "weekly": [ { "day": "MONDAY", "open": "08:00", "close": "18:00" },
              { "day": "SATURDAY", "open": "09:00", "close": "13:00" } ],
  "specialDays": [ { "date": "2026-12-25", "closed": true, "ranges": [], "note": "Christmas" } ],
  "sameDayCutoff": "16:00"
}

```

Several ranges per day (max 21 in all), close before open = past midnight, open = close = all day; special days ≤60, each up to 3 ranges. Offers count only open time; after the cut-off a same-day job starts the next opening.

## G6. Coverage

- <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/setup/coverage` · <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/setup/coverage` · <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/setup/coverage/outline` (the ticked areas as map shapes, for the read-only map)

**Request JSON Sample**:

```json
{
  "trips": "WITHIN_AND_ACROSS",
  "areas": [ { "level": "REGION", "regionCode": "07" },
             { "level": "DISTRICT", "regionCode": "05", "districtCode": "03" },
             { "level": "WARD", "wardId": 1146 } ]
}

```

<table id="bkmrk-parameter-descriptio-1"><thead><tr><th>Parameter</th><th>Description</th></tr></thead><tbody><tr><td>trips</td><td>`WITHIN_EACH` — both ends in the same ticked area · `WITHIN_AND_ACROSS` — both ends in any ticked areas</td></tr><tr><td>areas</td><td>up to 100, from the location area picker (location doc §1.3)</td></tr></tbody></table>

**Response**: `{ "businessId", "trips", "areas": [AreaResponse], "wardCount": 116 }`. **Errors**: `AREA_NOT_FOUND`, `AREA_OVERLAP` (two ticked areas overlap, e.g. a ward inside a ticked district), `COVERAGE_REQUIRED`.

## G7. Door prices

- <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/setup/pricing` · <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/setup/pricing`

**Request JSON Sample** (bands + value ladder):

```json
{
  "mode": "BANDS",
  "bands": [ { "toKm": 3,  "price": 2000, "minMinutes": 30, "maxMinutes": 60 },
             { "toKm": 7,  "price": 3500, "minMinutes": 60, "maxMinutes": 120 },
             { "toKm": 15, "price": 5000, "minMinutes": 120, "maxMinutes": 180 } ],
  "valueAddons": [ { "upToValue": 100000, "amount": 0 },
                   { "upToValue": 500000, "amount": 1000 },
                   { "percent": 1 } ]
}

```

<table id="bkmrk-parameter-descriptio-2"><thead><tr><th>Parameter</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>mode</td><td>`BANDS` (by distance) or `FLAT`</td><td></td></tr><tr><td>bands</td><td>each starts where the previous ends (first at 0 km); the last `toKm` = max distance</td><td>≤10, toKm 0.1–500, price ≥1, minutes 5–10080</td></tr><tr><td>flat</td><td>`{ "price", "minMinutes", "maxMinutes" }` — price 0 only with a value ladder (value-only pricing)</td><td></td></tr><tr><td>valueAddons</td><td>insurance ladder by parcel value: a fixed `amount` per step, a `percent` allowed on the open top step</td><td>≤10</td></tr></tbody></table>

**Response**: `{ "businessId", "mode", "bands": [{ fromKm, toKm, price, minMinutes, maxMinutes }], "flat", "valueAddons": [{ fromValue, upToValue, amount, percent }], "maxDistanceKm", "distanceFactor": 1.3 }`. New prices apply to new quotations only. **Errors**: `PRICING_INVALID` (message says what), `TIME_RANGE_INVALID`.

---

## H. Stations (station businesses) — `{base_url}/shipping/businesses/{businessId}/setup/…`

<table id="bkmrk-endpoint-does-post-%E2%80%A6"><thead><tr><th>Endpoint</th><th>Does</th></tr></thead><tbody><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/stations`</td><td>add a station</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/stations`</td><td>list</td></tr><tr><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/stations/{stationId}`</td><td>edit</td></tr><tr><td><span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `…/stations/{stationId}`</td><td>remove</td></tr><tr><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/stations/{stationId}/hours`</td><td>the station's own hours (same body as G5)</td></tr><tr><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/station-prices` · <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/station-prices`</td><td>the pair price table</td></tr><tr><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/collection`</td><td>collection from shops</td></tr></tbody></table>

**Station request**:

```json
{ "name": "Magufuli Terminal, gate 3", "phone": "0755000111",
  "pin": { "lat": -6.8402, "lng": 39.1601, "landmark": "Shabiby office, gate 3", "building": null } }

```

**Station response**: `{ "stationId", "businessId", "name", "phone", "lat", "lng", "ward", "areaLabel", "landmark", "building", "hours" }`. The station's phone receives the handover codes for parcels it receives. **Errors**: `NOT_A_STATION_BUSINESS`, `STATION_OUTSIDE_COVERAGE`.

**Station prices request** (the whole table, replaced at once):

```json
{ "pairs": [ { "fromStationId": "s-dar", "toStationId": "s-mbeya", "price": 21000,
               "minMinutes": 720, "maxMinutes": 1440, "bothWays": true } ] }

```

**Response**: every direction between the stations (`price` null = not carried yet, show empty to fill in) + the `collection`. **Errors**: `STATION_NOT_FOUND`, `SAME_STATION`, `PAIR_TWICE`, `TIME_RANGE_INVALID`.

**Collection request**:

```json
{ "collects": true, "fee": 0, "extraMinutes": 120,
  "areas": [ { "level": "DISTRICT", "regionCode": "07", "districtCode": "04" } ] }

```

`collects: false` = parcels reach its stations only through a door shipper. **Errors**: `COLLECTION_INCOMPLETE`.

---

## I. Offers and jobs (the shipper's work)

A **job** is a parcel as the shipper sees it:

```json
{
  "jobId": "j-1", "businessId": "c4bc…", "parcelNumber": "NX-4K7P-2Q", "bulky": false, "valueBand": "UP_TO_500K",
  "from": { "areaLabel": "Kariakoo, Ilala, Dar es Salaam", "wardName": "Kariakoo", "districtName": "Ilala", "regionName": "Dar es Salaam" },
  "to":   { "areaLabel": "Sinza, Ubungo, Dar es Salaam", "wardName": "Sinza", "districtName": "Ubungo", "regionName": "Dar es Salaam" },
  "roadKm": 6.2, "cost": 3500, "commission": 0, "payout": 3500, "payoutStatus": "HELD",
  "minMinutes": 30, "maxMinutes": 60, "arrivalFrom": "…", "arrivalTo": "…",
  "status": "SHIPPER_ACCEPTED", "stage": null, "signature": "SIGNED", "paidAt": "…",
  "details": { "pickup": { "label": "Shoe Shop", "lat": -6.819, "lng": 39.2768, "directions": "…", "phone": "+2557…" },
               "dropoff": { "lat": -6.7735, "lng": 39.2187, "directions": "Blue gate" },
               "receiverName": "Mama Json", "receiverPhone": "+255712345678", "note": "Call when you arrive" },
  "rated": ["SELLER"]
}

```

<table id="bkmrk-field-description-va"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`valueBand`</td><td>`UP_TO_50K`, `UP_TO_500K`, `ABOVE_500K` — never the exact value</td></tr><tr><td>`from` / `to`</td><td>areas only, until accepted</td></tr><tr><td>`details`</td><td>exact places, receiver and note — **only after the shipper accepted**</td></tr><tr><td>`cost` / `commission` / `payout` / `payoutStatus`</td><td>its price, NexGate's cut, what it gets, and whether held / released / refunded</td></tr><tr><td>`stage`</td><td>Upcoming only: `WAITING_FOR_SELLER`, `SELLER_PACKING`</td></tr><tr><td>`signature`</td><td>its party state on the deal: `PENDING`, `SIGNED`, `DECLINED`, `WITHDRAWN`</td></tr><tr><td>`rated`</td><td>parties it already rated privately</td></tr></tbody></table>

## I1. Lists

<table id="bkmrk-endpoint-shows-get-%7B"><thead><tr><th>Endpoint</th><th>Shows</th></tr></thead><tbody><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/upcoming?page=1&size=20`</td><td>paid parcels coming its way, before any offer</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/offers?page=1&size=20`</td><td>open offers with a countdown</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/jobs?status=ACTIVE&page=1&size=20`</td><td>`ACTIVE` (accepted, not done) or `DONE`</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/businesses/{businessId}/earnings?page=1&size=20`</td><td>`{ held, released, refunded, jobs }`</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/jobs/{jobId}`</td><td>one job</td></tr></tbody></table>

Pages start at 1 (`content`, `totalElements`, `totalPages`, …). An **offer**: `{ "offerId", "status": "OPEN", "sentAt", "expiresAt", "job": {…}, "reconfirmNote": null }` — `reconfirmNote` set = a job it already accepted, asked again because its handover point or time moved ("Later than agreed: …").

## I2. Accept an offer

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/offers/{offerId}/accept`

**Access Level**: 🔒 Protected (the business owner)

No body. Signs the deal for that leg — binding from now on.

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Job accepted", "action_time": "2026-10-24T10:30:45",
  "data": { "job": { "jobId": "j-1", "status": "SHIPPER_ACCEPTED", "…": "…" },
            "pickupCode": { "code": "7310", "expiresAt": "2026-10-25T10:30:45", "sentTo": "+255745****50" } }
}

```

`pickupCode` = the code the seller will type at the shop; shown **once** (also by SMS). **Null** until every leg of a route accepted, and for legs that do not collect at the shop.

**Errors**: `OFFER_CLOSED` (expired / withdrawn / answered), `BUSINESS_NOT_LIVE`, `NOT_YOUR_BUSINESS`.

## I3. Reject an offer

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/offers/{offerId}/reject`

**Request**: `{ "reason": "TOO_BUSY", "note": null }` — `TOO_BUSY`, `TOO_FAR`, `NO_VEHICLE`, `CLOSING_SOON`, `PARCEL_TOO_BIG`, `OTHER` (needs a note, ≤300). Message only. Counts in the acceptance rate, never "in a row".

**Errors**: `OFFER_CLOSED`, `REJECT_NOTE_REQUIRED`, `REJECT_REASON_INVALID` (`BULKY_MISMATCH` / `BADLY_PACKED` are reported at the shop with I7).

## I4. Job steps

<table id="bkmrk-step-endpoint-body-w"><thead><tr><th>Step</th><th>Endpoint</th><th>Body</th><th>Who / when</th></tr></thead><tbody><tr><td>Heading to the shop</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/shipping/jobs/{jobId}/heading`</td><td>—</td><td>the leg collecting at the shop, after accepting</td></tr><tr><td>Check the parcel</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/shipping/jobs/{jobId}/check-parcel`</td><td>`{ "parcelNumber": "NX-4K7P-2Q" }`</td><td>at the shop or a handover, before the code; → `{ "yours": true, "message": "✓ this parcel is yours" }`</td></tr><tr><td>Deliver</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/shipping/jobs/{jobId}/deliver`</td><td>`{ "code": "4821" }`</td><td>last leg: the receiver's code at the door, or the buyer's code at the station (`AT_STATION`)</td></tr><tr><td>Hand to the next leg</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/shipping/jobs/{jobId}/hand-over-next`</td><td>`{ "code": "…" }`</td><td>the giver types the next rider's / station counter's code</td></tr><tr><td>Arrived at the station</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/shipping/jobs/{jobId}/arrived`</td><td>—</td><td>station leg at its destination station → `AT_STATION`, sends the next code</td></tr><tr><td>New pickup code</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/shipping/jobs/{jobId}/code`</td><td>—</td><td>the leg collecting at the shop lost its code, before or after tapping heading → message "New pickup code sent"</td></tr><tr><td>My handover code</td><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/shipping/jobs/{jobId}/handover-code`</td><td>—</td><td>a receiving leg / station: show its handover code once (+SMS)</td></tr></tbody></table>

The step endpoints answer with the job (`heading`, `deliver`, `hand-over-next`, `arrived`) or a `{ code, expiresAt, sentTo }`.

**Errors**: `NOT_AT_THE_SHOP`, `NOT_THE_LAST_LEG`, `NOT_A_STATION_ROUTE`, `NO_NEXT_LEG`, `NOT_ARRIVED`, `PARCEL_NOT_RECEIVED`, `CODE_WRONG` (`details.triesLeft`), `CODE_LOCKED`, `CODE_EXPIRED`, `CODE_NOT_ACTIVE`, `CODE_LIMIT`.

## I5. Refuse the parcel at the shop

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/jobs/{jobId}/refuse-parcel`

**Request**: `{ "reason": "TOO_BIG", "note": "Needs a car, it's a mattress" }` — `TOO_BIG` or `BADLY_PACKED`. Only after accepting and before taking the parcel (`REFUSE_NOT_ALLOWED`). Message only. See §1.13.

## I6. Rate the seller or the buyer (private)

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/jobs/{jobId}/rate`

**Request**: `{ "party": "BUYER", "score": 2, "issue": "NO_SHOW", "note": "Waited 20 minutes" }`

<table id="bkmrk-field-values-party-s"><thead><tr><th>Field</th><th>Values</th></tr></thead><tbody><tr><td>party</td><td>`SELLER` (after the hand-over), `BUYER` (after delivery)</td></tr><tr><td>score</td><td>1–5</td></tr><tr><td>issue</td><td>buyer: `WRONG_ADDRESS`, `NOT_REACHABLE`, `NO_SHOW` · seller: `LATE_HANDOVER`, `BADLY_PACKED` · both: `RUDE`, `OTHER` (needs a note)</td></tr></tbody></table>

Message "Thanks, only NexGate sees this". **Errors**: `ALREADY_RATED`, `RATE_NOT_YET`, `ISSUE_NOT_FOR_PARTY`, `NOTE_REQUIRED`.

---

## J. Bolt webhook (Bolt only)

<span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/providers/bolt/webhook` — public, checked by our token in `Authorization`; ride updates from Bolt. Always answers 200 with no body. Not for the app.

---

## K. Admin — `{base_url}/admin/shipping/…`

Body for every action: `{ "reason": "…" (required, ≤500), "shipperAtFault": false }`. Every action is audit-logged.

<table id="bkmrk-endpoint-role-does-g"><thead><tr><th>Endpoint</th><th>Role</th><th>Does</th></tr></thead><tbody><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/businesses?status=&integrated=&regionCode=&districtCode=&wardId=&search=&from=&to=&page=1&size=20`</td><td>staff</td><td>shippers list (with `adminStats { from, to, earned, held, deliveries, rating }`, default last 30 days)</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/businesses/{businessId}/overview?from=&to=`</td><td>staff</td><td>one shipper's page: business, coverage, stations, reliability, stats, jobs `{ active, delivered, missed }`</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/businesses/{businessId}/reliability`</td><td>staff</td><td>as F6, for admins</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/businesses/{businessId}/suspend` · `/lift`</td><td>staff</td><td>stop / restart a shipper (the reason is shown to it)</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/businesses/{businessId}/commission`</td><td>staff</td><td>`{ source: BUSINESS | PLATFORM, calculation, value, history }`</td></tr><tr><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/businesses/{businessId}/commission`</td><td>super</td><td>`{ "percent": 5, "effectiveFrom": "…", "reason": "…" }` — `percent` null = back to the platform rate; never in the past (`COMMISSION_IN_PAST`, `COMMISSION_ORDER`)</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/documents/expiring?days=30`</td><td>staff</td><td>KYC documents expired or expiring, soonest first (`daysLeft` &lt; 0 = expired)</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/operations`</td><td>staff</td><td>stuck orders: `waitingForShipper` (Ready over 1 h), `buyerDecisions`, `problemReports`, `moneyHeldLong` (over 14 days), `boltSearching` (over 10 min) + `counts`; each `{ orderId, orderNumber, parcelNumber, status, since, amount, detail, notes }`</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/notes?targetType=ORDER|BUSINESS&targetId=` · <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/notes`</td><td>staff</td><td>internal notes `{ targetType, targetId, text }` (≤1000), with the admin's name</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/reports?groupBy=REGION|DISTRICT|WARD&regionCode=&districtCode=&from=&to=`</td><td>staff</td><td>by area only: `total`, `areas[] { code, name, deliveries, pickups, onTimeRate, averageCost, boltSpend }`, top 10 `shippers`</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/campaigns?creator=&status=&page=&size=`</td><td>staff</td><td>every campaign + totals (campaigns doc)</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/accounts/{accountId}/party-ratings`</td><td>staff</td><td>what shippers privately said about an account, as buyer and as seller</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/refusals/{refusalId}/false-claim`</td><td>staff</td><td>a "too big" refusal was false → strike (`NOT_A_BULKY_CLAIM`)</td></tr><tr><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/reviews/{reviewId}/status`</td><td>staff</td><td>`{ "status": "HIDDEN", "reason": "…" }`</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/orders/{orderId}/reassign`</td><td>staff</td><td>take the job from the shipper (between Ready and pickup), find another (`REASSIGN_NOT_ALLOWED`, `NOT_DELIVERY`)</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/orders/{orderId}/cancel`</td><td>super</td><td>cancel while the parcel is at the shop; everything refunded (a shipper heading keeps 50%) — after it left: `ADMIN_USE_ESCROW_ACTIONS`</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/escrows/{escrowId}/release` · `/refund`</td><td>super</td><td>settle a stuck / reported order part by hand (`ESCROW_STATE`, `ESCROW_NOT_ON_ORDER`)</td></tr></tbody></table>

Order and escrow actions answer `{ before, after }`. `shipperAtFault` with no accepted shipper → `NO_SHIPPER_TO_BLAME`.

## K2. Integrated providers (Bolt) — `{base_url}/admin/shipping/providers/…`

<table id="bkmrk-endpoint-role-does-g-1"><thead><tr><th>Endpoint</th><th>Role</th><th>Does</th></tr></thead><tbody><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/providers`</td><td>staff</td><td>providers with status, connection, coverage, spent today vs daily limit</td></tr><tr><td><span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `…/providers/{businessId}/coverage`</td><td>super</td><td>`{ "coverage": { "trips", "areas" }, "reason" }` — where Bolt is offered</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/providers/{businessId}/on` · `/off`</td><td>super</td><td>the kill-switch (`COVERAGE_REQUIRED` before on)</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/providers/bolt/rides?page=1&size=20`</td><td>staff</td><td>rides: states, times, held price vs Bolt's receipt (`difference`), rider</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/providers/bolt/rides/{rideId}/state`</td><td>super</td><td>test modes only: move a ride `{ "state": "DRIVER_ON_ROUTE_TO_CLIENT" }` (`BOLT_LIVE`)</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/providers/bolt/status`</td><td>staff</td><td>mode, on/off, limit vs spent today, live / stuck / problem rides, `owed`, this month `paid / receipts / kept`, `lastWebhookAt`</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/providers/bolt/invoices`</td><td>staff</td><td>recorded invoices</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/providers/bolt/invoices`</td><td>super</td><td>`{ "invoiceNumber", "from", "to", "amount", "note" }` → with our `ledgerAmount` and `difference` (`INVOICE_ALREADY_RECORDED`, `INVOICE_PERIOD_INVALID`)</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/providers/bolt/invoices/{invoiceId}/pay`</td><td>super</td><td>`{ "reference": "<bank ref>", "reason" }` — difference settled with revenue, then the bill paid out of `PROVIDER-BOLT`; paying twice changes nothing (`INVOICE_CANNOT_BE_PAID`)</td></tr></tbody></table>

## K3. Audit log

<span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/admin/audit?action=&targetType=&targetId=&adminId=&from=&to=&page=1&size=20` (staff) — every admin action, newest first: `{ id, adminId, adminName, action, targetType, targetId, reason, before, after, at }`. `action`matches its start (`SHIPPING_`, `FINANCE_`, `BOLT_INVOICE`).

---

# Part 4 — Statuses, values, error codes, settings

## 4.1 Fulfillment status (`fulfillment.status`)

<table id="bkmrk-status-pickup-delive"><thead><tr><th>Status</th><th>Pickup</th><th>Delivery</th><th>Means</th></tr></thead><tbody><tr><td>`PLACED`</td><td>✓</td><td>✓</td><td>paid, waiting for the seller to accept</td></tr><tr><td>`ACCEPTED`</td><td>✓</td><td>✓</td><td>seller accepted; parcel number given; packing</td></tr><tr><td>`READY`</td><td>✓</td><td>✓</td><td>pickup: waiting for the buyer · delivery: offers out</td></tr><tr><td>`SHIPPER_ACCEPTED`</td><td></td><td>✓</td><td>every leg accepted; **delivery locked**</td></tr><tr><td>`HEADING_TO_SHOP`</td><td></td><td>✓</td><td>the shipper (or Bolt rider) is on the way to the shop</td></tr><tr><td>`ON_THE_WAY`</td><td></td><td>✓</td><td>handed over at the shop</td></tr><tr><td>`AT_STATION`</td><td></td><td>✓</td><td>waiting at a station (collect, or the next leg)</td></tr><tr><td>`DELIVERED`</td><td></td><td>✓</td><td>delivered / collected at the station; waiting for the buyer's confirm</td></tr><tr><td>`COLLECTED`</td><td>✓</td><td></td><td>collected at the shop; waiting for the buyer's confirm</td></tr><tr><td>`COMPLETED`</td><td>✓</td><td>✓</td><td>buyer confirmed; money released</td></tr><tr><td>`CANCELLED`</td><td>✓</td><td>✓</td><td>see `closeReason`</td></tr><tr><td>`EXPIRED`</td><td>✓</td><td>✓</td><td>not collected in time; refunded</td></tr></tbody></table>

## 4.2 Agreement status (backend; shown through the order)

<table id="bkmrk-draft-pending-agreed"><thead><tr><th>`DRAFT`</th><th>`PENDING`</th><th>`AGREED`</th><th>`DONE`</th><th>`CANCELLED`</th></tr></thead><tbody><tr><td>checkout, editable</td><td>paid, waiting for seller / shippers to sign</td><td>everyone signed</td><td>buyer confirmed</td><td>refunded</td></tr></tbody></table>

## 4.3 Other values

<table id="bkmrk-value-options-fulfil"><thead><tr><th>Value</th><th>Options</th></tr></thead><tbody><tr><td>`FulfillmentType`</td><td>`PICKUP`, `DELIVERY`</td></tr><tr><td>`BusinessStatus`</td><td>`KYC_APPROVED`, `LIVE`, `PAUSED`, `SUSPENDED`</td></tr><tr><td>`TripRule`</td><td>`WITHIN_EACH`, `WITHIN_AND_ACROSS`</td></tr><tr><td>`PricingMode`</td><td>`BANDS`, `FLAT`</td></tr><tr><td>`QuoteRefusal`</td><td>`NO_PRICING`, `TOO_FAR`, `VALUE_TOO_HIGH`, `BULKY_NOT_ACCEPTED`, `NOT_OPEN_SOON`</td></tr><tr><td>`OptionLabel`</td><td>`RECOMMENDED`, `CHEAPEST`, `FASTEST`, `USED_BEFORE`</td></tr><tr><td>`HiddenReason`</td><td>`DOMINATED`, `OUTLIER`, `BEYOND_TOP`</td></tr><tr><td>`SelectionReason`</td><td>`BUYER_CHOICE`, `FAVOURITE`, `RECOMMENDED`</td></tr><tr><td>`ShiftReason`</td><td>`SHOP_PAUSED`, `SHOP_CLOSED`, `SHIPPER_CLOSED`, `CUT_OFF`</td></tr><tr><td>`CartChoiceBy`</td><td>`BUYER`, `DEFAULT`</td></tr><tr><td>`RouteKind`</td><td>`STATION_COLLECTS`, `DOOR_TO_STATION`</td></tr><tr><td>`DecisionReason`</td><td>`NO_SHIPPER`, `COSTS_MORE`, `SLOWER`, `TOO_MANY_CHANGES`, `WAITING_TOO_LONG`, `PARCEL_TOO_BIG`</td></tr><tr><td>`DecisionChoice`</td><td>`USE_NEW_SHIPPER`, `KEEP_WAITING`, `PICKUP`, `END_AT_STATION`, `CANCEL`</td></tr><tr><td>`OfferStatus`</td><td>`OPEN`, `ACCEPTED`, `REJECTED`, `EXPIRED`, `WITHDRAWN`</td></tr><tr><td>`OfferRejectReason`</td><td>`TOO_BUSY`, `TOO_FAR`, `NO_VEHICLE`, `CLOSING_SOON`, `PARCEL_TOO_BIG`, `OTHER` (+ shown only: `BULKY_MISMATCH`, `BADLY_PACKED`)</td></tr><tr><td>`ParcelRefusalReason`</td><td>`TOO_BIG`, `BADLY_PACKED`</td></tr><tr><td>`CodeStatus`</td><td>`ACTIVE`, `USED`, `LOCKED`, `REPLACED`, `EXPIRED`</td></tr><tr><td>`ValueBand`</td><td>`UP_TO_50K`, `UP_TO_500K`, `ABOVE_500K`</td></tr><tr><td>`UpcomingStage`</td><td>`WAITING_FOR_SELLER`, `SELLER_PACKING`</td></tr><tr><td>`JobListStatus`</td><td>`ACTIVE`, `DONE`</td></tr><tr><td>`PartyState`</td><td>`PENDING`, `SIGNED`, `DECLINED`, `WITHDRAWN`</td></tr><tr><td>`RatedParty` / `PartyIssue`</td><td>`BUYER`, `SELLER` / `WRONG_ADDRESS`, `NOT_REACHABLE`, `NO_SHOW`, `LATE_HANDOVER`, `BADLY_PACKED`, `RUDE`, `OTHER`</td></tr><tr><td>`ReliabilitySignal`</td><td>`MISSED_OFFERS`, `ACCEPTANCE_RATE`, `ON_TIME`, `BROKE_BINDING`, `AT_FAULT`, `FALSE_BULKY_CLAIM`, `AUTO_PAUSES`</td></tr><tr><td>`ReliabilityEventType`</td><td>`STRIKE`, `WARNED`, `PAUSED`, `SUSPENDED`</td></tr><tr><td>`BusinessDocumentType`</td><td>`BUSINESS_LICENCE`, `DIRECTOR_NIDA`, `LATRA_LICENCE`</td></tr><tr><td>`ReportLevel` / `NoteTarget`</td><td>`REGION`, `DISTRICT`, `WARD` / `ORDER`, `BUSINESS`</td></tr><tr><td>`BoltMode` / `BoltInvoiceStatus`</td><td>`OFF`, `FAKE`, `SANDBOX`, `LIVE` / `RECORDED`, `PAID`</td></tr></tbody></table>

## 4.4 Fixed rules (backend settings)

<table id="bkmrk-rule-value-seller-ac"><thead><tr><th>Rule</th><th>Value</th></tr></thead><tbody><tr><td>Seller accept window</td><td>3 opening hours</td></tr><tr><td>Offer response window</td><td>15 min, same for every shipper, only while open; closed → waits and rings at opening; closed &gt; 24 h → next shipper</td></tr><tr><td>Replacements per order before the buyer is always asked</td><td>3</td></tr><tr><td>Chain safety net / buyer decision</td><td>24 h / 24 h → pickup</td></tr><tr><td>Re-confirm an accepted leg when its time moves</td><td>&gt; 4 h</td></tr><tr><td>Pickup collection / station collection</td><td>14 days from Ready / 7 days</td></tr><tr><td>Address changes per order</td><td>3 (only before a shipper accepts)</td></tr><tr><td>Quotation price hold</td><td>5 days</td></tr><tr><td>Options shown</td><td>top 5; outlier = more than 3× the cheapest</td></tr><tr><td>Codes</td><td>4 digits, 24 h, 5 wrong tries, 5 new codes per handover per 24 h</td></tr><tr><td>Distance</td><td>straight line × 1.3; add-ons rounded up to 100</td></tr><tr><td>Meeting points</td><td>1 km counts as the same place</td></tr><tr><td>Station reach</td><td>30 km default</td></tr><tr><td>Estimation cache</td><td>1 h</td></tr><tr><td>Favourites</td><td>10</td></tr><tr><td>"New" badge</td><td>30 days after going live</td></tr><tr><td>Rating nudge on ⭐</td><td>shippers with ≥ 5 reviews, up to 5%</td></tr><tr><td>Bolt</td><td>boda, non-bulky, price buffer 2%, polled every 15 s, searching &gt; 10 min → replaced</td></tr><tr><td>Admin alerts</td><td>Ready over 1 h without a shipper, money held over 14 days, digest 07:30</td></tr></tbody></table>

## 4.5 Error codes (HTTP 409, `data.code`)

Location codes (`DROPOFF_INVALID`, `SHOP_LOCATION_REQUIRED`, …) are in `docs/location/location_api_doc.md`; campaign codes in `docs/shipping/campaigns/campaigns_api_doc.md`; checkout codes (`FULFILLMENT_REQUIRED`, `RECEIVER_INCOMPLETE`, `SHOP_CLOSED`) in `commerce_logistics_changes.md` §11c / §22.

<table id="bkmrk-code-meaning-admin_u"><thead><tr><th>Code</th><th>Meaning</th></tr></thead><tbody><tr><td>`ADMIN_USE_ESCROW_ACTIONS`</td><td>The parcel already left the shop; settle it with escrow release / refund</td></tr><tr><td>`AGREEMENT_CLOSED`</td><td>This order is already completed</td></tr><tr><td>`AGREEMENT_FROZEN`</td><td>A problem was reported on this order; support will settle it</td></tr><tr><td>`AGREEMENT_STATE`</td><td>Not possible in the deal's current state</td></tr><tr><td>`ALREADY_DELIVERY`</td><td>This order is already for delivery</td></tr><tr><td>`ALREADY_PICKUP`</td><td>This order is already for pickup</td></tr><tr><td>`ALREADY_RATED`</td><td>You already rated this party on this job</td></tr><tr><td>`AREA_NOT_FOUND`</td><td>One of the areas does not exist</td></tr><tr><td>`AREA_OVERLAP`</td><td>Two ticked areas overlap (e.g. a ward inside a ticked district, or ticked twice)</td></tr><tr><td>`BOLT_CANNOT_CANCEL`</td><td>This ride can no longer be cancelled</td></tr><tr><td>`BOLT_FARE_EXPIRED`</td><td>The Bolt price ran out; estimate again</td></tr><tr><td>`BOLT_LIVE`</td><td>Ride states can only be set in FAKE or SANDBOX mode</td></tr><tr><td>`BOLT_NOT_ASSIGNED`</td><td>Bolt has not assigned a rider yet</td></tr><tr><td>`BOLT_NOT_CONFIGURED`</td><td>Bolt credentials are not set</td></tr><tr><td>`BOLT_NO_RECEIPT`</td><td>This ride has no charge</td></tr><tr><td>`BOLT_OFF`</td><td>Bolt is switched off</td></tr><tr><td>`BOLT_RIDE_BOOKED`</td><td>A Bolt rider is already booked for this address; it can't change now</td></tr><tr><td>`BOLT_RIDE_NOT_FOUND`</td><td>No such Bolt ride</td></tr><tr><td>`BOLT_STOPS_CHANGED`</td><td>Book with the stops that were estimated</td></tr><tr><td>`BOLT_UNAVAILABLE`</td><td>Bolt did not accept the request</td></tr><tr><td>`BULKY_EXTRA_REQUIRED`</td><td>Set the extra you charge for bulky parcels (0 for none)</td></tr><tr><td>`BUSINESS_NOT_LIVE`</td><td>Resume your business before accepting jobs</td></tr><tr><td>`BUSINESS_SUSPENDED`</td><td>This business is suspended; contact NexGate support</td></tr><tr><td>`CAMPAIGN_ENDED`</td><td>At payment: a campaign ended / ran out since checkout (`details` as DELIVERY\_PRICE\_CHANGED) — PATCH the session, then pay</td></tr><tr><td>`CANCEL_NOT_ALLOWED`</td><td>Cancelling is not possible now; the message says what to do instead (e.g. switch to pickup)</td></tr><tr><td>`CANNOT_END_HERE`</td><td>This route cannot end at a station here</td></tr><tr><td>`CHANGE_NOT_ALLOWED`</td><td>A shipper has taken this order; the delivery address can no longer change</td></tr><tr><td>`CODE_EXPIRED`</td><td>This code has expired. Ask for a new code</td></tr><tr><td>`CODE_LIMIT`</td><td>Too many new codes today. Try again tomorrow</td></tr><tr><td>`CODE_LOCKED`</td><td>Too many wrong tries. Ask for a new code</td></tr><tr><td>`CODE_NOT_ACTIVE`</td><td>There is no active code for this handover</td></tr><tr><td>`CODE_NOT_YET`</td><td>Your collection code comes when the parcel reaches the station</td></tr><tr><td>`CODE_WRONG`</td><td>Wrong code (`details.triesLeft`)</td></tr><tr><td>`COLLECTION_INCOMPLETE`</td><td>Set the areas you collect from and your fee (0 for free)</td></tr><tr><td>`COMMISSION_IN_PAST`</td><td>A commission change cannot start in the past</td></tr><tr><td>`COMMISSION_ORDER`</td><td>A commission change must start after the current one</td></tr><tr><td>`COVERAGE_REQUIRED`</td><td>Set the areas the business serves first</td></tr><tr><td>`DECISION_CHOICE_INVALID`</td><td>Choose one of the offered choices</td></tr><tr><td>`DELIVERY_NOT_AVAILABLE`</td><td>No shipper can deliver this parcel to this address</td></tr><tr><td>`DELIVERY_NOT_PAID`</td><td>This leg was free, so it cannot cost more</td></tr><tr><td>`DELIVERY_OPTION_GONE`</td><td>The chosen shipper can no longer deliver (`details`: shopId, businessId, businessName, before, after)</td></tr><tr><td>`DELIVERY_PRICE_CHANGED`</td><td>The delivery price changed since the quotation (`details` as above) — show before → after, retry</td></tr><tr><td>`DESTINATION_CHANGE_LIMIT`</td><td>The address was already changed 3 times; contact support</td></tr><tr><td>`DESTINATION_REQUIRED`</td><td>Add a delivery address first</td></tr><tr><td>`DIGITAL_NO_DELIVERY`</td><td>A digital product needs no delivery</td></tr><tr><td>`DOCUMENT_EXPIRED`</td><td>The document has already expired</td></tr><tr><td>`DOCUMENT_INVALID`</td><td>The document file was not found, is not yours, or failed to upload</td></tr><tr><td>`DOCUMENT_NOT_READY`</td><td>This document cannot be opened right now</td></tr><tr><td>`ESCROW_AMOUNT`</td><td>The escrow amount does not allow this action</td></tr><tr><td>`ESCROW_NOT_ON_ORDER`</td><td>This escrow is not linked to a product order</td></tr><tr><td>`ESCROW_STATE`</td><td>The escrow is not held (already released / refunded)</td></tr><tr><td>`FAVOURITES_LIMIT`</td><td>You can keep up to 10 favourite shippers</td></tr><tr><td>`FULFILLMENT_STATE`</td><td>There is no pickup code to replace for this job</td></tr><tr><td>`INFORM_BUYER_FIRST`</td><td>Confirm that you have already informed the buyer</td></tr><tr><td>`INSTALLMENT_ORDER`</td><td>This order is paid by installments; only its agreement can be cancelled</td></tr><tr><td>`INVOICE_ALREADY_RECORDED`</td><td>This invoice number is already recorded</td></tr><tr><td>`INVOICE_CANNOT_BE_PAID`</td><td>Not enough in PROVIDER-BOLT or PLATFORM-REVENUE to pay this invoice</td></tr><tr><td>`INVOICE_PERIOD_INVALID`</td><td>The period ends before it starts</td></tr><tr><td>`ISSUE_NOT_FOR_PARTY`</td><td>That issue is not about this party (e.g. NO\_SHOW for a seller)</td></tr><tr><td>`ITEMS_REQUIRED`</td><td>Add at least one physical item to quote delivery</td></tr><tr><td>`LAYAWAY_DELIVERY_LATER`</td><td>Layaway plans choose delivery after the last instalment</td></tr><tr><td>`LEG_HAS_SHIPPER`</td><td>This leg still has a shipper</td></tr><tr><td>`LEG_NOT_FOUND`</td><td>This option has no such leg</td></tr><tr><td>`LICENCE_TAKEN`</td><td>A business with this licence number is already registered</td></tr><tr><td>`LOGO_INVALID`</td><td>The logo file was not found</td></tr><tr><td>`NIDA_INVALID`</td><td>The director's NIDA number must have 20 digits</td></tr><tr><td>`NOTE_REQUIRED`</td><td>Say what went wrong</td></tr><tr><td>`NOTHING_TO_CHANGE_BACK`</td><td>There is no earlier address to go back to</td></tr><tr><td>`NOT_ARRIVED`</td><td>Tap Arrived at the station first; that sends the rider's code</td></tr><tr><td>`NOT_AT_THE_SHOP`</td><td>Only the shipper collecting at the shop does this</td></tr><tr><td>`NOT_A_BULKY_CLAIM`</td><td>Only a 'too big' refusal can be a false bulky claim</td></tr><tr><td>`NOT_A_DOOR_LEG`</td><td>To change the station business, choose another option</td></tr><tr><td>`NOT_A_PARTY`</td><td>You are not a party to this agreement</td></tr><tr><td>`NOT_A_PROVIDER`</td><td>This business registered itself; manage it from the shippers list</td></tr><tr><td>`NOT_A_STATION_BUSINESS`</td><td>Tick station in your service type first</td></tr><tr><td>`NOT_A_STATION_ROUTE`</td><td>This job does not end at a station</td></tr><tr><td>`NOT_DELIVERY`</td><td>This order is for pickup; there is no shipper to replace</td></tr><tr><td>`NOT_PICKUP`</td><td>This order is for delivery, not pickup</td></tr><tr><td>`NOT_REVIEWABLE`</td><td>This shipper is not taking orders yet</td></tr><tr><td>`NOT_THE_LAST_LEG`</td><td>Only the shipper at the end of the route does this</td></tr><tr><td>`NOT_YOUR_BUSINESS`</td><td>This job is for another delivery business</td></tr><tr><td>`NOT_YOUR_ORDER`</td><td>Only the seller can do this</td></tr><tr><td>`NOT_YOUR_SHOP`</td><td>This is not your shop</td></tr><tr><td>`NO_BOLT_RIDE`</td><td>No Bolt rider is booked for this order</td></tr><tr><td>`NO_DECISION_NEEDED`</td><td>Nothing is waiting for your decision on this order</td></tr><tr><td>`NO_NEXT_LEG`</td><td>This job ends with the buyer; there is nobody to hand over to</td></tr><tr><td>`NO_SHIPPER_TO_BLAME`</td><td>No shipper has accepted this job, so none broke it</td></tr><tr><td>`OFFER_CLOSED`</td><td>The offer is no longer open (expired, withdrawn or answered)</td></tr><tr><td>`OPTION_NOT_FOUND`</td><td>That option is not part of this quotation</td></tr><tr><td>`OPTION_REQUIRED`</td><td>Choose one of the quotation's options</td></tr><tr><td>`OWN_BUSINESS`</td><td>You cannot review your own delivery business</td></tr><tr><td>`PAIR_TWICE`</td><td>The same direction has two different prices or times</td></tr><tr><td>`PARCEL_NOT_RECEIVED`</td><td>Receive the parcel first</td></tr><tr><td>`PHONE_INVALID`</td><td>The WhatsApp number is not valid</td></tr><tr><td>`PICKUP_TIME_INVALID`</td><td>The shop is closed at that time</td></tr><tr><td>`PLATE_MISMATCH`</td><td>Wrong rider: the message names the plate Bolt sent</td></tr><tr><td>`PRICING_INVALID`</td><td>The price table is not valid (the message says what)</td></tr><tr><td>`PRODUCTS_FROM_DIFFERENT_SHOPS`</td><td>Quote one shop at a time</td></tr><tr><td>`PRODUCT_NOT_AVAILABLE`</td><td>One of the products is not available</td></tr><tr><td>`PRODUCT_NOT_IN_SHOP`</td><td>Choose only products of this shop</td></tr><tr><td>`QUOTATION_EXPIRED`</td><td>These prices are no longer held; ask again for today's prices</td></tr><tr><td>`QUOTATION_OUTDATED`</td><td>Your parcel or address changed since these options; ask again</td></tr><tr><td>`QUOTATION_REPLACED`</td><td>This quotation was replaced by a newer one; ask again</td></tr><tr><td>`RATE_NOT_YET`</td><td>You can rate the buyer once the parcel is delivered</td></tr><tr><td>`READY_CONFIRM_REQUIRED`</td><td>Delivery Ready needs both ticks: packed well, label on the package</td></tr><tr><td>`REASSIGN_NOT_ALLOWED`</td><td>Only between Ready and pickup</td></tr><tr><td>`REFUSE_NOT_ALLOWED`</td><td>Only at the shop, before you take the parcel</td></tr><tr><td>`REJECT_NOTE_REQUIRED`</td><td>Say why you can't take this job</td></tr><tr><td>`REJECT_REASON_INVALID`</td><td>Report the parcel from the job once you are at the shop</td></tr><tr><td>`REVIEW_EMPTY`</td><td>Give a rating or write a review</td></tr><tr><td>`REVIEW_EXISTS`</td><td>You already reviewed this shipper. Update your review instead</td></tr><tr><td>`SAME_STATION`</td><td>A price needs two different stations</td></tr><tr><td>`SERVICE_TYPE_REQUIRED`</td><td>Choose door, station or both</td></tr><tr><td>`SHIPPER_CANNOT_DO_LEG`</td><td>That shipper cannot carry this leg</td></tr><tr><td>`SHIPPER_DELIVERS`</td><td>A shipper delivers this order; use the delivery steps</td></tr><tr><td>`SHIPPER_NOT_FOUND`</td><td>The shipper no longer exists</td></tr><tr><td>`SHOP_NOT_FOUND`</td><td>One of the shops does not exist</td></tr><tr><td>`SHOP_NOT_IN_CART`</td><td>Nothing from this shop in your cart needs pickup or delivery</td></tr><tr><td>`SHOP_REQUIRED`</td><td>Send the shop, or the items to quote</td></tr><tr><td>`STATION_NOT_FOUND`</td><td>One of the stations is not yours</td></tr><tr><td>`STATION_OUTSIDE_COVERAGE`</td><td>The station is not in the areas the business serves</td></tr><tr><td>`STATION_ROUTE_NOT_HERE`</td><td>Collecting at a station can only be chosen at checkout for now; choose a door option</td></tr><tr><td>`STRIKE_INVALID`</td><td>Only broke-binding, at-fault and false bulky claims are strikes</td></tr><tr><td>`SWITCH_NOT_ALLOWED`</td><td>A shipper has taken this order; it can no longer switch to pickup</td></tr><tr><td>`TIME_RANGE_INVALID`</td><td>The shortest time cannot be longer than the longest</td></tr><tr><td>`TOO_MANY_PRODUCTS`</td><td>Too many products in one estimation request</td></tr><tr><td>`USE_PICKUP_FLOW`</td><td>This is a pickup order; use the pickup steps</td></tr><tr><td>`USE_PLATE_CHECK`</td><td>Bolt riders have no code: check the plate and hand over with it</td></tr><tr><td>`WALLET_INSUFFICIENT`</td><td>The wallet does not hold enough for this payment</td></tr></tbody></table>

# Shipping Campaigns API

**Author**: Josh S. Sakweli, Backend Lead Team **Last Updated**: 2026-10-28 **Version**: v1.2

**Base URL**: `https://api.nexgate.co/api/v1`

**Short Description**: A shipping campaign is **someone paying part of a buyer's delivery**, for buyers who meet some rules, for some time — "Free delivery in Dar this weekend", "I pay 50% of delivery", "25% off my deliveries into Kinondoni". Three kinds of creator can run one: a **shipper** (a discount on its own price), a **seller** (paid from the order's own items money) and **NexGate** (paid from a pot of money held in escrow). This doc explains how they are worked out, paid, refunded and managed.

**Related docs**: `docs/shipping/shipping_api_doc.md` (options, cart, checkout, orders) · `docs/location/location_api_doc.md` (areas) · `docs/shipping/campaigns/SHIPPING_CAMPAIGNS_DESIGN.md` (full design with every decision and example) · `commerce_logistics_changes.md` §64–§68 (fields added to existing responses).

**Hints**:

- **`cost.total` everywhere stays the shipper's table price.** What the buyer pays is `offer.buyerPays`; show <s>cost.total</s> **buyerPays** and the shares ("Shop pays 3,000 · NexGate pays 1,800").
- The campaign is **shown** at estimation, **worked out** at the quotation, **paid** at payment and **frozen** after. Nothing is held at quotation time — the buyer may learn at payment that a campaign has just ended (`CAMPAIGN_ENDED`).
- A campaign **never pays more after payment**.
- Coded refusals are HTTP **409** with `data.code`.

---

## Standard Response Format

### Success

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Campaign created",
  "action_time": "2026-10-24T10:30:45",
  "data": { }
}

```

### Error (coded refusal)

```json
{
  "success": false,
  "httpStatus": "CONFLICT",
  "message": "Say the most you pay per delivery (the cap)",
  "action_time": "2026-10-24T10:30:45",
  "data": { "code": "CAMPAIGN_CAP_REQUIRED", "reason": "Say the most you pay per delivery (the cap)" }
}

```

<table id="bkmrk-field-type-descripti"><thead><tr><th>Field</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>`success`</td><td>boolean</td><td>`true` for success, `false` for errors</td></tr><tr><td>`httpStatus`</td><td>string</td><td>HTTP status name</td></tr><tr><td>`message`</td><td>string</td><td>Human-readable result, safe to show</td></tr><tr><td>`action_time`</td><td>string</td><td>When the response was made</td></tr><tr><td>`data`</td><td>object/string</td><td>Payload, or `{ code, reason, details? }`</td></tr></tbody></table>

---

## HTTP Method Badge Standards

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

---

# Part 1 — How campaigns work

## 1.1 Who can run what

<table id="bkmrk-creator-covers-kinds"><thead><tr><th>Creator</th><th>Covers</th><th>Kinds</th><th>Money comes from</th><th>Who manages it</th></tr></thead><tbody><tr><td>**SHIPPER**</td><td>its own deliveries, from any shop</td><td>`PERCENT`, `FIXED` (no `FREE`; free delivery = `PERCENT` 100)</td><td>nowhere — it simply charges less</td><td>the business owner only (not admins)</td></tr><tr><td>**SELLER**</td><td>deliveries of its own shop's orders</td><td>`FREE`, `PERCENT`, `FIXED`</td><td>the order's own items money, at payment</td><td>the shop owner (or a super admin)</td></tr><tr><td>**NEXGATE**</td><td>deliveries of any shop, or chosen shops</td><td>`FREE`, `PERCENT`, `FIXED`</td><td>a **pot** held in escrow, funded from `SHIPPING-CAMPAIGNS`</td><td>super admins</td></tr></tbody></table>

<table id="bkmrk-kind-means-applies-t"><thead><tr><th>Kind</th><th>Means</th><th>Applies to</th></tr></thead><tbody><tr><td>`FREE`</td><td>the whole delivery, up to a `cap` per order</td><td>the **cheapest qualifying option** becomes free; a faster one costs the buyer the difference</td></tr><tr><td>`PERCENT`</td><td>`value`% of the delivery, optional `cap`</td><td>the option the buyer picks</td></tr><tr><td>`FIXED`</td><td>`value` TZS off</td><td>the option the buyer picks</td></tr></tbody></table>

## 1.2 Who qualifies

<table id="bkmrk-rule-field-notes-whe"><thead><tr><th>Rule</th><th>Field</th><th>Notes</th></tr></thead><tbody><tr><td>**Where the parcel goes** (main)</td><td>`areas`</td><td>the buyer's destination: regions / districts / wards; empty = everywhere</td></tr><tr><td>**When** (main)</td><td>`startsAt`, `endsAt`</td><td>start defaults to now; **every campaign needs an end**</td></tr><tr><td>Where it starts</td><td>`fromAreas`</td><td>shipper only</td></tr><tr><td>Minimum order</td><td>`minOrder`</td><td>this shop's items — §1.2a</td></tr><tr><td>Audience</td><td>`audience`</td><td>`EVERYONE` or `FIRST_ORDER`</td></tr><tr><td>Shops</td><td>`shopIds`</td><td>NexGate only (empty = all shops)</td></tr><tr><td>Products</td><td>`productIds` / `excludedProductIds`</td><td>seller only; a mixed parcel qualifies only if every item does</td></tr><tr><td>Per buyer</td><td>`perBuyerLimit`</td><td>e.g. 1 = once per buyer — §1.2a</td></tr><tr><td>Cap per order</td><td>`cap`</td><td>`FREE` and `PERCENT` — §1.2a</td></tr><tr><td>Spending limit</td><td>`spendLimit`</td><td>**seller and shipper, required** — a counter, not money held ("stop after 200,000") — §1.2a</td></tr></tbody></table>

A creator may run several campaigns at once; per order only **one campaign per creator** applies — the one that gives the buyer the most, worked out per option.

**Every campaign has an end date and a total budget**, so its screen and reports can always say "used X of Y, ends on Z": sellers and shippers give `endsAt` and `spendLimit` (`CAMPAIGN_END_REQUIRED`, `CAMPAIGN_LIMIT_REQUIRED`), NexGate gives `endsAt` and `budget`. Everything else is a rule about who qualifies and may be left out (§1.2a).

## 1.2a The four limits: `minOrder`, `perBuyerLimit`, `cap`, `spendLimit`

They answer four questions: **who** qualifies (`minOrder`), **how often** (`perBuyerLimit`), **how much per order**(`cap`) and **how much in total** (`spendLimit`). Example used below: the seller sample in Part 2 §1 — "Free delivery over 50,000", `cap` 5,000, `perBuyerLimit` 2, `spendLimit` 200,000.

<table id="bkmrk-field-means-example-"><thead><tr><th>Field</th><th>Means</th><th>Example</th><th>Left out</th><th>Who can use it</th></tr></thead><tbody><tr><td>`minOrder`</td><td>the buyer's items **from this shop** must add up to at least this; delivery is not counted</td><td>45,000 in the cart → no campaign; 60,000 → applies</td><td>any order size qualifies</td><td>everyone</td></tr><tr><td>`perBuyerLimit`</td><td>how many orders **one buyer** can use this campaign on; a refunded order gives its use back</td><td>2 → the third order pays delivery as normal</td><td>**unlimited**</td><td>everyone</td></tr><tr><td>`cap`</td><td>the most the campaign pays on **one** order</td><td>delivery 4,000 → free; delivery 7,000 → buyer pays 2,000</td><td>no limit per order</td><td>everyone; **required for a seller's `FREE` / `PERCENT`**</td></tr><tr><td>`spendLimit`</td><td>the most the seller or shipper gives away **across all orders**; nothing is set aside, it only counts</td><td>after 200,000 given the campaign shows `RAN_OUT` and its owner is notified; a refund or cancelled delivery lowers the count and it runs again</td><td>**not allowed** — required (`CAMPAIGN_LIMIT_REQUIRED`)</td><td>seller and shipper (NexGate uses `budget`)</td></tr></tbody></table>

**What each is useful for**

- `minOrder` — "free delivery over X": buyers add more to reach it, and the cart shows the nudge *"Add 5,000 more from {shop} for free delivery"*. It also keeps the seller's share small next to the sale.
- `perBuyerLimit` — stops one buyer taking the whole campaign. With `audience: FIRST_ORDER` and 1 it is a welcome offer.
- `cap` — stops one far or bulky delivery eating the budget, and makes the promise clear ("free, up to 5,000").
- `spendLimit` — a monthly budget with no surprises. For a shipper it counts the discount it gives (its own lower price); for a seller the share it pays. NexGate's version is its pot (`budget`), which is real money held.

**Why a seller must give a cap.** The seller's share comes out of that order's items money. With no cap one far delivery could take almost the whole sale (items 50,000, a bulky parcel to Kigoma 45,000 → the seller keeps about 2,500 after commission). So for `FREE` and `PERCENT` the seller says the most they pay (`CAMPAIGN_CAP_REQUIRED`), and with a `minOrder` the cap must fit inside it after commission (`CAMPAIGN_CAP_ABOVE_MINIMUM`). A seller `FIXED` needs no cap — its amount already is the most. Shipper and NexGate caps are optional: a shipper only earns less, NexGate is bounded by its pot.

**On the screen:** offer "No limit" for `perBuyerLimit` (send nothing); `spendLimit` and `endsAt` are always asked. For a seller pre-fill `cap` with a sensible amount they can change (e.g. the usual delivery price in their area) — it is required, so never leave it blank.

**There is no "unlimited" value — an empty optional field is unlimited.** Never ask the user for a big number; show a "No limit" / "Everywhere" / "All" choice and leave the field out. `endsAt`, `spendLimit` (seller, shipper) and `budget`(NexGate) can never be left out.

<table id="bkmrk-field-left-out-means"><thead><tr><th>Field left out</th><th>Means</th></tr></thead><tbody><tr><td>`cap`</td><td>no limit per order (not allowed for a seller's `FREE` / `PERCENT`)</td></tr><tr><td>`minOrder`</td><td>any order size qualifies</td></tr><tr><td>`perBuyerLimit`</td><td>one buyer can use it on every order</td></tr><tr><td>`startsAt`</td><td>starts now</td></tr><tr><td>`areas`</td><td>every destination</td></tr><tr><td>`fromAreas`</td><td>shipper: parcels starting anywhere</td></tr><tr><td>`shopIds`</td><td>NexGate: every shop</td></tr><tr><td>`productIds`</td><td>seller: every product of the shop</td></tr><tr><td>`excludedProductIds`</td><td>seller: no product left out</td></tr><tr><td>`audience`</td><td>`EVERYONE`</td></tr></tbody></table>

**Editing (PUT) sends the whole campaign again.** A field left out on an edit becomes **unlimited / everything** — leaving out `perBuyerLimit` turns "2 per buyer" into no limit, leaving out `areas` makes it run everywhere. Always send back every field the user did not clear; leave one out only when the user chose "No limit". Only `startsAt` keeps its old value when left out.

All four together, with the sample: items 60,000 + delivery 6,000 → the buyer pays **1,000** for delivery (the cap pays 5,000); they can do this twice; the campaign ends on 30 November, or earlier once the seller has given 200,000.

## 1.3 Stacking — when several apply

1. Order: **shipper discount → seller → NexGate**.
2. The shipper's discount sets the real price (`price`); every other share is worked out from **that full price**, never from "what is left".
3. Shares together never exceed the price; the **last one is trimmed** (normally NexGate). The buyer never pays below zero.

<table id="bkmrk-case-seller-nexgate-"><thead><tr><th>Case</th><th>Seller</th><th>NexGate</th><th>Buyer</th></tr></thead><tbody><tr><td>6,000 · seller 50% · NexGate 30%</td><td>3,000</td><td>1,800</td><td>**1,200**</td></tr><tr><td>10,000 · seller 50% at most 3,000 · NexGate 30%</td><td>3,000</td><td>3,000</td><td>**4,000**</td></tr><tr><td>6,000 · seller 70% · NexGate 50%</td><td>4,200</td><td>1,800 (trimmed)</td><td>**0 · Free**</td></tr><tr><td>8,000, shipper 25% off → 6,000 · seller 50% · NexGate 30%</td><td>3,000</td><td>1,800</td><td>**1,200** (the shipper earns 6,000)</td></tr><tr><td>6,000 · NexGate 50% but the pot holds 1,000</td><td>—</td><td>0 (full share or nothing)</td><td>**6,000**</td></tr></tbody></table>

Ranking uses **what the buyer pays** (+ arrival time), so a campaign can make a shipper ⭐ Recommended or 💰 Cheapest.

## 1.4 The offer on an option

Every delivery option (quotation, cart, checkout, order) gains `offer` when a campaign applies (absent otherwise):

```json
"offer": {
  "listPrice": 7000,
  "price": 7000,
  "buyerPays": 1900,
  "shares": [
    { "campaignId": "…", "funder": "SELLER",  "name": "Half delivery in Dar", "amount": 3000 },
    { "campaignId": "…", "funder": "NEXGATE", "name": "Dar 30 percent",       "amount": 2100 }
  ]
}

```

<table id="bkmrk-field-meaning-listpr"><thead><tr><th>Field</th><th>Meaning</th></tr></thead><tbody><tr><td>`listPrice`</td><td>the shipper's table price (= `cost.total`)</td></tr><tr><td>`price`</td><td>after the shipper's own discount — what the shipper is paid</td></tr><tr><td>`shares`</td><td>who pays part of `price`; a `SHIPPER` share is the discount (not money)</td></tr><tr><td>`buyerPays`</td><td>the rest</td></tr></tbody></table>

Product cards show a badge from the estimation's `campaign` field: `{ "listFrom": 7000, "paidBy": ["SELLER", "NEXGATE"] }`→ "Delivery from <s>7,000</s> 1,900 · Shop + NexGate pay part"; `freeDelivery: true` when the cheapest option is free. The cart shows a **nudge** under a shop when a minimum order is near: `"Add 4,995 more from My Shop for free delivery"`.

## 1.5 Where the money sits

**Shipper** — nothing set aside; it earns less per job. Each discount still **counts against its `spendLimit`** when the buyer pays (and at the quotation the discount must fit what is left of it). The count goes back when the delivery does not happen at that price: the order is cancelled or refunded, switched to pickup, the group fails, or the job moves to another shipper (within a minute for cancellations; at once for the switch and the move).

**Seller** — taken **from the order's own money at payment**: items 50,000 + delivery 6,000, seller pays all of the delivery → the buyer pays 50,000, split in escrow into **44,000** items + **6,000** delivery. The shipper is fully covered from payment. Guards so a seller never ends below zero:

- every seller `FREE` / `PERCENT` campaign needs a **cap**;
- with a minimum order, the cap must fit inside it after commission (`CAMPAIGN_CAP_ABOVE_MINIMUM`);
- at the quotation and again at payment the share must fit **this order's items money minus commission**, else the seller's campaign does not apply to that option (full share or nothing);
- with a `spendLimit`, the share must fit what is left of it.

**NexGate** — a **pot** per campaign, held in escrow:

```
real money ──top-up──► PLATFORM-REVENUE ──transfer──► SHIPPING-CAMPAIGNS ──fund / top-up──► campaign pot ──at payment──► the order's delivery part
                         (the only door                       ▲                                   │
                          for outside money)                  └──── leftovers, late refunds ──────┘

```

- Creating a NexGate campaign moves its `budget` from `SHIPPING-CAMPAIGNS` into its pot (`CAMPAIGN_BUDGET_LOW` if short); a **top-up** adds more.
- Each use moves the share from the pot into the order's delivery part **under a lock** — parallel checkouts can never take a pot below zero. **Full share or nothing.**
- Pot empty → **Ran out** (stops by itself); a top-up or a refund restarts it.
- Ended / stopped → whatever is left goes back to `SHIPPING-CAMPAIGNS` at once.

## 1.6 One order, start to finish

<table id="bkmrk-stage-what-happens-e"><thead><tr><th>Stage</th><th>What happens</th></tr></thead><tbody><tr><td>Estimation (card)</td><td>badge only — matching campaigns, nothing exact, nothing held</td></tr><tr><td>Quotation (sheet / cart / checkout)</td><td>the rules run on every option; best campaign per creator; the quotation remembers which it used; **nothing held**</td></tr><tr><td>Payment</td><td>checked again under a lock: still running? pot / limit / items still cover the share? **Yes** → the buyer pays only their part, the shares move into the delivery part. **No** → payment refused `CAMPAIGN_ENDED` (`details`: shopId, businessId, businessName, before, after); nothing charged; `PATCH` the checkout session (same pick) for today's price, then pay</td></tr><tr><td>Recorded</td><td>buyer · seller · NexGate amounts frozen on the delivery escrow — they drive every refund and report</td></tr><tr><td>Delivered + confirmed</td><td>the shipper gets its full price; the seller gets items minus its share (commission on the full items price)</td></tr></tbody></table>

## 1.7 After payment

<table id="bkmrk-change-campaign-mone"><thead><tr><th>Change</th><th>Campaign money</th></tr></thead><tbody><tr><td>Address change (before a shipper accepts)</td><td>each share kept **up to what it paid**; one that no longer applies goes back to its source and the buyer pays it; the buyer tops up / gets back only their own part</td></tr><tr><td>Cheaper shipper on reassignment</td><td>the difference comes back in proportion (pot, seller's items part, buyer)</td></tr><tr><td>Dearer shipper</td><td>shares stay; the buyer pays the extra</td></tr><tr><td>Switch to pickup / cancel / refund</td><td>every share goes back where it came from; the buyer gets back all they paid</td></tr><tr><td>Pickup → delivery after payment</td><td>campaigns apply like at checkout (`CAMPAIGN_ENDED` possible)</td></tr><tr><td>Admin cancel while the rider is heading</td><td>the 50% wasted trip is paid pro rata by everyone in the delivery part</td></tr></tbody></table>

Where a NexGate share goes on a refund:

<table id="bkmrk-campaign-state-at-re"><thead><tr><th>Campaign state at refund</th><th>NexGate's share</th><th>Seller's limit</th></tr></thead><tbody><tr><td>Running / Paused</td><td>back to the pot</td><td>restored</td></tr><tr><td>Ran out</td><td>back to the pot → **Running again**</td><td>restored</td></tr><tr><td>Ended / Cancelled</td><td>back to the pot, moved on to `SHIPPING-CAMPAIGNS` within a minute</td><td>nothing to do</td></tr></tbody></table>

## 1.8 Installments and group purchase

- **Immediate installment:** the seller's share comes from the **down payment** (qualifying uses the full price; the share + commission must fit the down payment, else payment refuses `CAMPAIGN_ENDED` "… pay a bigger down payment"). NexGate and shipper campaigns work as usual.
- **Layaway:** campaigns apply when the buyer chooses delivery after the last instalment.
- **Group purchase:** each member's delivery gets its own campaigns; leaving or a failed group refunds in full and every share goes back.
- A station route (several businesses) gets seller and NexGate shares but no shipper discount.

## 1.9 States

<table id="bkmrk-status-%28stored%29-stat"><thead><tr><th>`status` (stored)</th><th>`state` (shown)</th><th>Means</th></tr></thead><tbody><tr><td>`SCHEDULED`</td><td>`SCHEDULED`</td><td>starts later (`startsAt`)</td></tr><tr><td>`RUNNING`</td><td>`RUNNING` / **`RAN_OUT`**</td><td>live; `RAN_OUT` = pot empty or spending limit used up</td></tr><tr><td>`PAUSED`</td><td>`PAUSED`</td><td>stopped by the creator; resume any time</td></tr><tr><td>`ENDED`</td><td>`ENDED`</td><td>the end date passed (timer, every minute)</td></tr><tr><td>`CANCELLED`</td><td>`CANCELLED`</td><td>stopped for good by the creator</td></tr></tbody></table>

A closed campaign (ended / cancelled) cannot be edited or restarted — create a new one (`CAMPAIGN_CLOSED`). Edits change **new quotations only**; paid orders keep what they got.

**Notifications** to whoever runs it (in-app + push, opens `SHIPPING_CAMPAIGN` with the `campaignId`): `SHIPPING_CAMPAIGN_RAN_OUT` ("Dar 30 percent" ran out · the pot is empty) and `SHIPPING_CAMPAIGN_ENDED`("Dar 30 percent" has ended · It paid 184,000 towards delivery on 96 orders.).

---

# Part 2 — Endpoints

## 1. Create a campaign

**Purpose**: Start a campaign for a shop, a delivery business, or NexGate.

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/campaigns`

**Access Level**: 🔒 Protected — SELLER: the shop owner · SHIPPER: the business owner · NEXGATE: `SUPER_ADMIN`

**Authentication**: Bearer token

**Request JSON Sample** (seller):

```json
{
  "creator": "SELLER",
  "shopId": "aaaa0000-0000-4000-8000-000000000001",
  "name": "Free delivery over 50,000",
  "kind": "FREE",
  "cap": 5000,
  "areas": [ { "level": "REGION", "regionCode": "07" } ],
  "startsAt": "2026-10-25T00:00:00",
  "endsAt": "2026-11-30T23:59:00",
  "minOrder": 50000,
  "audience": "EVERYONE",
  "excludedProductIds": ["77a1…"],
  "perBuyerLimit": 2,
  "spendLimit": 200000
}

```

**Request JSON Sample** (NexGate):

```json
{
  "creator": "NEXGATE",
  "name": "Dar 30 percent",
  "kind": "PERCENT", "value": 30, "cap": 3000,
  "areas": [ { "level": "REGION", "regionCode": "07" } ],
  "endsAt": "2026-11-02T23:59:00",
  "shopIds": [],
  "budget": 500000
}

```

**Request JSON Sample** (shipper — free delivery into Kinondoni, at most 300,000 of discount in total):

```json
{
  "creator": "SHIPPER",
  "businessId": "c4bcb296-98f0-4ca4-9ace-ad7f6df26681",
  "name": "Free into Kinondoni",
  "kind": "PERCENT", "value": 100,
  "areas": [ { "level": "DISTRICT", "regionCode": "07", "districtCode": "01" } ],
  "endsAt": "2026-11-30T23:59:00",
  "spendLimit": 300000
}

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>creator</td><td>enum</td><td>Yes</td><td>`SHIPPER`, `SELLER`, `NEXGATE`</td><td>cannot change later</td></tr><tr><td>shopId</td><td>UUID</td><td>SELLER</td><td>the shop running it</td><td>your shop</td></tr><tr><td>businessId</td><td>UUID</td><td>SHIPPER</td><td>the delivery business running it</td><td>your business</td></tr><tr><td>name</td><td>string</td><td>Yes</td><td>shown to buyers in the shares</td><td>max 80</td></tr><tr><td>kind</td><td>enum</td><td>Yes</td><td>`FREE`, `PERCENT`, `FIXED`</td><td>shipper: no `FREE`</td></tr><tr><td>value</td><td>number</td><td>PERCENT / FIXED</td><td>percent 1–100, or TZS off</td><td>none for `FREE`</td></tr><tr><td>cap</td><td>number</td><td>FREE / PERCENT for sellers</td><td>most paid on one order; left out = no limit (§1.2a)</td><td>≥ 1</td></tr><tr><td>areas</td><td>array</td><td>No</td><td>buyer's destination areas (empty = everywhere)</td><td>≤ 100</td></tr><tr><td>fromAreas</td><td>array</td><td>No</td><td>shipper only: where the parcel starts</td><td>≤ 100</td></tr><tr><td>startsAt / endsAt</td><td>datetime</td><td>endsAt: Yes</td><td>the period</td><td>end after start, in the future</td></tr><tr><td>minOrder</td><td>number</td><td>No</td><td>this shop's items must reach this, delivery not counted (§1.2a)</td><td>≥ 0</td></tr><tr><td>audience</td><td>enum</td><td>No</td><td>`EVERYONE` (default), `FIRST_ORDER`</td><td></td></tr><tr><td>shopIds</td><td>array</td><td>No</td><td>NexGate only: chosen shops</td><td>≤ 500</td></tr><tr><td>productIds / excludedProductIds</td><td>array</td><td>No</td><td>seller only: only these / never these</td><td>own shop's products</td></tr><tr><td>perBuyerLimit</td><td>integer</td><td>No</td><td>orders one buyer can use it on; left out = unlimited (§1.2a)</td><td>≥ 1</td></tr><tr><td>spendLimit</td><td>number</td><td>SELLER / SHIPPER</td><td>most given away across all orders (§1.2a); NexGate: not allowed</td><td>≥ 1</td></tr><tr><td>budget</td><td>number</td><td>NEXGATE</td><td>moved from `SHIPPING-CAMPAIGNS` into the pot</td><td>≥ 1</td></tr></tbody></table>

**Success Response JSON Sample**:

```json
{
  "success": true, "httpStatus": "OK", "message": "Campaign created", "action_time": "2026-10-24T10:30:45",
  "data": {
    "campaignId": "…", "creator": "NEXGATE", "name": "Dar 30 percent", "kind": "PERCENT", "value": 30, "cap": 3000,
    "areas": [ { "level": "REGION", "regionCode": "07", "name": "Dar es Salaam", "label": "Dar es Salaam" } ],
    "startsAt": "2026-10-24T10:30:45", "endsAt": "2026-11-02T23:59:00", "audience": "EVERYONE",
    "state": "RUNNING",
    "numbers": { "orders": 0, "buyers": 0, "givenAway": 0, "returned": 0 },
    "pot": { "accountNumber": "POT-3dd27daf", "funded": 500000, "used": 0, "returned": 0, "left": 500000 },
    "createdAt": "2026-10-24T10:30:45"
  }
}

```

**Success Response Fields**:

<table id="bkmrk-field-description-st"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>`state`</td><td>§1.9</td></tr><tr><td>`numbers`</td><td>orders and buyers that used it; `givenAway` (net of refunds), `returned`</td></tr><tr><td>`pot`</td><td>NexGate only: funded, used, returned, left</td></tr><tr><td>`limit`</td><td>seller and shipper: `{ limit, used }`</td></tr><tr><td>`endedAt`</td><td>when it ended / was stopped</td></tr></tbody></table>

Empty fields are left out of the response.

**Errors**: `CAMPAIGN_KIND_NOT_ALLOWED`, `CAMPAIGN_VALUE_INVALID`, `CAMPAIGN_CAP_REQUIRED`, `CAMPAIGN_CAP_ABOVE_MINIMUM`, `CAMPAIGN_END_REQUIRED`, `CAMPAIGN_LIMIT_REQUIRED`, `CAMPAIGN_DATES_INVALID`, `CAMPAIGN_FIELD_NOT_ALLOWED` (message says which field), `CAMPAIGN_BUDGET_REQUIRED`, `CAMPAIGN_BUDGET_LOW`, `SHOP_REQUIRED`, `BUSINESS_REQUIRED`, `NOT_YOUR_SHOP`, `NOT_YOUR_BUSINESS`, `ADMIN_ONLY`, `AREA_NOT_FOUND`, `SHOP_NOT_FOUND`, `PRODUCT_NOT_IN_SHOP`.

---

## 2. List one creator's campaigns

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/campaigns?creator=SELLER&shopId=…`

**Access Level**: 🔒 Protected (same as create)

**Query Parameters**:

<table id="bkmrk-parameter-type-requi-1"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>creator</td><td>enum</td><td>Yes</td><td>`SELLER`, `SHIPPER`, `NEXGATE`</td></tr><tr><td>shopId</td><td>UUID</td><td>SELLER</td><td>the shop</td></tr><tr><td>businessId</td><td>UUID</td><td>SHIPPER</td><td>the business</td></tr></tbody></table>

**Success Response**: a list of campaigns (as create), newest first.

---

## 3. Get / edit one campaign

- <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/campaigns/{campaignId}`
- <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/shipping/campaigns/{campaignId}` — the whole campaign (same body as create; `creator` must stay the same; `budget` is ignored — use top-up)

**Access Level**: 🔒 Protected (whoever runs it)

Edits apply to new quotations only. Moving `startsAt` into the future makes it `SCHEDULED` again.

**Errors**: as create, plus `CAMPAIGN_CLOSED`, `CAMPAIGN_CREATOR_FIXED`.

---

## 4. Orders that used it

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/shipping/campaigns/{campaignId}/uses?page=1&size=20`

**Access Level**: 🔒 Protected (whoever runs it)

**Success Response** `data` (a page, newest first):

```json
{ "content": [ { "orderId": "…", "orderNumber": "ORD-2026-21597", "amount": 2100, "returned": 0, "at": "2026-10-24T11:02:10" } ],
  "totalElements": 1, "totalPages": 1, "…": "…" }

```

`orderId` / `orderNumber` are null until the order exists (a group purchase only when the group fills).

---

## 5. Pause / resume / stop

<table id="bkmrk-endpoint-does-post-%7B"><thead><tr><th>Endpoint</th><th>Does</th></tr></thead><tbody><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/campaigns/{campaignId}/pause`</td><td>stops for new orders; paid orders keep it; idempotent</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/campaigns/{campaignId}/resume`</td><td>back to `RUNNING` (or `SCHEDULED`); idempotent</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/campaigns/{campaignId}/stop`</td><td>`CANCELLED` for good; a NexGate pot's leftover goes back to `SHIPPING-CAMPAIGNS` at once</td></tr></tbody></table>

**Access Level**: 🔒 Protected (whoever runs it). Each answers with the campaign. **Errors**: `CAMPAIGN_CLOSED`.

---

## 6. Top up a NexGate pot

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/shipping/campaigns/{campaignId}/top-up`

**Access Level**: 🔒 Protected (`SUPER_ADMIN`)

**Request**: `{ "amount": 200000 }` — moved from `SHIPPING-CAMPAIGNS` into the pot; a `RAN_OUT` campaign runs again. Audit-logged.

**Errors**: `CAMPAIGN_HAS_NO_POT` (seller / shipper campaigns), `CAMPAIGN_CLOSED`, `CAMPAIGN_BUDGET_LOW`.

---

## 7. Admin: every campaign

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/admin/shipping/campaigns?creator=&status=&page=1&size=20`

**Access Level**: 🔒 Protected (`STAFF_ADMIN`, `SUPER_ADMIN`) — read only

**Query Parameters**: `creator` (`SHIPPER` / `SELLER` / `NEXGATE`), `status` (`SCHEDULED`, `RUNNING`, `PAUSED`, `ENDED`, `CANCELLED`), `page` (from 1), `size` (≤ 100).

**Success Response** `data`:

```json
{
  "items": [ { "campaignId": "…", "creator": "SELLER", "name": "Free delivery over 50,000", "state": "RUNNING", "…": "…" } ],
  "page": 1, "size": 20, "totalElements": 7, "totalPages": 1,
  "totals": { "byState": { "RUNNING": 4, "ENDED": 2, "RAN_OUT": 1 }, "givenAway": 184000, "returned": 6300, "potsLeft": 412000 }
}

```

`totals` cover everything matching the filter (not just this page); `potsLeft` = money still in pots of campaigns not closed.

---

## 8. Funding: NexGate system accounts — `{base_url}/admin/finance/system-accounts`

**Access Level**: 🔒 Protected (`SUPER_ADMIN`) — every move needs a reason and is audit-logged.

<table id="bkmrk-endpoint-does-get-%E2%80%A6%2F"><thead><tr><th>Endpoint</th><th>Does</th></tr></thead><tbody><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/system-accounts`</td><td>`PLATFORM-REVENUE`, `SHIPPING-CAMPAIGNS`, `PROVIDER-BOLT`, … with balances; revenue also shows `putIn` (owner top-ups) and `transferredOut`</td></tr><tr><td><span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `…/system-accounts/{accountNumber}/entries?page=1&size=20`</td><td>history: `{ entryNumber, type, direction: IN | OUT, amount, other, description, metadata, at }`</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/system-accounts/top-up`</td><td>**real money** NexGate put in → `PLATFORM-REVENUE`: `{ "amount": 1000000, "reference": "<bank / M-Pesa id>", "reason": "…" }` — record only when the money really arrived</td></tr><tr><td><span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `…/system-accounts/transfer`</td><td>`{ "fromAccount": "PLATFORM-REVENUE", "toAccount": "SHIPPING-CAMPAIGNS", "amount": 500000, "reason": "…" }` — the only allowed pair for now</td></tr></tbody></table>

**Errors**: `REFERENCE_ALREADY_USED` (the same reference twice), `TRANSFER_NOT_ALLOWED`, `INSUFFICIENT_BALANCE`. Nothing leaves `SHIPPING-CAMPAIGNS` except into a campaign pot; no account goes below zero.

---

# Part 3 — Values and error codes

<table id="bkmrk-value-options-campai"><thead><tr><th>Value</th><th>Options</th></tr></thead><tbody><tr><td>`CampaignCreator`</td><td>`SHIPPER`, `SELLER`, `NEXGATE` (also the stacking order)</td></tr><tr><td>`CampaignKind`</td><td>`FREE`, `PERCENT`, `FIXED`</td></tr><tr><td>`CampaignAudience`</td><td>`EVERYONE`, `FIRST_ORDER`</td></tr><tr><td>`CampaignStatus` (filter)</td><td>`SCHEDULED`, `RUNNING`, `PAUSED`, `ENDED`, `CANCELLED`</td></tr><tr><td>`CampaignState` (shown)</td><td>the statuses + `RAN_OUT`</td></tr></tbody></table>

<table id="bkmrk-code-when-campaign_k"><thead><tr><th>Code</th><th>When</th></tr></thead><tbody><tr><td>`CAMPAIGN_KIND_NOT_ALLOWED`</td><td>a shipper asked for `FREE`</td></tr><tr><td>`CAMPAIGN_VALUE_INVALID`</td><td>`FREE` with a value, a percent outside 1–100, `FIXED` without an amount</td></tr><tr><td>`CAMPAIGN_CAP_REQUIRED`</td><td>a seller `FREE` / `PERCENT` without a cap</td></tr><tr><td>`CAMPAIGN_CAP_ABOVE_MINIMUM`</td><td>a seller's cap (or fixed amount) is bigger than the minimum order after commission</td></tr><tr><td>`CAMPAIGN_END_REQUIRED`</td><td>a campaign without an end date</td></tr><tr><td>`CAMPAIGN_LIMIT_REQUIRED`</td><td>a seller or shipper campaign without a `spendLimit`</td></tr><tr><td>`CAMPAIGN_DATES_INVALID`</td><td>end not after the start, or in the past</td></tr><tr><td>`CAMPAIGN_FIELD_NOT_ALLOWED`</td><td>a field this creator cannot use (from areas, shops, products; a spending limit on NexGate)</td></tr><tr><td>`CAMPAIGN_BUDGET_REQUIRED`</td><td>a NexGate campaign without a budget</td></tr><tr><td>`CAMPAIGN_BUDGET_LOW`</td><td>`SHIPPING-CAMPAIGNS` holds less than the budget / top-up (message says how much)</td></tr><tr><td>`CAMPAIGN_CLOSED`</td><td>editing, pausing, resuming or topping up an ended / cancelled campaign</td></tr><tr><td>`CAMPAIGN_CREATOR_FIXED`</td><td>changing `creator` on edit</td></tr><tr><td>`CAMPAIGN_HAS_NO_POT`</td><td>top-up on a seller / shipper campaign</td></tr><tr><td>`CAMPAIGN_ENDED`</td><td>at payment: a campaign ended, ran out or no longer fits since checkout (`details` = `{ shopId, businessId, businessName, before, after }`)</td></tr><tr><td>`SHOP_REQUIRED` / `BUSINESS_REQUIRED`</td><td>seller / shipper campaign without its shop / business</td></tr><tr><td>`NOT_YOUR_SHOP` / `NOT_YOUR_BUSINESS` / `ADMIN_ONLY`</td><td>not allowed to run this creator's campaigns</td></tr><tr><td>`AREA_NOT_FOUND` · `SHOP_NOT_FOUND` · `PRODUCT_NOT_IN_SHOP`</td><td>a bad area, shop or product id</td></tr><tr><td>`REFERENCE_ALREADY_USED` · `TRANSFER_NOT_ALLOWED` · `INSUFFICIENT_BALANCE`</td><td>system accounts</td></tr></tbody></table>

# App Fixes — Change Log

**Author**: Josh S. Sakweli, Backend Lead Team **Last Updated**: 2026-10-25 **Version**: v1.0 **Backend version / branch**: 1.2.4 · `fet/location_service` (+ notification server `fet/location_service`, File Thunder `fet/shipping`) **Deployed to**: not yet — staging first **Compared with**: the `staging` branch as deployed (`448f06a0`, 2026-10-06) — "Before" means what the app sees on staging today

**Base URL**: `https://api.nexgate.co/api/v1` (staging: `https://dev.api.nexgate.co/api/v1`)

**Short Description**: Shops now have a real place on the map, buyers keep an address book, and every shop in a checkout is either **pickup at the shop** or **delivery by a shipper** with a real price. This changes existing shop, product, cart, checkout and order endpoints — the old fake shipping fields (`shippingAddressId`, `shippingMethodId`, `trackingNumber`, `carrier`) are gone. The release also carries app fixes: digital downloads, chat avatars, profile cover, donation target, the sign-in alert. Android, iOS and web must update before this goes to production; the admin dashboard has a few changes.

**Audience**: mobile team · web team · admin dashboard

**Related docs** — the **new** endpoints are not repeated here, they live in their own docs:

- `docs/location/location_api_doc.md` — pin → area, area lists, shop location, my addresses, recent pins
- `docs/shipping/shipping_api_doc.md` — delivery options, cart delivery, every pickup / delivery order action, shippers, admin
- `docs/shipping/campaigns/campaigns_api_doc.md` — delivery discounts run by shops, shippers and NexGate
- `notifications_inapp_bell_api_doc.md` — the bell list, `targetType` / `targetId`

Also new since staging, each with its own doc (already shared, not repeated here):

- `event_group_tickets_api_doc.md` — event tickets "buy together": `groupBuying` on tickets, `group` on `POST /e-events/checkout`, ticket groups (open, by code, mine, transfer, withdraw), 4 notifications
- `product_group_purchase_api_doc.md` — product group buys: whole-payment transfer, withdraw, orders always created, true savings, 15-minute expiry

This log covers **what changed in endpoints, fields, rules and notifications that already existed**, plus the few new endpoints that sit inside an existing service and have no other doc.

---

## How to read this

### Change types

<table id="bkmrk-badge-means-app-must"><thead><tr><th>Badge</th><th>Means</th><th>App must act?</th></tr></thead><tbody><tr><td><span style="background-color: #6f42c1; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">NEW</span></td><td>a new endpoint, field or notification</td><td>only to use the new feature</td></tr><tr><td><span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span></td><td>an existing endpoint gained fields or behaves differently; old calls still work</td><td>should update</td></tr><tr><td><span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span></td><td>old calls fail or give a different meaning — a field removed or renamed, a rule tightened</td><td>**must update before the deploy date**</td></tr><tr><td><span style="background-color: #6c757d; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">REMOVED</span></td><td>the endpoint / field / notification is gone</td><td>**must stop using it**</td></tr><tr><td><span style="background-color: #20c997; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">FIX</span></td><td>a bug fixed; same shape, now correct values</td><td>check screens that relied on the wrong value</td></tr></tbody></table>

### HTTP methods

- **GET** - <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span>
- **POST** - <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span>
- **PUT** - <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span>
- **PATCH** - <span style="background-color: #17a2b8; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span>
- **DELETE** - <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span>

### Rules this log follows

- Grouped **by service**. Inside a service: what changed, the flow (when the order of steps changed), the endpoint table, then one block per endpoint.
- Every changed endpoint shows **Before** and **After** for the request and the response — only the parts that changed.
- Samples are short: the changed fields and one or two around them.
- Coded refusals are HTTP **409** with `data.code` (and now, sometimes, `data.details`). New codes are listed per endpoint and again in the index (§16).

---

## 0. At a glance

<table id="bkmrk-%23-service-new-change"><thead><tr><th>\#</th><th>Service</th><th>New</th><th>Changed</th><th>Breaking</th><th>Removed</th><th>App work</th></tr></thead><tbody><tr><td>1</td><td>Shops</td><td>4</td><td>6</td><td>2</td><td>6 fields</td><td>location step after create; opening hours + pause screens; read `location`, `availability`; show review replies</td></tr><tr><td>2</td><td>Products</td><td>—</td><td>3</td><td>—</td><td>—</td><td>Directions on the product page; "Bulky" switch</td></tr><tr><td>3</td><td>Cart</td><td>1</td><td>4</td><td>—</td><td>—</td><td>group by shop, delivery per shop, ticks, `selectedTotal`</td></tr><tr><td>4</td><td>Checkout &amp; payment</td><td>—</td><td>4</td><td>1</td><td>2 request + 2 response fields</td><td>send `fulfillment`; handle price-changed codes</td></tr><tr><td>5</td><td>Orders</td><td>—</td><td>6</td><td>2</td><td>3 fields</td><td>read `fulfillment`; pickup orders use the new order actions</td></tr><tr><td>6</td><td>Installments</td><td>—</td><td>3</td><td>—</td><td>1 field</td><td>delivery for "ships now" plans; cancel via the agreement</td></tr><tr><td>7</td><td>Group purchase</td><td>—</td><td>1</td><td>—</td><td>—</td><td>pickup / delivery in the group sheet</td></tr><tr><td>8</td><td>Wallet &amp; transactions</td><td>—</td><td>1</td><td>—</td><td>—</td><td>new history titles</td></tr><tr><td>9</td><td>Events</td><td>—</td><td>4</td><td>1</td><td>—</td><td>venue pin required to publish; donation progress</td></tr><tr><td>10</td><td>Profile &amp; account</td><td>—</td><td>2</td><td>—</td><td>—</td><td>cover photo</td></tr><tr><td>11</td><td>Interests</td><td>—</td><td>1</td><td>—</td><td>—</td><td>(admin) only admins edit categories</td></tr><tr><td>12</td><td>Chat</td><td>—</td><td>2</td><td>—</td><td>—</td><td>avatars are now real links</td></tr><tr><td>13</td><td>Digital downloads</td><td>—</td><td>1</td><td>—</td><td>—</td><td>save the file as received</td></tr><tr><td>14</td><td>Admin (existing screens)</td><td>1</td><td>2</td><td>—</td><td>—</td><td>review moderation, fee type, reconciliation lines</td></tr><tr><td>15</td><td>Notifications</td><td>26</td><td>9</td><td>—</td><td>—</td><td>handle new types and 4 new targets</td></tr></tbody></table>

## 0.1 Breaking changes — do these first

<table id="bkmrk-service-endpoint-%2F-i"><thead><tr><th>Service</th><th>Endpoint / item</th><th>What breaks</th><th>Do this</th><th>Section</th></tr></thead><tbody><tr><td>Shops</td><td>create / update shop</td><td>`city`, `region`, `streetAddress`, `landmark`, `latitude`, `longitude` no longer exist</td><td>stop sending them; add the **Shop location** step</td><td>§1.2</td></tr><tr><td>Shops</td><td>every shop response, shop search</td><td>the same fields are gone from responses</td><td>read `hasLocation` + `location`</td><td>§1.3, §1.4</td></tr><tr><td>Checkout</td><td>`POST /e-commerce/checkout-sessions`, `PATCH …/{id}`</td><td>`shippingAddressId` / `shippingMethodId` removed; a session with physical items needs `fulfillment`</td><td>send `fulfillment`</td><td>§4.2</td></tr><tr><td>Checkout</td><td>session response</td><td>`shippingAddress` / `shippingMethod` removed</td><td>read `fulfillment`</td><td>§4.3</td></tr><tr><td>Orders</td><td>order detail</td><td>`deliveryAddress`, `trackingNumber`, `carrier` removed</td><td>read `fulfillment`</td><td>§5.2</td></tr><tr><td>Orders</td><td>`/orders/{id}/ship`, `/confirm-delivery`, `/regenerate-code`</td><td>refused for pickup orders and for orders a shipper delivers</td><td>use the shipping order actions</td><td>§5.4</td></tr><tr><td>Orders</td><td>delivery code</td><td>6 digits → **4 digits**, expires after 24 h, wrong code is a coded 409</td><td>4-digit input, handle the codes</td><td>§5.5</td></tr><tr><td>Events</td><td>publish / reveal-location</td><td>an in-person or hybrid event needs a venue **pin**</td><td>pin screen on the venue step</td><td>§9.2</td></tr></tbody></table>

## 0.2 Removed

<table id="bkmrk-service-endpoint-%2F-f"><thead><tr><th>Service</th><th>Endpoint / field / notification</th><th>Use instead</th><th>Section</th></tr></thead><tbody><tr><td>Shops</td><td>request + response fields `city`, `region`, `streetAddress`, `landmark`, `latitude`, `longitude`</td><td>`location` (shop location)</td><td>§1.2–§1.4</td></tr><tr><td>Checkout</td><td>`shippingAddressId`, `shippingMethodId` (request) · `shippingAddress`, `shippingMethod` (response)</td><td>`fulfillment`</td><td>§4.2, §4.3</td></tr><tr><td>Orders</td><td>`deliveryAddress`, `trackingNumber`, `carrier` (detail) · `trackingNumber` on `/ship`</td><td>`fulfillment`</td><td>§5.2</td></tr><tr><td>Installments</td><td>`shippingAddress` on the agreement</td><td>`fulfillment`</td><td>§6.1</td></tr></tbody></table>

---

# 1. Shops

**What changed in this service**: a shop's place is no longer typed text (city, region, landmark). It is a **pin on the map**, turned by the backend into ward / district / region, set with the shop location endpoint (location doc). Every shop response now carries that `location`, and an `availability` block (open now, paused, taking orders). Paused shops stay visible. Shop reviews finally show the owner's reply.

## 1.0 Flow — before and after

**Before**

```mermaid
flowchart LR
    A[Create shop<br/>type city, region, street, landmark, lat/lng] --> B[Shop live]

```

**After**

```mermaid
flowchart LR
    A[Create shop<br/>no location fields] --> B[Shop location step<br/>drop a pin: PUT /shops/id/location] --> C[Shop can sell physical items]
    A -. no location yet .-> D[Physical items refused at checkout:<br/>SHOP_LOCATION_REQUIRED]

```

**What the user notices**: the seller drops a pin instead of typing an address; buyers see "Kariakoo, Ilala, Dar es Salaam" with a Directions and a Call button; shops show "Open now · closes 18:00" or "Paused until …".

## 1.1 Endpoints in this service

<table id="bkmrk-change-method-endpoi"><thead><tr><th>Change</th><th>Method</th><th>Endpoint</th><th>One line</th><th>App</th></tr></thead><tbody><tr><td>BREAKING</td><td>POST</td><td>`/e-commerce/shops`</td><td>location fields removed</td><td>must update</td></tr><tr><td>BREAKING</td><td>PUT</td><td>`/e-commerce/shops/{shopId}`</td><td>location fields removed</td><td>must update</td></tr><tr><td>BREAKING</td><td>GET</td><td>every shop response (profile, detailed, lists, create / update / approve)</td><td>old location fields out, `hasLocation` + `location` + `availability` in</td><td>must update</td></tr><tr><td>BREAKING</td><td>GET</td><td>`/e-commerce/shops/search`</td><td>`city` → `location`</td><td>must update</td></tr><tr><td>CHANGED</td><td>GET</td><td>`/e-commerce/search` (global)</td><td>`shop.location` is now the area name</td><td>check display</td></tr><tr><td>CHANGED</td><td>—</td><td>product pages, search, subscribe, event / post / clip shop links</td><td>paused shops are accepted, not 404</td><td>no change</td></tr><tr><td>CHANGED</td><td>GET</td><td>shop reviews (list, paged, my-review, create / update)</td><td>gain `replyText`, `repliedAt`</td><td>should update</td></tr><tr><td>FIX</td><td>GET</td><td>shop rating, `/summary`</td><td>counts only ACTIVE reviews</td><td>check</td></tr><tr><td>NEW</td><td>PUT</td><td>`/e-commerce/shops/{shopId}/hours`</td><td>set the shop's opening hours</td><td>to use</td></tr><tr><td>NEW</td><td>GET</td><td>`/e-commerce/shops/{shopId}/hours`</td><td>read them</td><td>to use</td></tr><tr><td>NEW</td><td>PUT</td><td>`/e-commerce/shops/{shopId}/pause`</td><td>pause the shop</td><td>to use</td></tr><tr><td>NEW</td><td>DELETE</td><td>`/e-commerce/shops/{shopId}/pause`</td><td>reopen it</td><td>to use</td></tr></tbody></table>

> New, documented elsewhere: shop location `PUT/GET /e-commerce/shops/{shopId}/location` → location doc §6–§7.

---

## 1.2 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Create / update shop — location fields removed

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/e-commerce/shops` · <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/e-commerce/shops/{shopId}`

<table id="bkmrk-change-breaking-in-m"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>BREAKING in meaning — old bodies are still accepted (the fields are ignored) but nothing is saved from them</td></tr><tr><td>**Impact**</td><td>Must update</td></tr><tr><td>**Reference**</td><td>`commerce_logistics_changes.md` §5</td></tr></tbody></table>

**In one line**: the shop's place is no longer part of create / update; set it with the shop location step.

### Request

<table id="bkmrk-field-before-after-n"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`city`, `region`</td><td>**required** on create</td><td>**removed**</td><td></td></tr><tr><td>`streetAddress`, `landmark`, `latitude`, `longitude`</td><td>optional</td><td>**removed**</td><td>landmark + pin now live in the shop location</td></tr><tr><td>`phoneNumber`, `countryCode`, the rest</td><td>unchanged</td><td>unchanged</td><td>`phoneNumber` is also the shop location's phone</td></tr></tbody></table>

<table id="bkmrk-beforeafter-%7B-%22shopn"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{
  "shopName": "Mama Yoyo Shop",
  "phoneNumber": "+255744742944",
  "city": "Dar es Salaam",
  "region": "Dar es Salaam",
  "landmark": "Opposite the clock tower"
}

```

</td><td>```json
{
  "shopName": "Mama Yoyo Shop",
  "phoneNumber": "+255744742944"
}

```

</td></tr></table>

### App to do

- [ ]  Remove city / region / street / landmark / lat / lng inputs from the shop form.
- [ ]  After create, open the **Shop location** step (`PUT …/location`, location doc §6); editing uses the same screen.

---

## 1.3 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Shop responses — `location`, `hasLocation`, `availability`

**Endpoint**: every shop response — `GET /e-commerce/shops/{shopId}`, `/{shopId}/detailed`, `/shops/all`, `/featured`, `/my-shops` (and paged / category forms), create / update / approve.

<table id="bkmrk-change-breaking-%E2%80%94-fi"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>BREAKING — fields removed; new blocks added</td></tr><tr><td>**Impact**</td><td>Must update</td></tr><tr><td>**Reference**</td><td>§6, §21</td></tr></tbody></table>

### Response

<table id="bkmrk-field-before-after-n-1"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`streetAddress`, `city`, `region`</td><td>present</td><td>**removed**</td><td></td></tr><tr><td>`latitude`, `longitude`, `landmark`</td><td>present</td><td>**removed**</td><td></td></tr><tr><td>`hasLocation`</td><td>—</td><td>**added**</td><td>`true` / `false`</td></tr><tr><td>`location`</td><td>—</td><td>**added**</td><td>same object as `GET …/location` (location doc §7), or `null`</td></tr><tr><td>`availability`</td><td>—</td><td>**added**</td><td>open now / paused / taking orders</td></tr></tbody></table>

<table id="bkmrk-beforeafter-%7B-%22shopn-1"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{
  "shopName": "Mama Yoyo Shop",
  "city": "Dar es Salaam",
  "region": "Dar es Salaam",
  "landmark": "Opposite the clock tower",
  "latitude": -6.819, "longitude": 39.2768
}

```

</td><td>```json
{
  "shopName": "Mama Yoyo Shop",
  "hasLocation": true,
  "location": { "lat": -6.819, "lng": 39.2768,
    "areaLabel": "Kariakoo, Ilala, Dar es Salaam",
    "landmark": "Opposite the clock tower",
    "phone": "+255744742944", "…": "…" },
  "availability": { "status": "ACTIVE", "acceptingOrders": true,
    "paused": false, "pauseMode": null, "pausedUntil": null, "pauseReason": null,
    "hours": { "hasHours": true, "openNow": true,
               "closesAt": "2026-10-25T18:00:00+03:00", "nextOpensAt": null } }
}

```

</td></tr></table>

### Behaviour

- `availability.acceptingOrders` is `false` when the shop is paused with `STOP_ORDERS`, suspended or closed → Buy is off.
- `pauseMode`: `KEEP_SELLING` (shows "paused" but orders still come in, accepted later) or `STOP_ORDERS`.
- `hours.openNow` is `null` when the shop has set no hours. All times are East Africa Time with the offset.
- **Paused shops stay visible.** Product pages, product and shop search, subscribe, profile shop counts, linking a shop to an event and shop tags on posts / clips now accept a paused (`TEMPORARILY_OFFLINE`) shop — before, its products 404'd.

### App to do

- [ ]  Show area / map / Directions (`lat,lng` → Google / Apple Maps) / Call (`phone`) from `location`.
- [ ]  Owner: when `hasLocation` is false show "Add your shop location to start receiving orders".
- [ ]  Shop page: "Open now · closes 18:00" / "Opens Mon 08:00" / "Paused until …"; Buy off when `acceptingOrders` is false.

---

## 1.4 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Shop search and global search

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/e-commerce/shops/search` · <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/e-commerce/search?query=…`

<table id="bkmrk-response-field-befor"><thead><tr><th>Response</th><th>Field</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>shop search items</td><td>`city`</td><td>owner-typed text</td><td>**removed**</td></tr><tr><td>shop search items</td><td>`location`</td><td>—</td><td>**added** (location object or `null`)</td></tr><tr><td>global search, `type: "SHOP"`</td><td>`shop.location` (string)</td><td>owner-typed landmark</td><td>the area name, e.g. `"Ubungo, Ubungo, Dar es Salaam"`, or `null`</td></tr></tbody></table>

**Reference**: §7, §8

---

## 1.5 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Shop reviews — the owner's reply is returned

**Endpoint**: shop review list, `/paged`, `/my-review`, create / update responses.

<table id="bkmrk-change-changed-%28%2B-fi"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>CHANGED (+ FIX on the rating)</td></tr><tr><td>**Impact**</td><td>Should update</td></tr><tr><td>**Reference**</td><td>§31</td></tr></tbody></table>

**In one line**: the reply the owner saved with `POST /shops/reviews/{shopId}/{reviewId}/reply` was never returned; now it is.

<table id="bkmrk-field-before-after-r"><thead><tr><th>Field</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>`replyText`, `repliedAt`</td><td>—</td><td>**added** (null when no reply)</td></tr></tbody></table>

**FIX**: the shop's average, rating count and the 5★…1★ breakdown (`/summary`, and the rating on shop responses) counted every review whatever its status; now only **ACTIVE** reviews count, so a hidden review leaves the stars at once.

### App to do

- [ ]  Show the shop's reply under a review when `replyText` is set.

---

## 1.6 <span style="background-color: #6f42c1; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">NEW</span> Shop opening hours

**Purpose**: the hours that drive `availability.hours` ("Open now · closes 18:00"), the seller's 24-opening-hour accept window and the buyer's pickup times.

**Endpoint**: <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/e-commerce/shops/{shopId}/hours` · <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/e-commerce/shops/{shopId}/hours`

**Access Level**: 🔒 PUT: shop owner, or a super / staff admin · GET: any logged-in user

**Authentication**: Bearer token

**Request JSON Sample** (PUT — send the whole week every time; it replaces what was there):

```json
{
  "weekly": [
    { "day": "MONDAY", "open": "08:00", "close": "18:00" },
    { "day": "SATURDAY", "open": "09:00", "close": "13:00" },
    { "day": "SATURDAY", "open": "14:00", "close": "17:00" }
  ],
  "specialDays": [
    { "date": "2026-12-25", "closed": true, "ranges": [], "note": "Christmas" },
    { "date": "2026-12-31", "closed": false, "ranges": [ { "open": "08:00", "close": "12:00" } ] }
  ]
}

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>weekly</td><td>array</td><td>Yes</td><td>`{ day, open, close }`; several ranges per day allowed; a day not listed = closed</td><td>max 21; `day` `MONDAY`…`SUNDAY`; times `HH:mm`</td></tr><tr><td>weekly\[\].close</td><td>time</td><td>Yes</td><td>earlier than `open` = runs past midnight (e.g. 20:00 → 02:00)</td><td></td></tr><tr><td>specialDays</td><td>array</td><td>No</td><td>one date that differs from the week: `closed: true`, or its own `ranges`</td><td>max 60; each date once; not closed → at least one range (max 3)</td></tr><tr><td>specialDays\[\].note</td><td>string</td><td>No</td><td>e.g. "Christmas"</td><td>max 100</td></tr><tr><td>sameDayCutoff</td><td>time</td><td>No</td><td>not used for shops (shippers only)</td><td></td></tr></tbody></table>

**Success Response JSON Sample** (PUT and GET):

```json
{ "success": true, "httpStatus": "OK", "message": "Opening hours saved",
  "data": { "weekly": [ { "day": "MONDAY", "open": "08:00:00", "close": "18:00:00" } ],
            "specialDays": [ { "date": "2026-12-25", "closed": true, "ranges": [], "note": "Christmas" } ],
            "sameDayCutoff": null, "timeZone": "Africa/Dar_es_Salaam", "updatedAt": "2026-10-25T10:12:00" } }

```

**Success Response Fields**:

<table id="bkmrk-field-description-we"><thead><tr><th>Field</th><th>Description</th></tr></thead><tbody><tr><td>weekly, specialDays</td><td>as saved, weekly sorted by day then open time</td></tr><tr><td>timeZone</td><td>always East Africa Time</td></tr></tbody></table>

**Errors**:

<table id="bkmrk-code-%2F-message-statu"><thead><tr><th>Code / message</th><th>Status</th><th>When</th></tr></thead><tbody><tr><td>`HOURS_INVALID`</td><td>409</td><td>a special day listed twice, or not closed and with no hours</td></tr><tr><td>"Only the shop owner can change the shop's hours or pause it"</td><td>403</td><td>not the owner</td></tr><tr><td>"This shop has not set its opening hours yet"</td><td>404</td><td>GET before any hours were saved</td></tr></tbody></table>

**Rules**: a shop with no hours counts as always open (`availability.hours.hasHours: false`, `openNow: null`). The status on shop responses updates at once after a save.

**App to do**:

- [ ]  Seller: "Opening hours" screen (a row per day, add a second range, special days) → PUT the whole thing.

---

## 1.7 <span style="background-color: #6f42c1; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">NEW</span> Pause / reopen the shop

**Purpose**: the seller takes a break — with or without still taking orders.

**Endpoint**: <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/e-commerce/shops/{shopId}/pause` · <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `{base_url}/e-commerce/shops/{shopId}/pause`

**Access Level**: 🔒 shop owner, or a super / staff admin

**Authentication**: Bearer token

**Request JSON Sample** (PUT):

```json
{ "mode": "STOP_ORDERS", "until": "2026-10-28T09:00:00+03:00", "reason": "Stock taking" }

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi-1"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>mode</td><td>enum</td><td>Yes</td><td>`STOP_ORDERS` — checkout refused with `SHOP_CLOSED`; `KEEP_SELLING` — shows "paused" but orders still come in and wait</td><td></td></tr><tr><td>until</td><td>datetime with offset</td><td>No</td><td>reopens by itself at that time (checked every 5 minutes); leave out = until reopened by hand</td><td>must be in the future</td></tr><tr><td>reason</td><td>string</td><td>No</td><td>shown to buyers ("Paused: Stock taking")</td><td>max 255</td></tr></tbody></table>

**Success Response JSON Sample** (PUT "Shop paused", DELETE "Shop reopened") — the `availability` block (§1.3):

```json
{ "success": true, "httpStatus": "OK", "message": "Shop paused",
  "data": { "status": "TEMPORARILY_OFFLINE", "acceptingOrders": false, "paused": true,
            "pauseMode": "STOP_ORDERS", "pausedUntil": "2026-10-28T09:00:00+03:00", "pauseReason": "Stock taking",
            "hours": { "hasHours": true, "openNow": true, "closesAt": "2026-10-25T18:00:00+03:00", "nextOpensAt": null } } }

```

**Errors**:

<table id="bkmrk-code-%2F-message-statu-1"><thead><tr><th>Code / message</th><th>Status</th><th>When</th></tr></thead><tbody><tr><td>`SHOP_NOT_PAUSABLE`</td><td>409</td><td>the shop is neither ACTIVE nor already paused (e.g. SUSPENDED, PENDING, closed)</td></tr><tr><td>"Only the shop owner can change the shop's hours or pause it"</td><td>403</td><td>not the owner</td></tr></tbody></table>

**Rules**:

- Pausing a paused shop replaces its mode / until / reason. DELETE on a shop that is not paused changes nothing and returns its availability.
- A paused shop stays visible everywhere (§1.3).
- `KEEP_SELLING`: orders are not auto-cancelled while paused; their 24-opening-hour accept deadline restarts when the pause ends.

**App to do**:

- [ ]  Seller: "Pause shop" sheet (stop orders / keep selling, optional until, optional reason) and a "Reopen" button.
- [ ]  Buyer: "Paused until …" on the shop page from `availability`.

---

# 2. Products

**What changed in this service**: product responses carry the shop's location (for "Pickup at …" and Directions), a new `bulky` flag tells shippers a parcel is big or heavy, and a refused save no longer half-saves.

## 2.1 Endpoints in this service

<table id="bkmrk-change-method-endpoi-1"><thead><tr><th>Change</th><th>Method</th><th>Endpoint</th><th>One line</th><th>App</th></tr></thead><tbody><tr><td>CHANGED</td><td>GET</td><td>product detail, public view, by slug, shop product lists / filter / search</td><td>gain `shopLocation` / `shop.location`</td><td>should update</td></tr><tr><td>CHANGED</td><td>POST / PUT / PATCH</td><td>create / update product, every product response</td><td>new `bulky`</td><td>should update (seller form)</td></tr><tr><td>FIX</td><td>POST / PUT / PATCH</td><td>create / update / publish / delete / restore</td><td>a refused request changes nothing</td><td>no change</td></tr><tr><td>FIX</td><td>DELETE</td><td>`/e-commerce/products/{shopId}/{productId}/installment-plans/{planId}`</td><td>readable refusal for a used plan</td><td>no change</td></tr></tbody></table>

---

## 2.2 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Product responses — shop location

<table id="bkmrk-response-field-added"><thead><tr><th>Response</th><th>Field added</th></tr></thead><tbody><tr><td>`GET …/products/{productId}/detailed` (owner)</td><td>`shopLocation`</td></tr><tr><td>`GET …/products/{productId}`, by slug (public)</td><td>`shopLocation`</td></tr><tr><td>shop product lists / filter / search (`shop` summary block)</td><td>`shop.location`</td></tr></tbody></table>

Same location object as the shop's, or `null` when the shop has none. **Reference**: §9

```json
"shopLocation": { "lat": -6.7889, "lng": 39.2083, "areaLabel": "Ubungo, Ubungo, Dar es Salaam", "phone": "+255700111222", "…": "…" }

```

### App to do

- [ ]  Product page: "Pickup at Ubungo, Ubungo" + Directions; optionally disable Buy for a physical product when `shopLocation` is `null`.

---

## 2.3 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Products — `bulky`

<table id="bkmrk-before-after-create-"><thead><tr><th></th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>Create (`POST`)</td><td>—</td><td>optional `"bulky": true` (default `false`)</td></tr><tr><td>Update (`PUT` / `PATCH`)</td><td>—</td><td>`"bulky"` changes it; leaving it out keeps it</td></tr><tr><td>Detailed, summary, public responses</td><td>—</td><td>`"bulky": false | true` (next to `condition`)</td></tr></tbody></table>

Shippers that do not carry bulky parcels are left out of its delivery options. The backend also ticks it by itself after two different shippers report the product too big. **Reference**: §19, §45

### App to do

- [ ]  Seller product form: "Bulky / heavy item" switch.

---

## 2.4 <span style="background-color: #20c997; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">FIX</span> Refused product saves / used installment plans

<table id="bkmrk-before-%28wrong%29-after"><thead><tr><th>Before (wrong)</th><th>After (correct)</th></tr></thead><tbody><tr><td>update + publish with no image → refused "At least one product image is required", **but the new name / price were saved**</td><td>a refused create / update / publish / delete / restore changes nothing</td></tr><tr><td>deleting an installment plan buyers used → raw database error</td><td>"Buyers have already used this plan, so it can't be deleted. Deactivate it instead."</td></tr></tbody></table>

**Reference**: §27, §71

---

# 3. Cart

**What changed in this service**: the cart now knows about delivery. It keeps **one delivery address** and, per shop with physical items, **pickup or delivery** with a held price. Each item has a **tick**: checkout buys only ticked items. Adding, changing or removing items answers with what that did to delivery.

## 3.0 Flow — before and after

**Before**

```mermaid
flowchart LR
    A[Add to cart] --> B[Cart: items only] --> C[Checkout: pick address + DHL placeholder] --> D[Pay the whole cart]

```

**After**

```mermaid
flowchart LR
    A[Add to cart<br/>+ pickup / delivery for that shop] --> B[Cart: one address,<br/>a choice per shop, held prices, ticks]
    B --> C[Checkout: takes the cart's choices,<br/>ticked items only] --> D[Pay: items + delivery]
    D --> E[Bought items leave the cart;<br/>unticked ones stay]

```

**What the user notices**: the cart is grouped by shop, each shop shows "Pickup at the shop" or "Delivery by Dar Cargo · TZS 3,500 · Tue–Wed", the total includes delivery, and a change of address re-prices every shop and says what changed.

## 3.1 Endpoints in this service

<table id="bkmrk-change-method-endpoi-2"><thead><tr><th>Change</th><th>Method</th><th>Endpoint</th><th>One line</th><th>App</th></tr></thead><tbody><tr><td>CHANGED</td><td>POST</td><td>`/e-commerce/cart/add`</td><td>optional `fulfillment` + `dropoff`; answers with the delivery change</td><td>should update</td></tr><tr><td>CHANGED</td><td>PUT</td><td>`/e-commerce/cart/items/{itemId}`</td><td>answers with the delivery change</td><td>should update</td></tr><tr><td>CHANGED</td><td>DELETE</td><td>`/e-commerce/cart/items/{itemId}`</td><td>answers with the delivery change</td><td>should update</td></tr><tr><td>CHANGED</td><td>GET</td><td>`/e-commerce/cart`</td><td>gains `destination`, `shops`, ticks, delivery totals</td><td>should update</td></tr><tr><td>CHANGED</td><td>DELETE</td><td>`/e-commerce/cart/clear`</td><td>keeps the delivery address</td><td>no change</td></tr><tr><td>NEW</td><td>PUT</td><td>`/e-commerce/cart/selection`</td><td>tick / untick items</td><td>to use</td></tr><tr><td>FIX</td><td>POST</td><td>`/e-commerce/cart/add`</td><td>two taps at once no longer fail one of them</td><td>no change</td></tr><tr><td>FIX</td><td>—</td><td>after a paid cart checkout</td><td>the bought items now leave the cart</td><td>re-read the cart</td></tr></tbody></table>

> New, documented elsewhere: `PUT /e-commerce/cart/destination`, `POST /e-commerce/cart/destination/change-back`, `PUT /e-commerce/cart/shops/{shopId}/fulfillment` → shipping doc §B.

---

## 3.2 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Add to cart / change / remove an item

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/e-commerce/cart/add` · <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/e-commerce/cart/items/{itemId}` · <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `{base_url}/e-commerce/cart/items/{itemId}`

<table id="bkmrk-change-changed-%E2%80%94-old"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>CHANGED — old bodies still work</td></tr><tr><td>**Impact**</td><td>Should update</td></tr><tr><td>**Reference**</td><td>§32</td></tr></tbody></table>

**In one line**: the product sheet can send the shop's pickup / delivery choice, and every cart change says what it did to delivery.

### Request (add only)

<table id="bkmrk-field-before-after-n-2"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`productId`, `quantity`</td><td>required</td><td>unchanged</td><td></td></tr><tr><td>`fulfillment`</td><td>—</td><td>**added**, optional: `{ type: PICKUP | DELIVERY, quotationId, optionId }`</td><td>the choice from the product sheet</td></tr><tr><td>`dropoff`</td><td>—</td><td>**added**, optional</td><td>same shape as checkout; only when the buyer changed the address in the sheet — it becomes the cart's address</td></tr></tbody></table>

<table id="bkmrk-beforeafter-%7B-%22produ"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{
  "productId": "5f0e…",
  "quantity": 2
}

```

</td><td>```json
{
  "productId": "5f0e…",
  "quantity": 2,
  "fulfillment": { "type": "DELIVERY", "quotationId": "3c1f…", "optionId": "o-1" },
  "dropoff": { "addressId": "9b1d…" }
}

```

</td></tr></table>

### Response (add, change, remove)

<table id="bkmrk-field-before-after-n-3"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`data`</td><td>`null`</td><td>**the delivery change**</td><td>`{ deliveryBefore, deliveryAfter, switchedToPickup, canChangeBack, message, changes }`</td></tr></tbody></table>

<table id="bkmrk-beforeafter-%7B-%22succe"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{ "success": true,
  "message": "Product added to cart successfully",
  "data": null }

```

</td><td>```json
{ "success": true,
  "message": "Product added to cart successfully",
  "data": { "deliveryBefore": 10500, "deliveryAfter": 13000,
            "switchedToPickup": 1, "canChangeBack": false,
            "message": "Delivery 10,500 → 13,000, 1 shop switched to pickup",
            "changes": [ { "shopId": "cfb6…", "shopName": "My Shop",
                           "before": { "type": "DELIVERY", "businessName": "Dar Cargo", "total": 3500 },
                           "after":  { "type": "PICKUP", "businessName": null, "total": 0 },
                           "message": "…" } ] } }

```

</td></tr></table>

### Behaviour

- A sheet quotation that no longer fits (other items, other address, expired) is **not an error**: the item is added and the shop falls back to the cart rules.
- **FIX**: two add-to-cart taps at the same moment for a new product used to fail one of them; now both succeed.

### App to do

- [ ]  Send `fulfillment` (and `dropoff` when changed) from the product sheet.
- [ ]  Show `data.message` after add / change / remove.

---

## 3.3 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Get the cart

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/e-commerce/cart`

<table id="bkmrk-change-changed-%E2%80%94-fie"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>CHANGED — fields added; `cartItems` and `totalAmount` unchanged (items only)</td></tr><tr><td>**Impact**</td><td>Should update</td></tr><tr><td>**Reference**</td><td>§32, §48, §49, §65, §68</td></tr></tbody></table>

### Response

<table id="bkmrk-field-before-after-n-4"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`destination`</td><td>—</td><td>**added**</td><td>the cart's delivery place (pin, `areaLabel`, label) or `null`</td></tr><tr><td>`shops[]`</td><td>—</td><td>**added**</td><td>one per shop with **ticked** physical items (below)</td></tr><tr><td>`cartItems[].selected`</td><td>—</td><td>**added**</td><td>the tick</td></tr><tr><td>`cartSummary.deliveryTotal`</td><td>—</td><td>**added**</td><td>delivery of ticked items, **what the buyer pays**</td></tr><tr><td>`cartSummary.totalWithDelivery`</td><td>—</td><td>**added**</td><td></td></tr><tr><td>`cartSummary.selectedItems`, `selectedQuantity`, `selectedAmount`</td><td>—</td><td>**added**</td><td>ticked items only</td></tr><tr><td>`cartSummary.selectedTotal`</td><td>—</td><td>**added**</td><td>ticked items + their delivery — **the amount to pay**</td></tr></tbody></table>

`shops[]`:

```json
{ "shopId": "cfb6…", "shopName": "My Shop", "itemIds": ["…"],
  "type": "DELIVERY", "chosenBy": "BUYER",
  "quotationId": "3c1f…",
  "selected": { "optionId": "o-1", "businessId": "c4bc…", "name": "Dar Cargo", "logoUrl": "…",
                "reason": "BUYER_CHOICE", "cost": { "total": 7000 }, "eta": { "…": "…" },
                "offer": { "listPrice": 7000, "price": 7000, "buyerPays": 3500, "shares": [ … ] } },
  "pricesHeldUntil": "2026-10-25T14:30:00+03:00",
  "notice": { "code": "NO_ADDRESS", "message": "Add a delivery address to see delivery prices" },
  "nudge": { "campaignId": "…", "funder": "SELLER", "kind": "FREE", "value": null, "addMore": 4995.05,
             "message": "Add 4,995 more from My Shop for free delivery" } }

```

### Behaviour

- Reading the cart refreshes expired or outdated quotations.
- No address → pickup + "Add a delivery address…"; an address nobody covers → pickup + "Delivery is not available to X yet".
- A pickup the **buyer** chose never changes by itself; a pickup set by default turns into delivery once a shipper covers.
- `chosenBy: "BUYER"` ↔ `selected.reason: "BUYER_CHOICE"` now always agree. A shipper picked on an earlier cart shows with the option label **`USED_BEFORE`** (not selected). (§49)
- `selected.offer` (delivery campaigns, campaigns doc): show `buyerPays`, not `cost.total`. `deliveryTotal` and the change messages count what the buyer pays.
- `nudge` appears only while a campaign's minimum order is not reached; it follows the ticked items.
- New items come in ticked; adding more of an unticked item ticks it again.
- `DELETE /cart/clear` keeps `destination`.
- **FIX**: after a paid cart checkout the bought quantities now leave the cart (before: nothing was removed). Units added after the checkout stay; unticked items stay.

### App to do

- [ ]  Group the cart by `shops`; show each shop's choice, `notice`, `nudge`, and "Used before" for `USED_BEFORE`.
- [ ]  A checkbox per item, per shop and "select all" (§3.4); the pay button shows `cartSummary.selectedTotal`.
- [ ]  After a cart payment, re-read the cart instead of clearing it locally.

---

## 3.4 <span style="background-color: #6f42c1; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">NEW</span> Tick / untick cart items

**Purpose**: choose which cart items the next checkout buys.

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

**Access Level**: 🔒 Protected (cart owner)

**Authentication**: Bearer token

**Request JSON Sample**:

```json
{ "itemIds": ["a1b2…", "c3d4…"], "selected": false }

```

**Request Body Parameters**:

<table id="bkmrk-parameter-type-requi-2"><thead><tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th><th>Validation</th></tr></thead><tbody><tr><td>itemIds</td><td>array of uuid</td><td>Yes</td><td>one item, a whole shop's items, or every item</td><td>items of my cart</td></tr><tr><td>selected</td><td>boolean</td><td>Yes</td><td>tick (`true`) or untick (`false`)</td><td></td></tr></tbody></table>

**Success Response**: the same body as `GET /e-commerce/cart` (§3.3).

**Errors**: unknown item → 404 "Cart item not found".

**Rules**: cart checkout (`REGULAR_CART`) takes ticked items only; nothing ticked → "Tick at least one item to check out." A shop with nothing ticked leaves `shops` and keeps its pickup / delivery choice for when it is ticked again. **Reference**: §48

**App to do**:

- [ ]  Checkbox per item, per shop, "select all" → one call each.

---

# 4. Checkout &amp; payment

**What changed in this service**: every shop with physical items in a checkout is **PICKUP** or **DELIVERY**. The fake address and DHL method are gone; `fulfillment` replaces them. Delivery has a real price from a real shipper, held from the quotation; if the price ran out and changed, checkout refuses instead of charging a new price silently. Group purchases and "ships now" installments can now be delivered. The payment response finally separates the seller's money from delivery.

## 4.0 Flow — before and after

**Before**

```mermaid
flowchart LR
    A[Create session<br/>shippingAddressId + shippingMethodId: fake] --> B[Shipping = 0] --> C[Pay: one amount]

```

**After**

```mermaid
flowchart LR
    A[Create session<br/>fulfillment: per shop PICKUP / DELIVERY<br/>+ dropoff + chosen option] --> B{Held price still valid?}
    B -- yes --> C[Pay: items part + delivery part per shop]
    B -- changed / gone / campaign ended --> D[409 with before → after<br/>re-quote, PATCH, pay]
    D --> C

```

**What the user notices**: the buyer picks pickup or delivery per shop, an address, who receives, a note; the total includes delivery; if a price moved they see "was X, now Y" and confirm.

## 4.1 Endpoints in this service

<table id="bkmrk-change-method-endpoi-3"><thead><tr><th>Change</th><th>Method</th><th>Endpoint</th><th>One line</th><th>App</th></tr></thead><tbody><tr><td>BREAKING</td><td>POST</td><td>`/e-commerce/checkout-sessions`</td><td>`fulfillment` replaces `shippingAddressId` / `shippingMethodId`</td><td>must update</td></tr><tr><td>BREAKING</td><td>PATCH</td><td>`/e-commerce/checkout-sessions/{id}`</td><td>same</td><td>must update</td></tr><tr><td>BREAKING</td><td>GET</td><td>checkout session response</td><td>`fulfillment` replaces `shippingAddress` / `shippingMethod`; real delivery in `pricing`</td><td>must update</td></tr><tr><td>CHANGED</td><td>POST</td><td>`/e-commerce/checkout-sessions/{id}/process-payment`, `/retry-payment`</td><td>new refusals; `deliveryAmount` + `parts`</td><td>should update</td></tr><tr><td>FIX</td><td>POST</td><td>same</td><td>`sellerAmount` no longer includes the shipper's money</td><td>check</td></tr></tbody></table>

---

## 4.2 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Create / update a checkout session — `fulfillment`

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/e-commerce/checkout-sessions` · <span style="background-color: #17a2b8; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span> `{base_url}/e-commerce/checkout-sessions/{id}`

<table id="bkmrk-change-breaking-%E2%80%94-tw"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>BREAKING — two fields removed; `fulfillment` required when the session has physical items</td></tr><tr><td>**Impact**</td><td>Must update before the deploy</td></tr><tr><td>**Reference**</td><td>§11c, §33, §55, §56</td></tr></tbody></table>

**In one line**: tell the backend, per shop, pickup or delivery — and where, who receives, and which shipper option.

### Request

<table id="bkmrk-field-before-after-n-5"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`shippingAddressId`</td><td>fake: any uuid gave "John Doe, 123 Main Street"</td><td>**removed**</td><td></td></tr><tr><td>`shippingMethodId`</td><td>fake: always "DHL, Standard Shipping, 0"</td><td>**removed**</td><td></td></tr><tr><td>`fulfillment.byShop`</td><td>—</td><td>**added**</td><td>`shopId → PICKUP | DELIVERY`, one per shop with physical items</td></tr><tr><td>`fulfillment.deliveries`</td><td>—</td><td>**added**</td><td>`shopId → { quotationId, optionId }` — the option from the sheet / cart; missing → today's default shipper</td></tr><tr><td>`fulfillment.dropoff`</td><td>—</td><td>**added**</td><td>required if any shop is DELIVERY — exactly one of `addressId` / `recentId` / `lat`+`lng` (+ `saveAs`, `customLabel`, `directions`)</td></tr><tr><td>`fulfillment.receiver`</td><td>—</td><td>**added**, optional</td><td>`{ name, phone }`; omit = me</td></tr><tr><td>`fulfillment.note`</td><td>—</td><td>**added**, optional</td><td>this order only, max 300</td></tr></tbody></table>

<table id="bkmrk-beforeafter-%7B-%22sessi"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{
  "sessionType": "REGULAR_DIRECTLY",
  "items": [ { "productId": "5f0e…", "quantity": 1 } ],
  "shippingAddressId": "1111…",
  "shippingMethodId": "2222…"
}

```

</td><td>```json
{
  "sessionType": "REGULAR_DIRECTLY",
  "items": [ { "productId": "5f0e…", "quantity": 1 } ],
  "fulfillment": {
    "byShop": { "cfb6…": "DELIVERY" },
    "deliveries": { "cfb6…": { "quotationId": "3c1f…", "optionId": "o-1" } },
    "dropoff": { "addressId": "9b1d…", "directions": "Blue gate" },
    "receiver": { "name": "Mama Json", "phone": "0712345678" },
    "note": "Call when you arrive"
  }
}

```

</td></tr></table>

### Behaviour

- Digital-only checkouts need no `fulfillment`.
- **Cart checkout** (`REGULAR_CART`) may send **no** `fulfillment`: pickup / delivery, the address and the held shipper come from the cart. Sending `fulfillment.dropoff` overrides the cart's address. Only ticked items are bought.
- **Group purchase** accepts DELIVERY (same shape). The group's member totals count items + tax only; each member's delivery is on their own session / order. (§55)
- **Installment**: a plan that ships after the down payment (`IMMEDIATE`) accepts DELIVERY — `pricing` = down payment + the whole delivery. A layaway plan (`AFTER_PAYMENT`) refuses delivery at checkout: `LAYAWAY_DELIVERY_LATER`. (§56)
- A new pin becomes a recent place (and a saved / recent one is marked used) only **after payment**; `saveAs` saves the address at once.
- The fulfillment is **frozen** when the session is created — later edits to the shop location or the address never change it.

### Errors

<table id="bkmrk-code-status-when-bef"><thead><tr><th>Code</th><th>Status</th><th>When</th><th>Before / After</th></tr></thead><tbody><tr><td>`FULFILLMENT_REQUIRED`</td><td>409</td><td>a shop with physical items has no PICKUP / DELIVERY choice</td><td>NEW</td></tr><tr><td>`DROPOFF_REQUIRED`</td><td>409</td><td>a shop is DELIVERY but no `dropoff`</td><td>NEW</td></tr><tr><td>`DROPOFF_INVALID`</td><td>409</td><td>not exactly one of addressId / recentId / pin, or it isn't yours</td><td>NEW</td></tr><tr><td>`RECEIVER_INCOMPLETE`</td><td>409</td><td>receiver name without phone, or the reverse, or a bad phone</td><td>NEW</td></tr><tr><td>`DELIVERY_NOT_AVAILABLE`</td><td>409</td><td>DELIVERY to an address no shipper covers</td><td>NEW</td></tr><tr><td>`SHOP_LOCATION_REQUIRED`</td><td>409</td><td>a physical product from a shop with no location (any session type)</td><td>NEW</td></tr><tr><td>`SHOP_CLOSED`</td><td>409</td><td>an item from a shop paused with STOP\_ORDERS, suspended or closed; `details` `{ shopId, shopName, reopensAt }`</td><td>NEW — before, checkout never checked the shop</td></tr><tr><td>`DELIVERY_PRICE_CHANGED` / `DELIVERY_OPTION_GONE`</td><td>409</td><td>the held price ran out and changed / the shipper can't take it now; `details` `{ shopId, businessId, businessName, before, after }`</td><td>NEW</td></tr><tr><td>`LAYAWAY_DELIVERY_LATER`</td><td>409</td><td>DELIVERY on a layaway installment</td><td>NEW</td></tr><tr><td>`OUTSIDE_COVERAGE`, `LABEL_ALREADY_USED`, `ADDRESS_LIMIT_REACHED`</td><td>409</td><td>from a `saveAs` pin</td><td>NEW</td></tr></tbody></table>

### App to do

- [ ]  Per shop "Pickup at shop / Delivery"; when any delivery: saved address / recent / new pin (+ "Save as"), receiver "Me / Someone else", optional note.
- [ ]  Send `fulfillment` (with `deliveries` from the sheet / cart); for cart checkout it can be left out.
- [ ]  Stop sending `shippingAddressId` / `shippingMethodId`.
- [ ]  On `DELIVERY_PRICE_CHANGED` / `DELIVERY_OPTION_GONE`: show before → after, get a fresh quotation (sheet: ask again; cart: re-read the cart), retry.

---

## 4.3 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Checkout session response — `fulfillment` and real delivery prices

**Endpoint**: the checkout session (create, get, patch).

<table id="bkmrk-change-breaking-%E2%80%94-tw-1"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>BREAKING — two fake blocks removed</td></tr><tr><td>**Impact**</td><td>Must update</td></tr><tr><td>**Reference**</td><td>§1, §11c, §33, §53, §65</td></tr></tbody></table>

### Response

<table id="bkmrk-field-before-after-n-6"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`shippingAddress`</td><td>fake John Doe block</td><td>**removed**</td><td></td></tr><tr><td>`shippingMethod`</td><td>fake DHL block</td><td>**removed**</td><td></td></tr><tr><td>`fulfillment`</td><td>—</td><td>**added**</td><td>`shopId → that shop's fulfillment` (below)</td></tr><tr><td>`pricing.shippingByShop`</td><td>—</td><td>**added**</td><td>`shopId → delivery`, DELIVERY shops only, **what the buyer pays**</td></tr><tr><td>`pricing.shippingCost`, `total`</td><td>shipping always 0</td><td>real</td><td>sum of `shippingByShop`</td></tr></tbody></table>

The fulfillment object (same on the session, the order and the installment agreement):

```json
{ "type": "DELIVERY",
  "pickup":  { "source": "SHOP_LOCATION", "label": "Yoyo Test Shop", "lat": -6.7889, "lng": 39.2083,
               "areaLabel": "Ubungo, Ubungo, Dar es Salaam", "phone": "+255700111222", "…": "…" },
  "dropoff": { "source": "SAVED_ADDRESS", "label": "Home", "lat": -6.77, "lng": 39.25,
               "areaLabel": "Mikocheni, Kinondoni, Dar es Salaam", "directions": "Blue gate", "…": "…" },
  "receiver": { "name": "Mama Json", "phone": "+255712345678" },
  "note": "Call when you arrive",
  "delivery": { "quotationId": "3c1f…", "optionId": "o-1", "businessId": "c4bc…", "businessName": "Dar Cargo",
                "total": 7000, "minMinutes": 120, "maxMinutes": 240, "arrivalFrom": "…", "arrivalTo": "…",
                "pricesHeldUntil": "…", "route": null,
                "offer": { "listPrice": 7000, "price": 7000, "buyerPays": 3500, "shares": [ … ] } } }

```

- `dropoff` and `delivery` are absent for PICKUP. `delivery.total` is what the **shipper** is paid; `offer` shows who paid the rest (campaigns). `route` is set for station routes (shipping doc §1.8).

---

## 4.4 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Process / retry payment

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/e-commerce/checkout-sessions/{id}/process-payment` · `/retry-payment`

<table id="bkmrk-change-changed-%2B-fix"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>CHANGED + FIX</td></tr><tr><td>**Impact**</td><td>Should update</td></tr><tr><td>**Reference**</td><td>§33, §34, §47, §65, §67</td></tr></tbody></table>

### Response

<table id="bkmrk-field-before-after-n-7"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`sellerAmount`</td><td>every held part added together (seller + shipper)</td><td>**the seller's share only**</td><td>FIX</td></tr><tr><td>`deliveryAmount`</td><td>—</td><td>**added**</td><td>the delivery parts' full value</td></tr><tr><td>`parts`</td><td>—</td><td>**added**</td><td>`[{ escrowId, escrowNumber, part: ITEMS | LEG, orderId, amount }]` — one per held part, every shop's order</td></tr><tr><td>`escrowId`, `escrowNumber`, `orderId`, `amountPaid`</td><td></td><td>unchanged</td><td></td></tr></tbody></table>

<table id="bkmrk-before-%28wrong%29after-"><tr><th>Before (wrong)</th><th>After (correct)</th></tr><tr><td>```json
{ "escrowId": "e1…",
  "amountPaid": 16000.99,
  "sellerAmount": 16000.99 }

```

</td><td>```json
{ "escrowId": "e1…",
  "amountPaid": 16000.99,
  "sellerAmount": 1000.99,
  "deliveryAmount": 15000,
  "parts": [ { "part": "ITEMS", "amount": 1000.99, "orderId": "…", "…": "…" },
             { "part": "LEG",   "amount": 15000,   "orderId": "…", "…": "…" } ] }

```

</td></tr></table>

### Behaviour

- The money is held per shop in parts: **ITEMS** (the seller; platform fee on items + tax only) and **LEG** (the shipper, one per leg). A free delivery has no LEG part.
- Buyer transaction history for a split payment reads "N parts" instead of "N sellers".

### Errors

<table id="bkmrk-code-status-when-bef-1"><thead><tr><th>Code</th><th>Status</th><th>When</th><th>Before / After</th></tr></thead><tbody><tr><td>`DELIVERY_OPTION_GONE`</td><td>409</td><td>the chosen shipper stopped taking jobs after the session was made — the session stays open: change the shipper with `PATCH`, pay</td><td>NEW</td></tr><tr><td>`CAMPAIGN_ENDED`</td><td>409</td><td>a delivery campaign ended / ran out since checkout; `details` `{ shopId, businessId, businessName, before, after }`. Nothing charged: `PATCH` the session (same pick) for today's price, then pay</td><td>NEW</td></tr><tr><td>`DELIVERY_PRICE_CHANGED`</td><td>409</td><td>now also when only the buyer's part changed</td><td>CHANGED</td></tr></tbody></table>

### App to do

- [ ]  Show items from `sellerAmount` and delivery from `deliveryAmount`; list each shop's order from `parts`.
- [ ]  Handle `CAMPAIGN_ENDED` like `DELIVERY_PRICE_CHANGED` (before → after, PATCH, pay).

---

# 5. Orders

**What changed in this service**: every physical order has a **fulfillment** — pickup or delivery — with its own status ladder, steps and times. Pickup orders and orders a shipper delivers no longer use the old ship / confirm-delivery / regenerate-code endpoints: they use the shipping order actions (shipping doc §C). The delivery code is 4 digits, comes by its own SMS and lasts 24 h. A buyer's cancel follows clearer rules.

## 5.0 Flow — before and after

**Before**

```mermaid
flowchart LR
    A[Paid] --> B[Seller: /ship<br/>fake tracking number] --> C[Buyer types 6-digit code:<br/>/confirm-delivery] --> D[Money to seller]

```

**After — pickup**

```mermaid
flowchart LR
    A[PLACED] --> B[Seller accepts<br/>ACCEPTED] --> C[Packed & ready<br/>READY + pickup code to buyer] --> D[Seller enters buyer's code<br/>COLLECTED] --> E[Buyer: It's what I ordered<br/>COMPLETED, money released]

```

**After — delivery**

```mermaid
flowchart LR
    A[PLACED] --> B[ACCEPTED] --> C[READY<br/>job offer to shipper] --> D[SHIPPER_ACCEPTED] --> E[HEADING_TO_SHOP] --> F[Hand-over at the shop<br/>ON_THE_WAY, code to receiver] --> G[Rider enters code<br/>DELIVERED] --> H[Buyer confirms<br/>COMPLETED: seller + shipper paid]

```

**What the user notices**: order screens show where the parcel is, the shipper's name and phone, "Code sent by SMS · valid until …", and buttons that depend on the step (Accept, Ready, Hand over, Collect, "It's what I ordered", Report a problem).

## 5.1 Endpoints in this service

<table id="bkmrk-change-method-endpoi-4"><thead><tr><th>Change</th><th>Method</th><th>Endpoint</th><th>One line</th><th>App</th></tr></thead><tbody><tr><td>BREAKING</td><td>GET</td><td>`/e-commerce/orders/{orderId}` (buyer + seller)</td><td>`deliveryAddress` / `trackingNumber` / `carrier` → `fulfillment`</td><td>must update</td></tr><tr><td>CHANGED</td><td>GET</td><td>order lists (buyer `/my-orders…`, shop `/shop/{shopId}/orders…`)</td><td>gain `fulfillmentType`, `fulfillmentStatus`</td><td>should update</td></tr><tr><td>BREAKING</td><td>POST</td><td>`/orders/{orderId}/ship`, `/confirm-delivery`, `/regenerate-code`</td><td>refused for pickup orders and shipper orders; 4-digit code</td><td>must update</td></tr><tr><td>CHANGED</td><td>POST</td><td>`/orders/{orderId}/regenerate-code`</td><td>"I lost my code": new fields, code shown once</td><td>should update</td></tr><tr><td>CHANGED</td><td>POST</td><td>`/orders/{orderId}/cancel`</td><td>pickup / shipper orders follow the new cancel rules; installments refused</td><td>should update</td></tr><tr><td>CHANGED</td><td>—</td><td>`shippingFee`, `totalAmount` on an order</td><td>can change after payment</td><td>check</td></tr></tbody></table>

> New, documented elsewhere: every pickup / delivery order action under `/shipping/orders/{orderId}/…` (accept, ready, pickup-time, code, hand-over, hand-over-rider, collect, confirm, report-problem, delivery-options, switch-to-delivery, change-destination, switch-to-pickup, delivery-decision, cancel) → shipping doc §C.

---

## 5.2 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Order detail and lists — `fulfillment`

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/e-commerce/orders/{orderId}` and the order lists

<table id="bkmrk-change-breaking-%E2%80%94-th"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>BREAKING — three fields removed</td></tr><tr><td>**Impact**</td><td>Must update</td></tr><tr><td>**Reference**</td><td>§11c, §24, §26, §37–§41, §45, §53, §59, §63</td></tr></tbody></table>

### Response

<table id="bkmrk-field-before-after-n-8"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`deliveryAddress`, `trackingNumber`, `carrier`</td><td>text / fake</td><td>**removed**</td><td></td></tr><tr><td>`fulfillment`</td><td>—</td><td>**added** (detail)</td><td>the object from §4.3 plus status, steps and times (below)</td></tr><tr><td>`fulfillmentType`</td><td>—</td><td>**added** (lists)</td><td>`PICKUP` / `DELIVERY`, null for digital</td></tr><tr><td>`fulfillmentStatus`</td><td>—</td><td>**added** (lists)</td><td></td></tr><tr><td>`productOrderStatus`</td><td></td><td>kept</td><td>still works; for pickup / shipper orders it follows the fulfillment steps</td></tr></tbody></table>

<table id="bkmrk-beforeafter-%7B-%22order"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{ "orderNumber": "ORD-2026-94070",
  "productOrderStatus": "SHIPPED",
  "deliveryAddress": "123 Main Street",
  "trackingNumber": "TRACK-8F2A",
  "carrier": "DHL" }

```

</td><td>```json
{ "orderNumber": "ORD-2026-94070",
  "productOrderStatus": "SHIPPED",
  "fulfillment": {
    "type": "DELIVERY", "status": "ON_THE_WAY",
    "parcelNumber": "NX-48213",
    "placedAt": "…", "acceptedAt": "…", "readyAt": "…", "pickedUpAt": "…",
    "code": { "status": "ACTIVE", "expiresAt": "2026-10-26T09:12:00" },
    "shippers": [ { "leg": 1, "name": "Dar Cargo", "phone": "+255745051250" } ],
    "delivery": { "businessName": "Dar Cargo", "total": 7000, "…": "…" },
    "decision": null, "needsShipperSince": null, "…": "…" } }

```

</td></tr></table>

### `fulfillment` keys added beyond §4.3

<table id="bkmrk-key-meaning-status-p"><thead><tr><th>Key</th><th>Meaning</th></tr></thead><tbody><tr><td>`status`</td><td>pickup: `PLACED → ACCEPTED → READY → COLLECTED → COMPLETED`; delivery: `PLACED → ACCEPTED → READY → SHIPPER_ACCEPTED → HEADING_TO_SHOP → ON_THE_WAY → (AT_STATION) → DELIVERED → COMPLETED`; or `CANCELLED` / `EXPIRED`</td></tr><tr><td>`parcelNumber`, `pickupTime`</td><td>parcel number from Accept; buyer's planned pickup time</td></tr><tr><td>`placedAt`, `acceptedAt`, `readyAt`, `collectedAt`, `headingAt`, `pickedUpAt`, `deliveredAt`, `completedAt`, `closedAt`</td><td>step times, absent until set</td></tr><tr><td>`acceptBy`, `collectBy`</td><td>deadlines (24 opening hours to accept; 14 days to collect)</td></tr><tr><td>`closeReason`</td><td>e.g. `NOT_ACCEPTED_IN_TIME`, `NOT_COLLECTED_IN_TIME`, `ADMIN_REFUNDED`, `ADMIN_CANCELLED`</td></tr><tr><td>`code`</td><td>`{ status: ACTIVE | USED | LOCKED | EXPIRED | REPLACED, expiresAt }` — detail only, never the code itself</td></tr><tr><td>`packedConfirmedAt`, `labelConfirmedAt`</td><td>the seller's Ready ticks</td></tr><tr><td>`needsShipperSince`</td><td>the shipper said no and a new one is being found</td></tr><tr><td>`decision`</td><td>the buyer must choose (new shipper costs more, nobody found, …) — shipping doc §1.11</td></tr><tr><td>`refusal`</td><td>the latest shipper refusal at the shop (`TOO_BIG` / `BADLY_PACKED`)</td></tr><tr><td>`shippers`</td><td>one per leg whose shipper accepted: `{ leg, businessId, name, phone }` (not for Bolt)</td></tr><tr><td>`rider`</td><td>Bolt only: `driverName`, `driverPhone`, `driverPicture`, `plate`, `vehicleModel`, `trackingUrl`, `etaToShopMinutes`, `state`</td></tr></tbody></table>

### Behaviour

- Existing orders were copied over: PENDING\_SHIPMENT → `PLACED`, SHIPPED / DELIVERED / DISPUTED → `READY`, COMPLETED → `COMPLETED`, CANCELLED / REFUNDED → `CANCELLED`.
- Automatic closing: a pickup or delivery order not accepted within **24 opening hours** is cancelled; a pickup not collected **14 days** after Ready becomes `EXPIRED`. Both refund in full; the order shows `CANCELLED` with no `cancelledBy`.
- **`shippingFee` and `totalAmount` can change after payment** (another shipper at another price; 0 after switching to pickup). `shippingFee` is what the buyer paid for delivery.
- For now the seller sees the full drop-off (pin, directions, receiver phone).

### App to do

- [ ]  Read `fulfillment` instead of `deliveryAddress` / `trackingNumber` / `carrier`; pickup orders show the shop's place + Directions.
- [ ]  Show `fulfillment.status` and the step times; lists show the `fulfillmentType` badge and `fulfillmentStatus`.
- [ ]  A Call button per entry in `shippers`; a rider card (photo, plate, Track) for Bolt.

---

## 5.3 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Cancel an order

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/e-commerce/orders/{orderId}/cancel`

<table id="bkmrk-change-changed-%E2%80%94-rul"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>CHANGED — rules for pickup orders and orders a shipper delivers</td></tr><tr><td>**Impact**</td><td>Should update</td></tr><tr><td>**Reference**</td><td>§25, §34, §43, §69</td></tr></tbody></table>

<table id="bkmrk-who-before-after-%28pi"><thead><tr><th>Who</th><th>Before</th><th>After (pickup orders and shipper orders)</th></tr></thead><tbody><tr><td>Buyer</td><td>any time before shipped</td><td>only before the seller accepts (`PLACED`), or while the delivery has no shipper (`needsShipperSince` / a `decision` waiting)</td></tr><tr><td>Seller</td><td>any time before delivered</td><td>pickup: until collected; delivery: only before Ready. Body `{ "informedBuyer": true, "reason"? }`</td></tr><tr><td>Refund</td><td>the order's single escrow</td><td>**every** part (items + delivery), stock back</td></tr></tbody></table>

Old orders without a shipper keep the old rules.

### Errors

<table id="bkmrk-code-status-when-bef-2"><thead><tr><th>Code</th><th>Status</th><th>When</th><th>Before / After</th></tr></thead><tbody><tr><td>`CANCEL_NOT_ALLOWED`</td><td>409</td><td>after those windows ("You can switch to pickup instead" / "Contact support to cancel")</td><td>NEW (was `FULFILLMENT_STATE`)</td></tr><tr><td>`INFORM_BUYER_FIRST`</td><td>409</td><td>seller without `informedBuyer: true`</td><td>NEW</td></tr><tr><td>`INSTALLMENT_ORDER`</td><td>409</td><td>an installment order — cancel the agreement instead</td><td>NEW</td></tr></tbody></table>

### App to do

- [ ]  Buyer: show Cancel only while `PLACED` or while "We're finding a new shipper" / a decision shows; otherwise "Collect it myself instead".
- [ ]  Seller: hide Cancel on delivery orders from Ready on; send `informedBuyer`.
- [ ]  Installment order: the Cancel button calls the agreement cancel (§6.2).

---

## 5.4 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Old ship / confirm-delivery / regenerate-code

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/e-commerce/orders/{orderId}/ship` · `/confirm-delivery` · `/regenerate-code`

<table id="bkmrk-change-breaking-%E2%80%94-re"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>BREAKING — refused for most new orders</td></tr><tr><td>**Impact**</td><td>Must update</td></tr><tr><td>**Reference**</td><td>§25, §40</td></tr></tbody></table>

<table id="bkmrk-order-before-after-p"><thead><tr><th>Order</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>Pickup order</td><td>seller ships, buyer confirms with the code</td><td>**409 `USE_PICKUP_FLOW`** — use the shipping order actions</td></tr><tr><td>Order a shipper delivers</td><td>—</td><td>**409 `SHIPPER_DELIVERS`**</td></tr><tr><td>Old order without a shipper</td><td></td><td>unchanged (old flow)</td></tr></tbody></table>

`POST /ship` no longer takes or returns `trackingNumber` (it was a fake "TRACK-…").

### App to do

- [ ]  For pickup and shipper orders, stop calling these three; use the buttons from shipping doc §C.

---

## 5.5 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Delivery code — 4 digits, own SMS, 24 h, "I lost my code"

**Endpoint**: `/orders/{orderId}/ship`, `/confirm-delivery`, `/regenerate-code` (old orders) — and the same code rules for the shipping `…/code` action.

<table id="bkmrk-change-breaking-impa"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>BREAKING</td></tr><tr><td>**Impact**</td><td>Must update</td></tr><tr><td>**Reference**</td><td>§20, §26</td></tr></tbody></table>

<table id="bkmrk-before-after-length-"><thead><tr><th></th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>Length</td><td>6 digits</td><td>**4 digits** (`confirmationCode` must match `^[0-9]{4}$`)</td></tr><tr><td>Lifetime</td><td>30 days</td><td>**24 hours**; a new code kills the old one; max **5 per order per 24 h**</td></tr><tr><td>Delivery of the code</td><td>inside the "Order shipped" email / SMS / push</td><td>its **own SMS** to the receiver; the bell says "Your delivery code was sent by SMS", never the code</td></tr><tr><td>Wrong code</td><td>HTTP 400 with prose</td><td>409 coded refusal, `details.triesLeft`</td></tr><tr><td>Old codes</td><td></td><td>gone — a buyer with a SHIPPED order taps "I lost my code"</td></tr></tbody></table>

`POST /regenerate-code` response — fields added (old ones stay):

<table id="bkmrk-beforeafter-%7B-%22order-1"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{ "orderId": "…",
  "orderNumber": "ORD-2026-94070",
  "codeSent": true,
  "destination": "email",
  "codeExpiresAt": null,
  "maxAttempts": 5 }

```

</td><td>```json
{ "orderId": "…",
  "orderNumber": "ORD-2026-94070",
  "codeSent": true,
  "destination": "sms",
  "codeExpiresAt": "2026-10-18T05:03:05",
  "maxAttempts": 5,
  "message": "New code sent by SMS to +255*****2944",
  "code": "4821",
  "sentTo": "+255*****2944" }

```

</td></tr></table>

`code` is shown **once**, on that screen; it is never stored readable, so it cannot be shown again.

### Errors

<table id="bkmrk-code-status-when-bef-3"><thead><tr><th>Code</th><th>Status</th><th>When</th><th>Before / After</th></tr></thead><tbody><tr><td>`CODE_WRONG`</td><td>409</td><td>wrong code; `details.triesLeft`</td><td>NEW (was 400)</td></tr><tr><td>`CODE_LOCKED`</td><td>409</td><td>after 5 wrong tries — even the right code, until a new one is asked for</td><td>NEW</td></tr><tr><td>`CODE_NOT_ACTIVE`</td><td>409</td><td>no active code, or already used</td><td>NEW</td></tr><tr><td>`CODE_EXPIRED`</td><td>409</td><td>older than 24 h</td><td>NEW</td></tr><tr><td>`CODE_LIMIT`</td><td>409</td><td>more than 5 new codes in 24 h</td><td>NEW</td></tr></tbody></table>

### App to do

- [ ]  4-digit input; show `triesLeft`; on `CODE_LOCKED` / `CODE_EXPIRED` offer "I lost my code".
- [ ]  Order screen: "Code sent by SMS to +255•••2944 · valid until …" from `fulfillment.code`.
- [ ]  "I lost my code" → show `code` big, once. Never cache it.

---

# 6. Installments

**What changed in this service**: the agreement carries the fulfillment like an order; "ships now" plans can be delivered; installment orders are cancelled only through their agreement; and two money bugs are fixed.

<table id="bkmrk-change-method-endpoi-5"><thead><tr><th>Change</th><th>Method</th><th>Endpoint</th><th>One line</th><th>App</th></tr></thead><tbody><tr><td>CHANGED</td><td>GET</td><td>installment agreement</td><td>`shippingAddress` → `fulfillment`</td><td>should update</td></tr><tr><td>CHANGED</td><td>POST</td><td>`/e-commerce/installments/agreements/{id}/cancel`</td><td>also cancels the order and refunds every part</td><td>no change</td></tr><tr><td>FIX</td><td>POST</td><td>`/installments/agreements/{id}/payments/{paymentId}/pay`</td><td>instalments after the down payment can be paid</td><td>no change</td></tr><tr><td>FIX</td><td>GET / POST</td><td>`/installments/agreements/{id}/early-payoff`</td><td>no "/ by zero" on 0 % plans</td><td>no change</td></tr><tr><td>FIX</td><td>—</td><td>confirming delivery</td><td>releases every instalment held so far to the seller</td><td>no change</td></tr></tbody></table>

## 6.1 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Agreement — `fulfillment`, layaway, cancel

<table id="bkmrk-field-%2F-rule-before-"><thead><tr><th>Field / rule</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>`shippingAddress`</td><td>always empty</td><td>**removed**</td></tr><tr><td>`fulfillment`</td><td>—</td><td>**added** (same object as orders)</td></tr><tr><td>Layaway (`AFTER_PAYMENT`)</td><td></td><td>refuses delivery at checkout (`LAYAWAY_DELIVERY_LATER`); when paid off the order is pickup and the buyer may choose delivery from the order</td></tr><tr><td>`INSTALLMENT_AGREEMENT_COMPLETED`</td><td></td><td>gains `nextStep` ("Collect it at the shop, or choose delivery in your order." for layaway)</td></tr><tr><td>Agreement cancel</td><td></td><td>when the order exists it is cancelled too and **everything** refunded (down payment, delivery, instalments) — refused once the parcel left the shop</td></tr><tr><td>Order cancel on an installment order</td><td>allowed (left the agreement ACTIVE)</td><td>refused `INSTALLMENT_ORDER` everywhere</td></tr></tbody></table>

**Reference**: §17, §56, §69

## 6.2 <span style="background-color: #20c997; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">FIX</span> Installment money

<table id="bkmrk-before-%28wrong%29-after-1"><thead><tr><th>Before (wrong)</th><th>After (correct)</th></tr></thead><tbody><tr><td>every instalment after the down payment failed to pay (database error)</td><td>pays normally</td></tr><tr><td>confirming delivery released only the down payment + delivery; held instalments stayed held for good</td><td>every instalment held so far is released; one paid after confirmation goes to the seller at once</td></tr><tr><td>early payoff on a 0 % plan crashed "/ by zero"</td><td>works</td></tr><tr><td>a "ships now" plan sometimes never got its order</td><td>always gets it</td></tr></tbody></table>

**Reference**: §56, §57, §70, §71

### App to do

- [ ]  Offer pickup / delivery in the installment sheet for "ships now" plans; layaway: "choose delivery after the last payment".
- [ ]  Installment order: Cancel = `POST /e-commerce/installments/agreements/{agreementId}/cancel`.

---

# 7. Group purchase

## 7.1 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Group checkout with delivery

<table id="bkmrk-rule-before-after-gr"><thead><tr><th>Rule</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>`GROUP_PURCHASE` with DELIVERY</td><td>not possible</td><td>accepted — `byShop`, `deliveries`, `dropoff` like a direct buy</td></tr><tr><td>Member totals (`totalPaid`, `amountPaid`)</td><td></td><td>items + tax only — the same for every member; each member's delivery is on their own session / order</td></tr><tr><td>Leaving (`POST /group-purchases/{id}/withdraw`) / group runs out of time</td><td>refund the items</td><td>refund **items and delivery**</td></tr><tr><td>Moving a payment to another group</td><td></td><td>keeps its delivery choice</td></tr><tr><td>Changing the delivery while the group fills</td><td></td><td>not possible; once the order exists the usual changes apply</td></tr></tbody></table>

**Reference**: §55

### App to do

- [ ]  The group checkout sheet offers pickup / delivery like a direct buy; the group screen keeps showing the group price.

---

# 8. Wallet &amp; transactions

## 8.1 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Transaction history titles

<table id="bkmrk-where-before-after-b"><thead><tr><th>Where</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>Buyer, split payment</td><td>"N sellers"</td><td>"N parts"</td></tr><tr><td>Shipper payout</td><td>—</td><td>"Delivery Earnings" ("Payment received for delivery"); type still `SALE`</td></tr><tr><td>Extra delivery payment after ordering</td><td>—</td><td>"Delivery Payment"</td></tr><tr><td>Money back (cheaper shipper, switch to pickup)</td><td>—</td><td>"Refund Received"</td></tr></tbody></table>

Known, not changed: a refund also writes "Sale Refund Issued" (debit) into the payee's history although the payee never received that money. **Reference**: §34, §40, §41

---

# 9. Events

**What changed in this service**: a venue is a **pin** turned into ward / district / region (like a shop); an in-person event needs that pin to publish. Donation tickets can have a target and show progress.

<table id="bkmrk-change-method-endpoi-6"><thead><tr><th>Change</th><th>Method</th><th>Endpoint</th><th>One line</th><th>App</th></tr></thead><tbody><tr><td>CHANGED</td><td>PATCH</td><td>`/e-events/drafts/{draftId}/location`</td><td>pin outside Tanzania → `OUTSIDE_COVERAGE`</td><td>should update</td></tr><tr><td>BREAKING</td><td>PATCH</td><td>`/e-events/{eventId}/publish`, `/e-events/{eventId}/published/reveal-location`</td><td>in-person / hybrid needs a pin</td><td>must update</td></tr><tr><td>CHANGED</td><td>GET</td><td>event responses</td><td>`venue` gains `ward`, `areaLabel`, `matchType`</td><td>should update</td></tr><tr><td>CHANGED</td><td>POST / PUT / PATCH</td><td>ticket create / draft update / published update</td><td>optional `donationTarget`</td><td>to use</td></tr><tr><td>CHANGED</td><td>GET</td><td>ticket details, ticket list, event `tickets`</td><td>`donation` progress on donation tickets</td><td>should update</td></tr></tbody></table>

## 9.1 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Venue — area from the pin

**Endpoint**: <span style="background-color: #17a2b8; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span> `{base_url}/e-events/drafts/{draftId}/location` · event responses

<table id="bkmrk-field-before-after-r-1"><thead><tr><th>Field</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>request `venue`</td><td></td><td>unchanged; `venue.coordinates` outside Tanzania's wards → `OUTSIDE_COVERAGE`</td></tr><tr><td>response `venue.ward`, `venue.areaLabel`, `venue.matchType`</td><td>—</td><td>**added** (null without a pin)</td></tr><tr><td>`locationSummary`, share preview, ticket / booking location, event on a post or clip</td><td>typed address</td><td>the area when no address was typed</td></tr></tbody></table>

```json
"venue": { "name": "Mlimani City Hall", "address": null, "coordinates": { "latitude": -6.77, "longitude": 39.22 },
           "areaLabel": "Mikocheni, Kinondoni, Dar es Salaam", "matchType": "CONTAINED", "ward": { "…": "…" } }

```

**Reference**: §78

## 9.2 <span style="background-color: #dc3545; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">BREAKING</span> Publish / reveal location needs a pin

**Endpoint**: <span style="background-color: #17a2b8; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span> `{base_url}/e-events/{eventId}/publish` · `{base_url}/e-events/{eventId}/published/reveal-location`

<table id="bkmrk-before-after-an-in_p"><thead><tr><th>Before</th><th>After</th></tr></thead><tbody><tr><td>an `IN_PERSON` / `HYBRID` event published with a venue name only</td><td>refused 422 "Drop a pin on the map for the venue" (`details.stage` `LOCATION_DETAILS`) without `coordinates`</td></tr></tbody></table>

TBA and online events unchanged; drafts can still be saved without a pin.

### App to do

- [ ]  Venue step: the same pin screen as the shop location (resolve, show `areaLabel`, Confirm off when not covered); the address field stays optional ("directions").

## 9.3 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Donation target and progress

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `{base_url}/e-events/tickets/{eventId}` · <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/e-events/tickets/{ticketId}` · <span style="background-color: #17a2b8; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PATCH</span> `{base_url}/e-events/tickets/{ticketId}/published`

<table id="bkmrk-change-changed-%E2%80%94-opt"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>CHANGED — optional field in, optional block out</td></tr><tr><td>**Impact**</td><td>To use (the progress bar)</td></tr><tr><td>**Reference**</td><td>§79</td></tr></tbody></table>

### Request

<table id="bkmrk-field-before-after-n-9"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`donationTarget`</td><td>—</td><td>**added**, optional</td><td>&gt; 0, at most 10 digits + 2 decimals; **donation tickets only**</td></tr></tbody></table>

### Response (ticket details, ticket list, `tickets` in the event response)

<table id="bkmrk-field-before-after-n-10"><thead><tr><th>Field</th><th>Before</th><th>After</th><th>Note</th></tr></thead><tbody><tr><td>`donation`</td><td>—</td><td>**added**</td><td>`{ target, raised, donations }` on donation tickets; `null` on others; `target` null when not set</td></tr></tbody></table>

<table id="bkmrk-beforeafter-%7B-%22name%22"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{ "name": "Support the choir",
  "ticketPricingType": "DONATION",
  "price": 0.00 }

```

</td><td>```json
{ "name": "Support the choir",
  "ticketPricingType": "DONATION",
  "price": 0.00,
  "donation": { "target": 500000.00,
                "raised": 210000.00,
                "donations": 11 } }

```

</td></tr></table>

- `raised` = confirmed donations only (cancelled / refunded bookings do not count). The organiser can set or raise the target after publishing.

### Errors

<table id="bkmrk-message-status-when-"><thead><tr><th>Message</th><th>Status</th><th>When</th></tr></thead><tbody><tr><td>"A donation target can only be set on a donation ticket"</td><td>422</td><td>`donationTarget` on a paid / free ticket</td></tr></tbody></table>

### App to do

- [ ]  Organiser: optional "Target" field on donation tickets.
- [ ]  Event page: progress bar from `donation.raised` / `donation.target` (hide the bar when `target` is null; still show `raised`).

---

# 10. Profile &amp; account

## 10.1 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Profile cover photo

**Endpoint**: <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `{base_url}/profile/update` · <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/profile/me`, `/profile/id/{userId}`, `/profile/u/{username}`

<table id="bkmrk-change-changed-%E2%80%94-fie-1"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>**Change**</td><td>CHANGED — field in, field out</td></tr><tr><td>**Impact**</td><td>To use</td></tr><tr><td>**Reference**</td><td>§79</td></tr></tbody></table>

<table id="bkmrk-where-field-before-a"><thead><tr><th>Where</th><th>Field</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>`PUT /profile/update`</td><td>`coverPhotoFileId`</td><td>—</td><td>**added**, optional — a File Thunder upload with context **`COVER_PHOTO`**</td></tr><tr><td>profile responses</td><td>`coverMedia`</td><td>—</td><td>**added** — same shape as `profileMedia` (`fileId`, `status`, `variants`, `mimeType`), null when not set</td></tr></tbody></table>

<table id="bkmrk-beforeafter-%7B-%22usern"><tr><th>Before</th><th>After</th></tr><tr><td>```json
{ "userName": "joshuasakweli",
  "profileMedia": { "fileId": "…", "status": "READY",
                    "variants": { "thumb": "https://…/thumb.webp" } } }

```

</td><td>```json
{ "userName": "joshuasakweli",
  "profileMedia": { "fileId": "…", "status": "READY",
                    "variants": { "thumb": "https://…/thumb.webp" } },
  "coverMedia":   { "fileId": "…", "status": "READY",
                    "variants": { "medium": "https://…/medium.webp",
                                  "large": "https://…/large.webp" } } }

```

</td></tr></table>

**Errors**: a file uploaded with another context → "File was not uploaded as a cover photo"; someone else's file → 403.

### App to do

- [ ]  Profile banner: upload as `COVER_PHOTO`, send `coverPhotoFileId`, show `coverMedia`.

## 10.2 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> New-device sign-in alert

`AUTH_NEW_DEVICE_LOGIN` is now sent by **password, SMS-code and Google** sign-in (was password only) and never for an account's first device. Its data gains the details the app can show in the bell item:

<table id="bkmrk-key-before-after-dev"><thead><tr><th>Key</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>`device.name`, `device.platform`, `ipAddress`</td><td>yes</td><td>unchanged</td></tr><tr><td>`device.type`</td><td>—</td><td>`Phone` / `Tablet` / `Computer`</td></tr><tr><td>`device.browser`</td><td>—</td><td>e.g. `Chrome`, `Safari`, `NexGate app`</td></tr><tr><td>`device.os`</td><td>—</td><td>`Windows`, `macOS`, `iOS`, `Android`, `Linux`, `ChromeOS`</td></tr><tr><td>`device.location`, `location`</td><td>—</td><td>e.g. `"Dar es Salaam, TZ"` (`"Unknown location"` when not found)</td></tr><tr><td>`timestamp`</td><td>—</td><td>e.g. `"Oct 25, 2026 at 8:15 AM EAT"`</td></tr></tbody></table>

Browser and system come from the `User-Agent` header — no new request fields. Email, push and SMS now show them. **Reference**: §79

---

# 11. Interests

## 11.1 <span style="background-color: #fd7e14; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">CHANGED</span> Category management is admin only

<table id="bkmrk-endpoint-before-afte"><thead><tr><th>Endpoint</th><th>Before</th><th>After</th></tr></thead><tbody><tr><td>`POST /interests/categories`, `PUT /{categoryId}`, `DELETE /{categoryId}`, `PATCH /{categoryId}/toggle-active`, `GET /{categoryId}/usage`</td><td>any signed-in user</td><td>**SUPER\_ADMIN / STAFF\_ADMIN** only (403 for others)</td></tr><tr><td>`GET /interests/categories/all`</td><td>public</td><td>unchanged</td></tr></tbody></table>

**Picking interests (unchanged, for the onboarding screen):** load `GET /interests/categories/all`, then save at least 3 of those ids with `POST /onboarding/secondary/interests` `{ "interestIds": [ … ] }`. One unknown or switched-off id → 404 "Some categories are inactive or do not exist" and nothing is saved — always send ids from the list you just loaded. The categories are created by the system at startup. **Reference**: §79

---

# 12. Chat

## 12.1 <span style="background-color: #20c997; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">FIX</span> Chat avatars and group icons are real links

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/chat/conversations` (`display.avatar`) · group responses (`iconMedia`: create, get, `PUT /chat/groups/{conversationId}/icon`)

<table id="bkmrk-before-%28wrong%29-after-2"><thead><tr><th>Before (wrong)</th><th>After (correct)</th></tr></thead><tbody><tr><td>`variants` held storage paths — `"thumb": "messages/4a8c…/thumb.webp"` — which no image can load</td><td>`"thumb": "https://…/thumb.webp"` — full links; same object shape</td></tr></tbody></table>

Applies to groups, people and shops in the chat list. An icon set while its upload was still processing now upgrades to its final images (it stayed stuck before). A failed icon upload now says "Upload failed" instead of "still in progress".

The chat doc said `avatar` was a plain link string — it is the object `{ fileId, status, mimeType, variants }`. **Reference**: §80

### App to do

- [ ]  Read the image from `display.avatar.variants.thumb` / `iconMedia.variants.thumb` (no prefixing).
- [ ]  On `CHAT_GROUP_UPDATED` (§15) refresh the chat list row and the group header.

---

# 13. Digital downloads

## 13.1 <span style="background-color: #20c997; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">FIX</span> Files keep their name and type

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `{base_url}/e-commerce/digital-files/my-downloads/{accessId}/url` — then the app downloads the returned `url`

<table id="bkmrk-before-%28wrong%29-after-3"><thead><tr><th>Before (wrong)</th><th>After (correct)</th></tr></thead><tbody><tr><td>the file arrived named `original`, type `application/octet-stream` — devices could not open it, and reading it as text corrupted it (and roughly doubled its size)</td><td>the link answers `Content-Disposition: attachment; filename="notes pedi.zip"` and the real `Content-Type` (`application/zip`, `video/mp4`, …)</td></tr></tbody></table>

Response body unchanged (`url`, `expiresInSeconds`). Works for files already uploaded. **Reference**: §80

### App to do

- [ ]  Download the `url` as **bytes** and stream it to a file; never read the body as text / string.
- [ ]  Use the filename from `Content-Disposition` (or `fileName` from the order downloads list).

---

# 14. Admin dashboard (existing screens)

<table id="bkmrk-change-method-endpoi-7"><thead><tr><th>Change</th><th>Method</th><th>Endpoint</th><th>One line</th></tr></thead><tbody><tr><td>NEW</td><td>PUT</td><td>`/admin/shops/reviews/{reviewId}/status`</td><td>moderate a shop review: `{ "status": "HIDDEN", "reason": "…" }` (SUPER\_ADMIN, reason required, audit-logged) → `{ reviewId, shopId, status }`</td></tr><tr><td>CHANGED</td><td>GET</td><td>fees, current + history</td><td>lists a new fee type `DELIVERY_COMMISSION` (PERCENTAGE)</td></tr><tr><td>CHANGED</td><td>GET</td><td>`/api/admin/reconciliation/position`</td><td>gains `owedToProviders`, `campaignMoney`, `ownerTopUps`; `expectedSelcomFloat` includes them</td></tr><tr><td>CHANGED</td><td>GET</td><td>`/api/admin/reconciliation/trial-balance`</td><td>new lines `PROVIDER`, `CAMPAIGN_BUDGET`, `CAMPAIGN_POT`</td></tr><tr><td>CHANGED</td><td>—</td><td>interest categories</td><td>management is admin only (§11)</td></tr></tbody></table>

**Reference**: §30, §31, §58, §64

> New admin endpoints for shipping, Bolt, campaigns, the operations board, reports and the audit log → shipping doc §K and campaigns doc §7–§8.

---

# 15. Notifications

New types are listed so the bell list and push taps can handle them; each opens the screen in its `targetType` / `targetId`. **Four new targets**: `SHIPPING_JOB`, `SHIPPER_BUSINESS`, `SHIPPING_CAMPAIGN`, `ADMIN_SHIPPING_BOARD` — an app that does not know a target yet opens the bell list.

<table id="bkmrk-change-type-to-when-"><thead><tr><th>Change</th><th>Type</th><th>To</th><th>When</th><th>Opens (`targetType`)</th><th>App</th></tr></thead><tbody><tr><td>NEW</td><td>`HANDOVER_CODE`</td><td>receiver</td><td>a pickup / delivery code was sent (in-app + SMS; never the code in-app)</td><td>`ORDER_TRACKING`</td><td>bell item</td></tr><tr><td>NEW</td><td>`ORDER_ACCEPTED`</td><td>buyer</td><td>seller accepted (parcel number)</td><td>`ORDER_TRACKING`</td><td>refresh the order</td></tr><tr><td>NEW</td><td>`ORDER_ACCEPT_REMINDER`</td><td>seller</td><td>2 h before the accept deadline</td><td>`SHOP_ORDER`</td><td></td></tr><tr><td>NEW</td><td>`PICKUP_READY`</td><td>buyer</td><td>pickup order ready (place, collect-by)</td><td>`ORDER_TRACKING`</td><td></td></tr><tr><td>NEW</td><td>`PICKUP_REMINDER`</td><td>buyer</td><td>not collected: day 7 and 12</td><td>`ORDER_TRACKING`</td><td></td></tr><tr><td>NEW</td><td>`PICKUP_LAST_DAY`</td><td>buyer (+ SMS)</td><td>24 h before the collect deadline</td><td>`ORDER_TRACKING`</td><td></td></tr><tr><td>NEW</td><td>`SHIPPER_FOUND`</td><td>buyer</td><td>every shipper accepted / Bolt rider assigned</td><td>`ORDER_TRACKING`</td><td>refresh</td></tr><tr><td>NEW</td><td>`SHIPPER_CHANGED`</td><td>buyer</td><td>automatic swap to an equal or cheaper shipper</td><td>`ORDER_TRACKING`</td><td>refresh</td></tr><tr><td>NEW</td><td>`DELIVERY_DECISION_NEEDED`</td><td>buyer</td><td>the buyer must choose (costs more, nobody found, …)</td><td>`ORDER_TRACKING`</td><td>open the decision</td></tr><tr><td>NEW</td><td>`PARCEL_AT_STATION`</td><td>buyer</td><td>the parcel reached the buyer's station</td><td>`ORDER_TRACKING`</td><td></td></tr><tr><td>NEW</td><td>`RIDER_COMING`</td><td>seller (+ SMS)</td><td>shipper heading to the shop / Bolt rider (plate to check)</td><td>`SHOP_ORDER`</td><td></td></tr><tr><td>NEW</td><td>`PARCEL_REFUSED`</td><td>seller</td><td>badly packed / Bolt left without the parcel</td><td>`SHOP_ORDER`</td><td>refresh</td></tr><tr><td>NEW</td><td>`JOB_OFFER`</td><td>shipper</td><td>a new job offer</td><td>`SHIPPING_JOB`</td><td></td></tr><tr><td>NEW</td><td>`JOB_CANCELLED`</td><td>shipper</td><td>an offer or accepted job was taken away</td><td>`SHIPPING_JOB`</td><td>refresh</td></tr><tr><td>NEW</td><td>`DELIVERY_EARNINGS`</td><td>shipper</td><td>delivery money released</td><td>`TRANSACTION`</td><td>refresh</td></tr><tr><td>NEW</td><td>`SHIPPER_NEW_REVIEW`</td><td>shipper</td><td>new review</td><td>`SHIPPER_BUSINESS`</td><td></td></tr><tr><td>NEW</td><td>`SHIPPER_REVIEW_REPLY`</td><td>reviewer</td><td>the shipper replied (in-app)</td><td>`SHIPPER_BUSINESS`</td><td></td></tr><tr><td>NEW</td><td>`SHIPPER_STANDING`</td><td>shipper owner</td><td>warning / automatic pause / suspension</td><td>`SHIPPER_BUSINESS`</td><td>banner</td></tr><tr><td>NEW</td><td>`SHIPPER_DOCUMENT_EXPIRING`</td><td>shipper owner</td><td>a KYC document expires in 14 / 3 days</td><td>`SHIPPER_BUSINESS`</td><td></td></tr><tr><td>NEW</td><td>`SHIPPING_CAMPAIGN_RAN_OUT`</td><td>campaign runner</td><td>a campaign ran out</td><td>`SHIPPING_CAMPAIGN`</td><td></td></tr><tr><td>NEW</td><td>`SHIPPING_CAMPAIGN_ENDED`</td><td>campaign runner</td><td>a campaign ended (what it paid)</td><td>`SHIPPING_CAMPAIGN`</td><td></td></tr><tr><td>NEW</td><td>`SHIPPING_ADMIN_DIGEST`</td><td>staff + super admins</td><td>07:30 when anything is stuck</td><td>`ADMIN_SHIPPING_BOARD`</td><td>admin app</td></tr><tr><td>NEW</td><td>`CHAT_GROUP_UPDATED`</td><td>other group members (in-app only)</td><td>the group photo changed; data `conversationId`, `group.name`, `change: "ICON"`</td><td>`CONVERSATION`</td><td>refresh the chat row + header</td></tr><tr><td>CHANGED</td><td>`ORDER_AWAITING_CONFIRM`</td><td>buyer</td><td>now sent **when a delivery is delivered**: "tap Received so the seller gets paid"</td><td>`ORDER`</td><td></td></tr><tr><td>CHANGED</td><td>`ORDER_DELIVERED`</td><td>was: buyer at completion → now: **seller at delivery** ("You are paid when they confirm")</td><td></td><td>`SHOP_ORDER`</td><td>move the handler</td></tr><tr><td>CHANGED</td><td>`ORDER_SHIPPED`</td><td>buyer</td><td>no carrier, tracking number or code; no SMS</td><td>`ORDER_TRACKING`</td><td></td></tr><tr><td>CHANGED</td><td>`AUTH_NEW_DEVICE_LOGIN`</td><td>user</td><td>all sign-in methods; new data keys (§10.2)</td><td>`ACTIVE_SESSIONS`</td><td>show the details</td></tr><tr><td>CHANGED</td><td>`INSTALLMENT_AGREEMENT_COMPLETED`</td><td>buyer</td><td>gains `nextStep` for layaway</td><td>`AGREEMENT`</td><td></td></tr><tr><td>FIX</td><td>`ESCROW_RELEASED_TO_SELLER`</td><td>seller</td><td>was blank (" released to your wallet / From order "); now amount + order number</td><td>`TRANSACTION`</td><td></td></tr><tr><td>FIX</td><td>`ESCROW_REFUNDED`, `ORDER_CANCELLED`</td><td>buyer</td><td>blank amount / order number / reason filled</td><td></td><td></td></tr><tr><td>FIX</td><td>`DIGITAL_PRODUCT_READY`</td><td>buyer</td><td>said only " is ready"; now the product name ("Notes Pedi and 2 more") and days the link lasts; sent only after access exists</td><td>`DOWNLOAD`</td><td></td></tr><tr><td>FIX</td><td>order "delivered" to the buyer</td><td>buyer</td><td>crashed when the buyer had no email</td><td></td><td></td></tr></tbody></table>

---

# 16. Error codes index

All HTTP 409, `data.code`; some carry `data.details`.

<table id="bkmrk-code-change-service-"><thead><tr><th>Code</th><th>Change</th><th>Service</th><th>Endpoint(s)</th><th>Meaning</th></tr></thead><tbody><tr><td>`SHOP_LOCATION_REQUIRED`</td><td>NEW</td><td>Checkout</td><td>create session</td><td>a physical product from a shop with no location</td></tr><tr><td>`SHOP_CLOSED`</td><td>NEW</td><td>Checkout</td><td>create session</td><td>shop paused (stop orders), suspended or closed; `details.reopensAt`</td></tr><tr><td>`FULFILLMENT_REQUIRED` / `DROPOFF_REQUIRED` / `DROPOFF_INVALID`</td><td>NEW</td><td>Checkout</td><td>create / patch session</td><td>missing choice / missing drop-off / not exactly one drop-off source</td></tr><tr><td>`RECEIVER_INCOMPLETE`</td><td>NEW</td><td>Checkout</td><td>create / patch session</td><td>receiver name and phone go together</td></tr><tr><td>`DELIVERY_NOT_AVAILABLE`</td><td>NEW</td><td>Checkout</td><td>create session</td><td>no shipper covers the address</td></tr><tr><td>`DELIVERY_PRICE_CHANGED` / `DELIVERY_OPTION_GONE`</td><td>NEW</td><td>Checkout</td><td>create session, process / retry payment</td><td>held price changed / shipper can't take it; show before → after</td></tr><tr><td>`CAMPAIGN_ENDED`</td><td>NEW</td><td>Checkout</td><td>process payment</td><td>a delivery campaign ended since checkout</td></tr><tr><td>`LAYAWAY_DELIVERY_LATER`</td><td>NEW</td><td>Checkout</td><td>create session (installment)</td><td>layaway: choose delivery after the last payment</td></tr><tr><td>`HOURS_INVALID`</td><td>NEW</td><td>Shops</td><td>`PUT /shops/{shopId}/hours`</td><td>a special day twice, or open with no hours</td></tr><tr><td>`SHOP_NOT_PAUSABLE`</td><td>NEW</td><td>Shops</td><td>`PUT /shops/{shopId}/pause`</td><td>only an ACTIVE (or already paused) shop can be paused</td></tr><tr><td>`OUTSIDE_COVERAGE`</td><td>NEW</td><td>Checkout, Events</td><td>`saveAs` pin, venue pin</td><td>pin outside Tanzania's wards</td></tr><tr><td>`LABEL_ALREADY_USED` / `ADDRESS_LIMIT_REACHED`</td><td>NEW</td><td>Checkout</td><td>`saveAs` pin</td><td>second HOME / WORK; 11th address</td></tr><tr><td>`USE_PICKUP_FLOW`</td><td>NEW</td><td>Orders</td><td>ship / confirm-delivery / regenerate-code</td><td>pickup order — use the shipping actions</td></tr><tr><td>`SHIPPER_DELIVERS`</td><td>NEW</td><td>Orders</td><td>ship / confirm-delivery / regenerate-code</td><td>a shipper delivers this order</td></tr><tr><td>`CODE_WRONG` / `CODE_LOCKED` / `CODE_NOT_ACTIVE`</td><td>NEW (was 400)</td><td>Orders</td><td>confirm-delivery</td><td>wrong code (`details.triesLeft`) / locked / none active</td></tr><tr><td>`CODE_EXPIRED` / `CODE_LIMIT`</td><td>NEW</td><td>Orders</td><td>confirm-delivery / regenerate-code</td><td>older than 24 h / more than 5 in 24 h</td></tr><tr><td>`CANCEL_NOT_ALLOWED`</td><td>NEW (was `FULFILLMENT_STATE`)</td><td>Orders</td><td>cancel</td><td>outside the cancel window</td></tr><tr><td>`INFORM_BUYER_FIRST`</td><td>NEW</td><td>Orders</td><td>cancel (seller)</td><td>send `informedBuyer: true`</td></tr><tr><td>`INSTALLMENT_ORDER`</td><td>NEW</td><td>Orders</td><td>cancel</td><td>cancel the installment agreement instead</td></tr></tbody></table>

The codes of the new location, shipping and campaign endpoints are in their docs (location §Part 3, shipping §4.5, campaigns §Part 3).

---

# 17. App checklist by screen

<table id="bkmrk-screen-what-to-chang"><thead><tr><th>Screen</th><th>What to change</th><th>Sections</th></tr></thead><tbody><tr><td>Shop create / edit (seller)</td><td>drop location inputs; add the Shop location (pin) step</td><td>§1.2</td></tr><tr><td>Shop page / lists / search</td><td>`location`, Directions, Call; `availability` (open now / paused); Buy off when not accepting</td><td>§1.3, §1.4</td></tr><tr><td>Shop settings (seller)</td><td>opening hours screen; pause / reopen</td><td>§1.6, §1.7</td></tr><tr><td>Shop reviews</td><td>show `replyText`</td><td>§1.5</td></tr><tr><td>Product page</td><td>"Pickup at …" + Directions from `shopLocation`</td><td>§2.2</td></tr><tr><td>Product form (seller)</td><td>"Bulky / heavy item" switch</td><td>§2.3</td></tr><tr><td>Cart</td><td>group by `shops`, delivery per shop, `notice`, `nudge`, "Used before", ticks, `selectedTotal`, change messages</td><td>§3.2–§3.4</td></tr><tr><td>Checkout</td><td>pickup / delivery per shop, drop-off, receiver, note; send `fulfillment`; price-changed codes</td><td>§4.2–§4.4</td></tr><tr><td>Payment result</td><td>`sellerAmount` + `deliveryAmount`, `parts`</td><td>§4.4</td></tr><tr><td>Order detail (buyer + seller)</td><td>`fulfillment` status, steps, times, shippers' phones, Bolt rider, code status, "I lost my code"</td><td>§5.2, §5.5</td></tr><tr><td>Order lists</td><td>`fulfillmentType` badge, `fulfillmentStatus`</td><td>§5.2</td></tr><tr><td>Order cancel</td><td>new windows; installment → agreement cancel</td><td>§5.3, §6.1</td></tr><tr><td>Delivery code entry</td><td>4 digits, `triesLeft`, locked / expired</td><td>§5.5</td></tr><tr><td>Installment sheet / agreement</td><td>delivery for "ships now"; layaway text; `fulfillment`</td><td>§6.1</td></tr><tr><td>Group purchase sheet</td><td>pickup / delivery</td><td>§7.1</td></tr><tr><td>Wallet history</td><td>new titles</td><td>§8.1</td></tr><tr><td>Event venue step (organiser)</td><td>pin screen; pin required to publish</td><td>§9.1, §9.2</td></tr><tr><td>Donation ticket (organiser + event page)</td><td>`donationTarget`; progress bar from `donation`</td><td>§9.3</td></tr><tr><td>Profile</td><td>cover banner (`COVER_PHOTO`, `coverMedia`)</td><td>§10.1</td></tr><tr><td>Interests (onboarding)</td><td>send ids from the loaded list</td><td>§11.1</td></tr><tr><td>Chat list / group header</td><td>avatars from `variants`; refresh on `CHAT_GROUP_UPDATED`</td><td>§12.1</td></tr><tr><td>Digital downloads</td><td>download as bytes, keep the filename</td><td>§13.1</td></tr><tr><td>Bell list / push</td><td>the new types and four new targets</td><td>§15</td></tr><tr><td>Admin dashboard</td><td>review moderation, `DELIVERY_COMMISSION`, reconciliation lines, admin-only interests</td><td>§14</td></tr></tbody></table>